title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Rotate matrix by 45 degrees - GeeksforGeeks
05 Jan, 2022 Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix. Examples: Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5 9 6 8 Input: N = 4, mat[][] = {{2, 5, 7, 2}, {9, 1, 4, 3}, {5, 8, 2, 3}, {6, 4, 6, 3}} Output: 2 9 5 5 1 76 8 4 2 4 2 3 6 3 3 Follow the steps given below in order to solve the problem: Store the diagonal elements in a list using a counter variable.Print the number of spaces required to make the output look like the desired pattern.Print the list elements after reversing the list.Traverse through only diagonal elements to optimize the time taken by the operation. Store the diagonal elements in a list using a counter variable. Print the number of spaces required to make the output look like the desired pattern. Print the list elements after reversing the list. Traverse through only diagonal elements to optimize the time taken by the operation. Below is the implementation of the above approach: C++ Java Python3 C# // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to rotate matrix by 45 degreevoid matrix(int n, int m, vector<vector<int>> li){ // Counter Variable int ctr = 0; while (ctr < 2 * n - 1) { for(int i = 0; i < abs(n - ctr - 1); i++) { cout << " "; } vector<int> lst; // Iterate [0, m] for(int i = 0; i < m; i++) { // Iterate [0, n] for(int j = 0; j < n; j++) { // Diagonal Elements // Condition if (i + j == ctr) { // Appending the // Diagonal Elements lst.push_back(li[i][j]); } } } // Printing reversed Diagonal // Elements for(int i = lst.size() - 1; i >= 0; i--) { cout << lst[i] << " "; } cout << endl; ctr += 1; }} // Driver code int main(){ // Dimensions of Matrix int n = 8; int m = n; // Given matrix vector<vector<int>> li{ { 4, 5, 6, 9, 8, 7, 1, 4 }, { 1, 5, 9, 7, 5, 3, 1, 6 }, { 7, 5, 3, 1, 5, 9, 8, 0 }, { 6, 5, 4, 7, 8, 9, 3, 7 }, { 3, 5, 6, 4, 8, 9, 2, 1 }, { 3, 1, 6, 4, 7, 9, 5, 0 }, { 8, 0, 7, 2, 3, 1, 0, 8 }, { 7, 5, 3, 1, 5, 9, 8, 5 } }; // Function call matrix(n, m, li); return 0;} // This code is contributed by divyeshrabadiya07 // Java program for// the above approachimport java.util.*;class GFG{ // Function to rotate// matrix by 45 degreestatic void matrix(int n, int m, int [][]li){ // Counter Variable int ctr = 0; while (ctr < 2 * n - 1) { for(int i = 0; i < Math.abs(n - ctr - 1); i++) { System.out.print(" "); } Vector<Integer> lst = new Vector<Integer>(); // Iterate [0, m] for(int i = 0; i < m; i++) { // Iterate [0, n] for(int j = 0; j < n; j++) { // Diagonal Elements // Condition if (i + j == ctr) { // Appending the // Diagonal Elements lst.add(li[i][j]); } } } // Printing reversed Diagonal // Elements for(int i = lst.size() - 1; i >= 0; i--) { System.out.print(lst.get(i) + " "); } System.out.println(); ctr += 1; }} // Driver code public static void main(String[] args){ // Dimensions of Matrix int n = 8; int m = n; // Given matrix int[][] li = {{4, 5, 6, 9, 8, 7, 1, 4}, {1, 5, 9, 7, 5, 3, 1, 6}, {7, 5, 3, 1, 5, 9, 8, 0}, {6, 5, 4, 7, 8, 9, 3, 7}, {3, 5, 6, 4, 8, 9, 2, 1}, {3, 1, 6, 4, 7, 9, 5, 0}, {8, 0, 7, 2, 3, 1, 0, 8}, {7, 5, 3, 1, 5, 9, 8, 5}}; // Function call matrix(n, m, li);}} // This code is contributed by Princi Singh # Python3 program for the above approach # Function to rotate matrix by 45 degree def matrix(n, m, li): # Counter Variable ctr = 0 while(ctr < 2 * n-1): print(" "*abs(n-ctr-1), end ="") lst = [] # Iterate [0, m] for i in range(m): # Iterate [0, n] for j in range(n): # Diagonal Elements # Condition if i + j == ctr: # Appending the # Diagonal Elements lst.append(li[i][j]) # Printing reversed Diagonal # Elements lst.reverse() print(*lst) ctr += 1 # Driver Code # Dimensions of Matrixn = 8m = n # Given matrixli = [[4, 5, 6, 9, 8, 7, 1, 4], [1, 5, 9, 7, 5, 3, 1, 6], [7, 5, 3, 1, 5, 9, 8, 0], [6, 5, 4, 7, 8, 9, 3, 7], [3, 5, 6, 4, 8, 9, 2, 1], [3, 1, 6, 4, 7, 9, 5, 0], [8, 0, 7, 2, 3, 1, 0, 8], [7, 5, 3, 1, 5, 9, 8, 5]] # Function Callmatrix(n, m, li) // C# program for// the above approachusing System;using System.Collections;class GFG{ // Function to rotate// matrix by 45 degreestatic void matrix(int n, int m, int [,]li){ // Counter Variable int ctr = 0; while (ctr < 2 * n - 1) { for(int i = 0; i < Math.Abs(n - ctr - 1); i++) { Console.Write(" "); } ArrayList lst = new ArrayList(); // Iterate [0, m] for(int i = 0; i < m; i++) { // Iterate [0, n] for(int j = 0; j < n; j++) { // Diagonal Elements // Condition if (i + j == ctr) { // Appending the // Diagonal Elements lst.Add(li[i, j]); } } } // Printing reversed Diagonal // Elements for(int i = lst.Count - 1; i >= 0; i--) { Console.Write((int)lst[i] + " "); } Console.Write("\n"); ctr += 1; }} // Driver code public static void Main(string[] args){ // Dimensions of Matrix int n = 8; int m = n; // Given matrix int[,] li = {{4, 5, 6, 9, 8, 7, 1, 4}, {1, 5, 9, 7, 5, 3, 1, 6}, {7, 5, 3, 1, 5, 9, 8, 0}, {6, 5, 4, 7, 8, 9, 3, 7}, {3, 5, 6, 4, 8, 9, 2, 1}, {3, 1, 6, 4, 7, 9, 5, 0}, {8, 0, 7, 2, 3, 1, 0, 8}, {7, 5, 3, 1, 5, 9, 8, 5}}; // Function call matrix(n, m, li);}} // This code is contributed by Rutvik_56 4 1 5 7 5 6 6 5 9 9 3 5 3 7 8 3 5 4 1 5 7 8 1 6 7 5 3 1 7 0 6 4 8 9 1 4 5 7 4 8 9 8 6 3 2 7 9 3 0 1 3 9 2 7 5 1 5 1 9 0 0 8 8 5 Time Complexity: O(N3)Auxiliary Space: O(N) (by rythmrana2) Follow the given steps to print the matrix rotated by 45 degree: print the spaces required.print the element this way – print the spaces required. print the element this way – traverse the matrix the way you want to print it – We will print the matrix by dividing it into two parts using two for loops , the first loop will print the first triangle of the matrix and the second loop will print the second triangle of the matrix for the first half of matrix, take a loop that goes from the first row to the last row of the matrix. at each row , take a while loop which prints the first element of the row and the second element of the row above the current row and the third element of the row which is twice above the current row, going this way we will print the first half triangle of the matrix. take two counters, c for counting how many more elements the current diagonal have and counter inc for accessing those elements. similarly do this for the second half of the matrix. Below is the implementation of the above approach: C++ #include <bits/stdc++.h>using namespace std; // function to print the matrix rotated at 45 degree.void rotate(int m, int n, int* a){ // for printing the first half of matrix for (int i = 0; i < m; i++) { // print spaces for (int k = 0; k < m - i; k++) { cout << " "; } // counter to keep a track of the number of elements // left for the current diagonal int c = min(m - 1, min(i, n - 1)); // to access the diagonal elements int inc = 0; // while loop prints the diagonal elements of the // current loop. while (i <= m - 1 && c != -1) { cout << *(a + (i - inc) * n + inc) << " "; // increasing this variable to reach the // remaining elements of the diagonal inc++; // decreasing the counter to as an element is // printed c--; } cout << endl; } // for printing second half of the matrix for (int j = 1; j < n; j++) { // print spaces if (m < n) { for (int k = 0; k <= j - 1; k++) { cout << " "; } } else{ for (int k = 0; k <= j; k++) { cout << " "; } } // counter to keep a track of the number of elements // left for the current diagonal int c2 = min(m - 1, n - j - 1); // to access the diagonal elements int inc2 = 0; // while loop prints the diagonal elements of the // current loop. while (j <= n - 1 && c2 != -1) { cout << *((a + (m - 1 - inc2) * n) + j + inc2) << " "; inc2++; c2--; } cout << endl; }}// Driver codeint main(){ int m, n; cin >> m >> n; int a[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cin >> a[i][j]; } } rotate(m, n, (int*)a); return 0;} // contributed by rythmrana2 3 6 4 1 9 5 4 5 8 1 4 7 9 7 5 4 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5 9 6 8 Time Complexity: O(N2) Auxiliary Space: O(1) divyeshrabadiya07 princi singh rutvik_56 rythmrana2 rotation school-programming Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Count all possible paths from top left to bottom right of a mXn matrix Program to multiply two matrices Min Cost Path | DP-6 Printing all solutions in N-Queen Problem Efficiently compute sums of diagonals of a matrix Python program to multiply two matrices The Celebrity Problem Search in a row wise and column wise sorted matrix
[ { "code": null, "e": 26435, "s": 26407, "text": "\n05 Jan, 2022" }, { "code": null, "e": 26540, "s": 26435, "text": "Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix." }, { "code": null, "e": 26550, "s": 26540, "text": "Examples:" }, { "code": null, "e": 26900, "s": 26550, "text": "Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5 9 6 8" }, { "code": null, "e": 27029, "s": 26900, "text": "Input: N = 4, mat[][] = {{2, 5, 7, 2}, {9, 1, 4, 3}, {5, 8, 2, 3}, {6, 4, 6, 3}}" }, { "code": null, "e": 27076, "s": 27029, "text": "Output: 2 9 5 5 1 76 8 4 2 4 2 3 6 3 3 " }, { "code": null, "e": 27136, "s": 27076, "text": "Follow the steps given below in order to solve the problem:" }, { "code": null, "e": 27418, "s": 27136, "text": "Store the diagonal elements in a list using a counter variable.Print the number of spaces required to make the output look like the desired pattern.Print the list elements after reversing the list.Traverse through only diagonal elements to optimize the time taken by the operation." }, { "code": null, "e": 27482, "s": 27418, "text": "Store the diagonal elements in a list using a counter variable." }, { "code": null, "e": 27568, "s": 27482, "text": "Print the number of spaces required to make the output look like the desired pattern." }, { "code": null, "e": 27618, "s": 27568, "text": "Print the list elements after reversing the list." }, { "code": null, "e": 27703, "s": 27618, "text": "Traverse through only diagonal elements to optimize the time taken by the operation." }, { "code": null, "e": 27754, "s": 27703, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27758, "s": 27754, "text": "C++" }, { "code": null, "e": 27763, "s": 27758, "text": "Java" }, { "code": null, "e": 27771, "s": 27763, "text": "Python3" }, { "code": null, "e": 27774, "s": 27771, "text": "C#" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to rotate matrix by 45 degreevoid matrix(int n, int m, vector<vector<int>> li){ // Counter Variable int ctr = 0; while (ctr < 2 * n - 1) { for(int i = 0; i < abs(n - ctr - 1); i++) { cout << \" \"; } vector<int> lst; // Iterate [0, m] for(int i = 0; i < m; i++) { // Iterate [0, n] for(int j = 0; j < n; j++) { // Diagonal Elements // Condition if (i + j == ctr) { // Appending the // Diagonal Elements lst.push_back(li[i][j]); } } } // Printing reversed Diagonal // Elements for(int i = lst.size() - 1; i >= 0; i--) { cout << lst[i] << \" \"; } cout << endl; ctr += 1; }} // Driver code int main(){ // Dimensions of Matrix int n = 8; int m = n; // Given matrix vector<vector<int>> li{ { 4, 5, 6, 9, 8, 7, 1, 4 }, { 1, 5, 9, 7, 5, 3, 1, 6 }, { 7, 5, 3, 1, 5, 9, 8, 0 }, { 6, 5, 4, 7, 8, 9, 3, 7 }, { 3, 5, 6, 4, 8, 9, 2, 1 }, { 3, 1, 6, 4, 7, 9, 5, 0 }, { 8, 0, 7, 2, 3, 1, 0, 8 }, { 7, 5, 3, 1, 5, 9, 8, 5 } }; // Function call matrix(n, m, li); return 0;} // This code is contributed by divyeshrabadiya07", "e": 29401, "s": 27774, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to rotate// matrix by 45 degreestatic void matrix(int n, int m, int [][]li){ // Counter Variable int ctr = 0; while (ctr < 2 * n - 1) { for(int i = 0; i < Math.abs(n - ctr - 1); i++) { System.out.print(\" \"); } Vector<Integer> lst = new Vector<Integer>(); // Iterate [0, m] for(int i = 0; i < m; i++) { // Iterate [0, n] for(int j = 0; j < n; j++) { // Diagonal Elements // Condition if (i + j == ctr) { // Appending the // Diagonal Elements lst.add(li[i][j]); } } } // Printing reversed Diagonal // Elements for(int i = lst.size() - 1; i >= 0; i--) { System.out.print(lst.get(i) + \" \"); } System.out.println(); ctr += 1; }} // Driver code public static void main(String[] args){ // Dimensions of Matrix int n = 8; int m = n; // Given matrix int[][] li = {{4, 5, 6, 9, 8, 7, 1, 4}, {1, 5, 9, 7, 5, 3, 1, 6}, {7, 5, 3, 1, 5, 9, 8, 0}, {6, 5, 4, 7, 8, 9, 3, 7}, {3, 5, 6, 4, 8, 9, 2, 1}, {3, 1, 6, 4, 7, 9, 5, 0}, {8, 0, 7, 2, 3, 1, 0, 8}, {7, 5, 3, 1, 5, 9, 8, 5}}; // Function call matrix(n, m, li);}} // This code is contributed by Princi Singh", "e": 30827, "s": 29401, "text": null }, { "code": "# Python3 program for the above approach # Function to rotate matrix by 45 degree def matrix(n, m, li): # Counter Variable ctr = 0 while(ctr < 2 * n-1): print(\" \"*abs(n-ctr-1), end =\"\") lst = [] # Iterate [0, m] for i in range(m): # Iterate [0, n] for j in range(n): # Diagonal Elements # Condition if i + j == ctr: # Appending the # Diagonal Elements lst.append(li[i][j]) # Printing reversed Diagonal # Elements lst.reverse() print(*lst) ctr += 1 # Driver Code # Dimensions of Matrixn = 8m = n # Given matrixli = [[4, 5, 6, 9, 8, 7, 1, 4], [1, 5, 9, 7, 5, 3, 1, 6], [7, 5, 3, 1, 5, 9, 8, 0], [6, 5, 4, 7, 8, 9, 3, 7], [3, 5, 6, 4, 8, 9, 2, 1], [3, 1, 6, 4, 7, 9, 5, 0], [8, 0, 7, 2, 3, 1, 0, 8], [7, 5, 3, 1, 5, 9, 8, 5]] # Function Callmatrix(n, m, li)", "e": 31825, "s": 30827, "text": null }, { "code": "// C# program for// the above approachusing System;using System.Collections;class GFG{ // Function to rotate// matrix by 45 degreestatic void matrix(int n, int m, int [,]li){ // Counter Variable int ctr = 0; while (ctr < 2 * n - 1) { for(int i = 0; i < Math.Abs(n - ctr - 1); i++) { Console.Write(\" \"); } ArrayList lst = new ArrayList(); // Iterate [0, m] for(int i = 0; i < m; i++) { // Iterate [0, n] for(int j = 0; j < n; j++) { // Diagonal Elements // Condition if (i + j == ctr) { // Appending the // Diagonal Elements lst.Add(li[i, j]); } } } // Printing reversed Diagonal // Elements for(int i = lst.Count - 1; i >= 0; i--) { Console.Write((int)lst[i] + \" \"); } Console.Write(\"\\n\"); ctr += 1; }} // Driver code public static void Main(string[] args){ // Dimensions of Matrix int n = 8; int m = n; // Given matrix int[,] li = {{4, 5, 6, 9, 8, 7, 1, 4}, {1, 5, 9, 7, 5, 3, 1, 6}, {7, 5, 3, 1, 5, 9, 8, 0}, {6, 5, 4, 7, 8, 9, 3, 7}, {3, 5, 6, 4, 8, 9, 2, 1}, {3, 1, 6, 4, 7, 9, 5, 0}, {8, 0, 7, 2, 3, 1, 0, 8}, {7, 5, 3, 1, 5, 9, 8, 5}}; // Function call matrix(n, m, li);}} // This code is contributed by Rutvik_56", "e": 33259, "s": 31825, "text": null }, { "code": null, "e": 33458, "s": 33259, "text": " 4 \n 1 5 \n 7 5 6 \n 6 5 9 9 \n 3 5 3 7 8 \n 3 5 4 1 5 7 \n 8 1 6 7 5 3 1 \n7 0 6 4 8 9 1 4 \n 5 7 4 8 9 8 6 \n 3 2 7 9 3 0 \n 1 3 9 2 7 \n 5 1 5 1 \n 9 0 0 \n 8 8 \n 5 " }, { "code": null, "e": 33502, "s": 33458, "text": "Time Complexity: O(N3)Auxiliary Space: O(N)" }, { "code": null, "e": 33519, "s": 33502, "text": " (by rythmrana2)" }, { "code": null, "e": 33584, "s": 33519, "text": "Follow the given steps to print the matrix rotated by 45 degree:" }, { "code": null, "e": 33639, "s": 33584, "text": "print the spaces required.print the element this way –" }, { "code": null, "e": 33666, "s": 33639, "text": "print the spaces required." }, { "code": null, "e": 33695, "s": 33666, "text": "print the element this way –" }, { "code": null, "e": 33757, "s": 33695, "text": " traverse the matrix the way you want to print it – " }, { "code": null, "e": 33958, "s": 33757, "text": "We will print the matrix by dividing it into two parts using two for loops , the first loop will print the first triangle of the matrix and the second loop will print the second triangle of the matrix" }, { "code": null, "e": 34060, "s": 33958, "text": "for the first half of matrix, take a loop that goes from the first row to the last row of the matrix." }, { "code": null, "e": 34329, "s": 34060, "text": "at each row , take a while loop which prints the first element of the row and the second element of the row above the current row and the third element of the row which is twice above the current row, going this way we will print the first half triangle of the matrix." }, { "code": null, "e": 34458, "s": 34329, "text": "take two counters, c for counting how many more elements the current diagonal have and counter inc for accessing those elements." }, { "code": null, "e": 34511, "s": 34458, "text": "similarly do this for the second half of the matrix." }, { "code": null, "e": 34562, "s": 34511, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 34566, "s": 34562, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; // function to print the matrix rotated at 45 degree.void rotate(int m, int n, int* a){ // for printing the first half of matrix for (int i = 0; i < m; i++) { // print spaces for (int k = 0; k < m - i; k++) { cout << \" \"; } // counter to keep a track of the number of elements // left for the current diagonal int c = min(m - 1, min(i, n - 1)); // to access the diagonal elements int inc = 0; // while loop prints the diagonal elements of the // current loop. while (i <= m - 1 && c != -1) { cout << *(a + (i - inc) * n + inc) << \" \"; // increasing this variable to reach the // remaining elements of the diagonal inc++; // decreasing the counter to as an element is // printed c--; } cout << endl; } // for printing second half of the matrix for (int j = 1; j < n; j++) { // print spaces if (m < n) { for (int k = 0; k <= j - 1; k++) { cout << \" \"; } } else{ for (int k = 0; k <= j; k++) { cout << \" \"; } } // counter to keep a track of the number of elements // left for the current diagonal int c2 = min(m - 1, n - j - 1); // to access the diagonal elements int inc2 = 0; // while loop prints the diagonal elements of the // current loop. while (j <= n - 1 && c2 != -1) { cout << *((a + (m - 1 - inc2) * n) + j + inc2) << \" \"; inc2++; c2--; } cout << endl; }}// Driver codeint main(){ int m, n; cin >> m >> n; int a[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cin >> a[i][j]; } } rotate(m, n, (int*)a); return 0;} // contributed by rythmrana2", "e": 36572, "s": 34566, "text": null }, { "code": null, "e": 36696, "s": 36572, "text": " 3 \n 6 4 \n 1 9 5 \n 4 5 8 1 \n 4 7 9 7 5 \n 4 5 8 7 2 9 \n 5 2 9 5 5 \n 7 9 3 3 \n 2 5 5 \n 9 6 \n 8 " }, { "code": null, "e": 36719, "s": 36696, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 36741, "s": 36719, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 36759, "s": 36741, "text": "divyeshrabadiya07" }, { "code": null, "e": 36772, "s": 36759, "text": "princi singh" }, { "code": null, "e": 36782, "s": 36772, "text": "rutvik_56" }, { "code": null, "e": 36793, "s": 36782, "text": "rythmrana2" }, { "code": null, "e": 36802, "s": 36793, "text": "rotation" }, { "code": null, "e": 36821, "s": 36802, "text": "school-programming" }, { "code": null, "e": 36828, "s": 36821, "text": "Matrix" }, { "code": null, "e": 36835, "s": 36828, "text": "Matrix" }, { "code": null, "e": 36933, "s": 36835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36957, "s": 36933, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 37019, "s": 36957, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 37090, "s": 37019, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 37123, "s": 37090, "text": "Program to multiply two matrices" }, { "code": null, "e": 37144, "s": 37123, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 37186, "s": 37144, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 37236, "s": 37186, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 37276, "s": 37236, "text": "Python program to multiply two matrices" }, { "code": null, "e": 37298, "s": 37276, "text": "The Celebrity Problem" } ]
chage command in Linux with examples - GeeksforGeeks
30 Oct, 2019 chage command is used to view and change the user password expiry information. This command is used when the login is to be provided for a user for limited amount of time or when it is necessary to change the login password time to time. With the help of this command we can view the aging information of an account, date when the password was previously changed, set the password changing time, lock an account after certain amount of time etc . The syntax for chage command is given below : SYNTAX: chage [options] LOGIN In order to view the list of options that can be used with the chage command use the help option Input : chage -h Output : Examples: 1. -l option : use this option to view the account aging information. In order to view the aging information of the root i am using the keyword sudoInput :sudo chage -l root Output : 2. -d option : use this option to set the last password change date to your specified date in the command. In order to change the aging information of the root i am using the keyword “sudo”. Further i am using the -l option to view the changed date.Input :sudo chage -d 2018-12-01 root Output : 3. -E option : use this option to specify the date when the account should expire. In order to change the aging information of the root i am using the keyword sudo.Further i am using the -l option to view the changed date.Input :sudo chage -E root Output : 4. -M or -m option : use this option to specify the maximum and minimum number of days between password change. In order to change the aging information of the root i am using the keyword sudo. Further i am using the -l option to view the changed period.Input :sudo chage -M 5 root Output : 5. -I option : use this option to specify the number of days the account should be inactive after its expiry. It is necessary that the user should change the password after it expires, this command is useful when the user does not login after its expiry. Even after this inactivity period if the password is not changed then the account is locked and the user should approach the admin to unlock it. In order to change the aging information of the root i am using the keyword sudo. Further I used the -l option to view the inactivity period.Input :sudo chage -I 5 root Output : 6. -W option : use this option to give prior warning before the password expires.The input given in the command is the number of days prior to the expiry date when the warning should be given .In order to change the aging information of the root i am using the keyword sudo.Further i am using the -l option to view the warning period.Input :sudo chage -W 2 root Output : Akanksha_Rai linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples Tail command in Linux with examples UDP Server-Client implementation in C Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples scp command in Linux with Examples
[ { "code": null, "e": 25777, "s": 25749, "text": "\n30 Oct, 2019" }, { "code": null, "e": 26222, "s": 25777, "text": "chage command is used to view and change the user password expiry information. This command is used when the login is to be provided for a user for limited amount of time or when it is necessary to change the login password time to time. With the help of this command we can view the aging information of an account, date when the password was previously changed, set the password changing time, lock an account after certain amount of time etc" }, { "code": null, "e": 26224, "s": 26222, "text": "." }, { "code": null, "e": 26270, "s": 26224, "text": "The syntax for chage command is given below :" }, { "code": null, "e": 26278, "s": 26270, "text": "SYNTAX:" }, { "code": null, "e": 26301, "s": 26278, "text": "chage [options] LOGIN\n" }, { "code": null, "e": 26398, "s": 26301, "text": "In order to view the list of options that can be used with the chage command use the help option" }, { "code": null, "e": 26419, "s": 26398, "text": "Input : \n chage -h \n" }, { "code": null, "e": 26428, "s": 26419, "text": "Output :" }, { "code": null, "e": 26438, "s": 26428, "text": "Examples:" }, { "code": null, "e": 26612, "s": 26438, "text": "1. -l option : use this option to view the account aging information. In order to view the aging information of the root i am using the keyword sudoInput :sudo chage -l root" }, { "code": null, "e": 26621, "s": 26612, "text": "Output :" }, { "code": null, "e": 26907, "s": 26621, "text": "2. -d option : use this option to set the last password change date to your specified date in the command. In order to change the aging information of the root i am using the keyword “sudo”. Further i am using the -l option to view the changed date.Input :sudo chage -d 2018-12-01 root" }, { "code": null, "e": 26916, "s": 26907, "text": "Output :" }, { "code": null, "e": 27164, "s": 26916, "text": "3. -E option : use this option to specify the date when the account should expire. In order to change the aging information of the root i am using the keyword sudo.Further i am using the -l option to view the changed date.Input :sudo chage -E root" }, { "code": null, "e": 27173, "s": 27164, "text": "Output :" }, { "code": null, "e": 27455, "s": 27173, "text": "4. -M or -m option : use this option to specify the maximum and minimum number of days between password change. In order to change the aging information of the root i am using the keyword sudo. Further i am using the -l option to view the changed period.Input :sudo chage -M 5 root" }, { "code": null, "e": 27464, "s": 27455, "text": "Output :" }, { "code": null, "e": 28033, "s": 27464, "text": "5. -I option : use this option to specify the number of days the account should be inactive after its expiry. It is necessary that the user should change the password after it expires, this command is useful when the user does not login after its expiry. Even after this inactivity period if the password is not changed then the account is locked and the user should approach the admin to unlock it. In order to change the aging information of the root i am using the keyword sudo. Further I used the -l option to view the inactivity period.Input :sudo chage -I 5 root" }, { "code": null, "e": 28042, "s": 28033, "text": "Output :" }, { "code": null, "e": 28404, "s": 28042, "text": "6. -W option : use this option to give prior warning before the password expires.The input given in the command is the number of days prior to the expiry date when the warning should be given .In order to change the aging information of the root i am using the keyword sudo.Further i am using the -l option to view the warning period.Input :sudo chage -W 2 root" }, { "code": null, "e": 28413, "s": 28404, "text": "Output :" }, { "code": null, "e": 28426, "s": 28413, "text": "Akanksha_Rai" }, { "code": null, "e": 28440, "s": 28426, "text": "linux-command" }, { "code": null, "e": 28462, "s": 28440, "text": "Linux-system-commands" }, { "code": null, "e": 28469, "s": 28462, "text": "Picked" }, { "code": null, "e": 28480, "s": 28469, "text": "Linux-Unix" }, { "code": null, "e": 28578, "s": 28480, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28613, "s": 28578, "text": "tar command in Linux with examples" }, { "code": null, "e": 28651, "s": 28613, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28684, "s": 28651, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 28720, "s": 28684, "text": "diff command in Linux with examples" }, { "code": null, "e": 28756, "s": 28720, "text": "Tail command in Linux with examples" }, { "code": null, "e": 28794, "s": 28756, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28829, "s": 28794, "text": "Cat command in Linux with examples" }, { "code": null, "e": 28866, "s": 28829, "text": "touch command in Linux with Examples" }, { "code": null, "e": 28902, "s": 28866, "text": "echo command in Linux with Examples" } ]
How to Install Deepin on VirtualBox? - GeeksforGeeks
08 Sep, 2021 Deepin is a Debian-based distribution that aims to provide a user-friendly, user-friendly and reliable operating system. It does not only include the best open source world has to offer, but also it has created its own desktop environment called DDE which is based on the Qt 5 toolkit. It focuses much of its attention on intuitive design. New Enchanting Graphical Interface. Support for Light and Dark themes. Personalized notification management. A new font manager. Intel Pentium IV 2GHz or higher More than 2G RAM, 4G or higher is recommended Minimum 25 GB free disk space Deepin iso file which can be downloaded from here. VirtualBox, download from here. Step 1: Open Virtual Box, click on press on the new button. Step 2: Write the name which you want for the virtual machine and select its type to Debian-based 64bit Linux architecture. Step 3: Allot the size of RAM to the Virtual Machine of Deepin. Step 4: Select the option to create a virtual hard disk now and then hit on the create button. Step 5: Select the Hard Disk File type to VDI. Step 6: Select the type of Storage on Physical Hard Disk Storage to Dynamically Allocated. Step 7: Select the size of your virtual hard disk and the location where you want to save your machine and its files. Step 8: Click on the settings icon option located above after selecting deepin machine and select your downloaded Deepin ISO file and then click on the start button. Step 9: Click on the start button. Select the first option and press enter. Step 10: Select your preferred language for installation setup. Step 11: Select the /dev/sda icon and click on next. Step 12: Click on continue if you don’t want a backup for system restore otherwise check its box. Step 13: Wait for the installation to finish. Step 14: After successful installation, reboot Deepin. Step 15: Select your language and click on next. Step 16: Select your keyboard layout and press continue. Step 17: Select your location and press continue. Step 18: Type your username and computer’s name. Pick a strong password that will be required whenever you or anybody else tries to access Deepin. Click on continue. Step 19: Now wait for the changes to apply. Step 20: After the changes were applied, you will be asked to enter your credentials to log in. Now let’s explore, on the bottom we can see the application launcher icon, settings icon, calendar etc. Open the terminal and enter few basic commands. whoami ls ping geeksforgeeks.org Now you can go ahead and explore yourself what this Linux distro has to offer. RajuKumar19 GitHub how-to-install VMWare How To Installation Guide Linux-Unix TechTips VMWare Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26197, "s": 26169, "text": "\n08 Sep, 2021" }, { "code": null, "e": 26537, "s": 26197, "text": "Deepin is a Debian-based distribution that aims to provide a user-friendly, user-friendly and reliable operating system. It does not only include the best open source world has to offer, but also it has created its own desktop environment called DDE which is based on the Qt 5 toolkit. It focuses much of its attention on intuitive design." }, { "code": null, "e": 26573, "s": 26537, "text": "New Enchanting Graphical Interface." }, { "code": null, "e": 26608, "s": 26573, "text": "Support for Light and Dark themes." }, { "code": null, "e": 26646, "s": 26608, "text": "Personalized notification management." }, { "code": null, "e": 26666, "s": 26646, "text": "A new font manager." }, { "code": null, "e": 26698, "s": 26666, "text": "Intel Pentium IV 2GHz or higher" }, { "code": null, "e": 26744, "s": 26698, "text": "More than 2G RAM, 4G or higher is recommended" }, { "code": null, "e": 26774, "s": 26744, "text": "Minimum 25 GB free disk space" }, { "code": null, "e": 26825, "s": 26774, "text": "Deepin iso file which can be downloaded from here." }, { "code": null, "e": 26857, "s": 26825, "text": "VirtualBox, download from here." }, { "code": null, "e": 26917, "s": 26857, "text": "Step 1: Open Virtual Box, click on press on the new button." }, { "code": null, "e": 27041, "s": 26917, "text": "Step 2: Write the name which you want for the virtual machine and select its type to Debian-based 64bit Linux architecture." }, { "code": null, "e": 27107, "s": 27041, "text": "Step 3: Allot the size of RAM to the Virtual Machine of Deepin. " }, { "code": null, "e": 27202, "s": 27107, "text": "Step 4: Select the option to create a virtual hard disk now and then hit on the create button." }, { "code": null, "e": 27249, "s": 27202, "text": "Step 5: Select the Hard Disk File type to VDI." }, { "code": null, "e": 27340, "s": 27249, "text": "Step 6: Select the type of Storage on Physical Hard Disk Storage to Dynamically Allocated." }, { "code": null, "e": 27458, "s": 27340, "text": "Step 7: Select the size of your virtual hard disk and the location where you want to save your machine and its files." }, { "code": null, "e": 27624, "s": 27458, "text": "Step 8: Click on the settings icon option located above after selecting deepin machine and select your downloaded Deepin ISO file and then click on the start button." }, { "code": null, "e": 27700, "s": 27624, "text": "Step 9: Click on the start button. Select the first option and press enter." }, { "code": null, "e": 27764, "s": 27700, "text": "Step 10: Select your preferred language for installation setup." }, { "code": null, "e": 27817, "s": 27764, "text": "Step 11: Select the /dev/sda icon and click on next." }, { "code": null, "e": 27915, "s": 27817, "text": "Step 12: Click on continue if you don’t want a backup for system restore otherwise check its box." }, { "code": null, "e": 27961, "s": 27915, "text": "Step 13: Wait for the installation to finish." }, { "code": null, "e": 28016, "s": 27961, "text": "Step 14: After successful installation, reboot Deepin." }, { "code": null, "e": 28065, "s": 28016, "text": "Step 15: Select your language and click on next." }, { "code": null, "e": 28122, "s": 28065, "text": "Step 16: Select your keyboard layout and press continue." }, { "code": null, "e": 28173, "s": 28122, "text": "Step 17: Select your location and press continue." }, { "code": null, "e": 28339, "s": 28173, "text": "Step 18: Type your username and computer’s name. Pick a strong password that will be required whenever you or anybody else tries to access Deepin. Click on continue." }, { "code": null, "e": 28384, "s": 28339, "text": "Step 19: Now wait for the changes to apply. " }, { "code": null, "e": 28480, "s": 28384, "text": "Step 20: After the changes were applied, you will be asked to enter your credentials to log in." }, { "code": null, "e": 28584, "s": 28480, "text": "Now let’s explore, on the bottom we can see the application launcher icon, settings icon, calendar etc." }, { "code": null, "e": 28632, "s": 28584, "text": "Open the terminal and enter few basic commands." }, { "code": null, "e": 28666, "s": 28632, "text": "whoami \nls\nping geeksforgeeks.org" }, { "code": null, "e": 28745, "s": 28666, "text": "Now you can go ahead and explore yourself what this Linux distro has to offer." }, { "code": null, "e": 28757, "s": 28745, "text": "RajuKumar19" }, { "code": null, "e": 28764, "s": 28757, "text": "GitHub" }, { "code": null, "e": 28779, "s": 28764, "text": "how-to-install" }, { "code": null, "e": 28786, "s": 28779, "text": "VMWare" }, { "code": null, "e": 28793, "s": 28786, "text": "How To" }, { "code": null, "e": 28812, "s": 28793, "text": "Installation Guide" }, { "code": null, "e": 28823, "s": 28812, "text": "Linux-Unix" }, { "code": null, "e": 28832, "s": 28823, "text": "TechTips" }, { "code": null, "e": 28839, "s": 28832, "text": "VMWare" }, { "code": null, "e": 28937, "s": 28839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28971, "s": 28937, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29029, "s": 28971, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29078, "s": 29029, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29120, "s": 29078, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 29180, "s": 29120, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 29213, "s": 29180, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29247, "s": 29213, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29282, "s": 29247, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 29340, "s": 29282, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
Find a number K such that exactly K array elements are greater than or equal to K - GeeksforGeeks
06 Jan, 2022 Given an array a[] of size N, which contains only non-negative elements, the task is to find any integer K for which there are exactly K array elements that are greater than or equal to K. If no such K exists, then print -1. Examples: Input: a[] = {7, 8, 9, 0, 0, 1}Output: 3Explanation:Since 3 is less than or equal to 7, 8, and 9, therefore, 3 is the answer. Input: a[] = {0, 0}Output: -1 Approach: The task is to find K such that the array elements are greater than or equal to K. Therefore, K cannot exceed the maximum element present in the array a[n]. Follow the steps below solve the problem: Traverse the array to find the largest array element, store it in a variable, say m.Initialize a counter variable, cnt to count the number of array elements greater than or equal to K.Iterate for possible values of K starting from 0 to m. Iterate over the array for each value and count the number of array elements greater than or equal to that value.If for any value, exactly K array elements are found to be greater than or equal to that value, print that value.If no such value is obtained after complete traversal of the array, print -1. Traverse the array to find the largest array element, store it in a variable, say m. Initialize a counter variable, cnt to count the number of array elements greater than or equal to K. Iterate for possible values of K starting from 0 to m. Iterate over the array for each value and count the number of array elements greater than or equal to that value. If for any value, exactly K array elements are found to be greater than or equal to that value, print that value. If no such value is obtained after complete traversal of the array, print -1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find K for which// there are exactly K array// elements greater than or equal to Kint zvalue(vector<int>& nums){ // Finding the largest array element int m = *max_element(nums.begin(), nums.end()); int cnt = 0; // Possible values of K for (int i = 0; i <= m; i++) { cnt = 0; // Traverse the array for (int j = 0; j < nums.size(); j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // Driver Codeint main(){ vector<int> nums = { 7, 8, 9, 0, 0, 1 }; cout << zvalue(nums) << endl;} // Java program for the above approachimport java.io.*; class GFG{ // Function to find K for which// there are exactly K array// elements greater than or equal to Kpublic static int zvalue(int[] nums){ // Finding the largest array element int m = max_element(nums); int cnt = 0; // Possible values of K for(int i = 0; i <= m; i++) { cnt = 0; // Traverse the array for(int j = 0; j < nums.length; j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // To find maximum Elementpublic static int max_element(int[] nums){ int max = nums[0]; for(int i = 1; i < nums.length; i++) max = Math.max(max, nums[i]); return max;} // Driver Codepublic static void main(String args[]){ int[] nums = { 7, 8, 9, 0, 0, 1 }; System.out.println(zvalue(nums));}} // This code is contributed by hemanth gadarla # Python3 program for the above approach # Function to find K for which# there are exactly K array# elements greater than or equal to Kdef zvalue(nums): # Finding the largest array element m = max(nums) cnt = 0 # Possible values of K for i in range(0, m + 1, 1): cnt = 0 # Traverse the array for j in range(0, len(nums), 1): # If current array element is # greater than or equal to i if (nums[j] >= i): cnt += 1 # If i array elements are # greater than or equal to i if (cnt == i): return i # Otherwise return -1 # Driver Codeif __name__ == '__main__': nums = [ 7, 8, 9, 0, 0, 1 ] print(zvalue(nums)) # This code is contributed by SURENDRA_GANGWAR // C# program for the// above approachusing System;class GFG{ // Function to find K for which// there are exactly K array// elements greater than or equal to Kpublic static int zvalue(int[] nums){ // Finding the largest array element int m = max_element(nums); int cnt = 0; // Possible values of K for(int i = 0; i <= m; i++) { cnt = 0; // Traverse the array for(int j = 0; j < nums.Length; j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // To find maximum Elementpublic static int max_element(int[] nums){ int max = nums[0]; for(int i = 1; i < nums.Length; i++) max = Math.Max(max, nums[i]); return max;} // Driver Codepublic static void Main(String []args){ int[] nums = {7, 8, 9, 0, 0, 1}; Console.WriteLine(zvalue(nums));}} // This code is contributed by 29AjayKumar <script> // javascript program for the above approach // Function to find K for which// there are exactly K array// elements greater than or equal to Kfunction zvalue(nums){ // Finding the largest array element var m = max_element(nums); var cnt = 0; // Possible values of K for(i = 0; i <= m; i++) { cnt = 0; // Traverse the array for(j = 0; j < nums.length; j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // To find maximum Elementfunction max_element(nums){ var max = nums[0]; for(i = 1; i < nums.length; i++) max = Math.max(max, nums[i]); return max;} // Driver Codenums = [ 7, 8, 9, 0, 0, 1 ]; document.write(zvalue(nums)); // This code contributed by shikhasingrajput </script> 3 Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: Find the maximum element in the array and store it.Create a count array with size of (maximum element +1) and initialize to 0.Traverse over the given array and increment the element count of the corresponding index in the count arrayi.e., if (nums[i] == j) then count[j]=count[j]+1Find the suffix sum of the count arrayTraverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of itAgain traverse through the count array, for any index == count[index], return indexElse return -1 Find the maximum element in the array and store it. Create a count array with size of (maximum element +1) and initialize to 0. Traverse over the given array and increment the element count of the corresponding index in the count arrayi.e., if (nums[i] == j) then count[j]=count[j]+1 i.e., if (nums[i] == j) then count[j]=count[j]+1 Find the suffix sum of the count arrayTraverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it Traverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it Traverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it Again traverse through the count array, for any index == count[index], return index Else return -1 C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std;int solve(vector<int>& nums){ // Finding the maximum element int max = *max_element(nums.begin(), nums.end()); // initialising the count to 0 for all indices int count[max + 1] = { 0 }; // incrementing count of corresponding element in the // count array for (int i = 0; i < nums.size(); i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (int j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1;}// Driver Codeint main(){ vector<int> v = { 2, 0, 0 }; cout << solve(v);} // This code is contributed by Maneesh Gupta NVSS // Java code to implement the above approachimport java.io.*;import java.util.Arrays; class GFG { public static int solve(int nums[]) { // Finding the maximum element int max = Arrays.stream(nums).max().getAsInt(); // initialising the count to 0 for all indices int count[] = new int[max + 1]; Arrays.fill(count, 0); // incrementing count of corresponding element in the // count array for (int i = 0; i < nums.length; i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (int j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1; } // Driver Code public static void main (String[] args) { int v[] = new int[]{ 2, 0, 0 }; System.out.println(solve(v)); }} // This code is contributed by Shubham Singh def solve(nums): # Finding the maximum element maxx = max(nums) # initialising the count to 0 for all indices count = [0]*(maxx + 1) # incrementing count of corresponding element in the # count array for i in range(len(nums)): count[nums[i]] += 1 # corner case if (count[maxx] == maxx): return maxx # finding suffix sum for j in range(maxx - 1, -1, -1): count[j] += count[j + 1] # Checking the index after updating the count if (j == count[j]): return j return -1 # Driver Codev = [ 2, 0, 0 ]print(solve(v)) # This code is contributed by ShubhamSingh // C# code to implement the above approachusing System;using System.Linq; public class GFG{ public static int solve(int[] nums) { // Finding the maximum element int max = nums.Max(); // initialising the count to 0 for all indices int[] count = new int[max + 1]; // incrementing count of corresponding element in the // count array for (int i = 0; i < nums.Length; i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (int j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1; } // Driver Code public static void Main () { int[] v = new int[]{ 2, 0, 0 }; Console.Write(solve(v)); }} // This code is contributed by Shubham Singh <script>// Javascript code to implement the above approach function solve(nums){ // Finding the maximum element var max = Math.max.apply(Math, nums); // initialising the count to 0 for all indices var count = new Array(max+1).fill(0); // incrementing count of corresponding element in the // count array for (var i = 0; i < nums.length; i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (var j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1;} // Driver Codevar v = [ 2, 0, 0 ];document.write(solve(v)); // This code is contributed by Shubham Singh</script> 1 Time complexity : O (N) where N is maximum(nums.size(), max element) Space complexity : O ( max element) hemanthswarna1506 29AjayKumar SURENDRA_GANGWAR shikhasingrajput nvssmgupta SHUBHAMSINGH10 frequency-counting Arrays Mathematical Searching Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26135, "s": 26107, "text": "\n06 Jan, 2022" }, { "code": null, "e": 26360, "s": 26135, "text": "Given an array a[] of size N, which contains only non-negative elements, the task is to find any integer K for which there are exactly K array elements that are greater than or equal to K. If no such K exists, then print -1." }, { "code": null, "e": 26370, "s": 26360, "text": "Examples:" }, { "code": null, "e": 26496, "s": 26370, "text": "Input: a[] = {7, 8, 9, 0, 0, 1}Output: 3Explanation:Since 3 is less than or equal to 7, 8, and 9, therefore, 3 is the answer." }, { "code": null, "e": 26526, "s": 26496, "text": "Input: a[] = {0, 0}Output: -1" }, { "code": null, "e": 26735, "s": 26526, "text": "Approach: The task is to find K such that the array elements are greater than or equal to K. Therefore, K cannot exceed the maximum element present in the array a[n]. Follow the steps below solve the problem:" }, { "code": null, "e": 27278, "s": 26735, "text": "Traverse the array to find the largest array element, store it in a variable, say m.Initialize a counter variable, cnt to count the number of array elements greater than or equal to K.Iterate for possible values of K starting from 0 to m. Iterate over the array for each value and count the number of array elements greater than or equal to that value.If for any value, exactly K array elements are found to be greater than or equal to that value, print that value.If no such value is obtained after complete traversal of the array, print -1." }, { "code": null, "e": 27363, "s": 27278, "text": "Traverse the array to find the largest array element, store it in a variable, say m." }, { "code": null, "e": 27464, "s": 27363, "text": "Initialize a counter variable, cnt to count the number of array elements greater than or equal to K." }, { "code": null, "e": 27633, "s": 27464, "text": "Iterate for possible values of K starting from 0 to m. Iterate over the array for each value and count the number of array elements greater than or equal to that value." }, { "code": null, "e": 27747, "s": 27633, "text": "If for any value, exactly K array elements are found to be greater than or equal to that value, print that value." }, { "code": null, "e": 27825, "s": 27747, "text": "If no such value is obtained after complete traversal of the array, print -1." }, { "code": null, "e": 27876, "s": 27825, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27880, "s": 27876, "text": "C++" }, { "code": null, "e": 27885, "s": 27880, "text": "Java" }, { "code": null, "e": 27893, "s": 27885, "text": "Python3" }, { "code": null, "e": 27896, "s": 27893, "text": "C#" }, { "code": null, "e": 27907, "s": 27896, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find K for which// there are exactly K array// elements greater than or equal to Kint zvalue(vector<int>& nums){ // Finding the largest array element int m = *max_element(nums.begin(), nums.end()); int cnt = 0; // Possible values of K for (int i = 0; i <= m; i++) { cnt = 0; // Traverse the array for (int j = 0; j < nums.size(); j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // Driver Codeint main(){ vector<int> nums = { 7, 8, 9, 0, 0, 1 }; cout << zvalue(nums) << endl;}", "e": 28803, "s": 27907, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find K for which// there are exactly K array// elements greater than or equal to Kpublic static int zvalue(int[] nums){ // Finding the largest array element int m = max_element(nums); int cnt = 0; // Possible values of K for(int i = 0; i <= m; i++) { cnt = 0; // Traverse the array for(int j = 0; j < nums.length; j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // To find maximum Elementpublic static int max_element(int[] nums){ int max = nums[0]; for(int i = 1; i < nums.length; i++) max = Math.max(max, nums[i]); return max;} // Driver Codepublic static void main(String args[]){ int[] nums = { 7, 8, 9, 0, 0, 1 }; System.out.println(zvalue(nums));}} // This code is contributed by hemanth gadarla", "e": 29942, "s": 28803, "text": null }, { "code": "# Python3 program for the above approach # Function to find K for which# there are exactly K array# elements greater than or equal to Kdef zvalue(nums): # Finding the largest array element m = max(nums) cnt = 0 # Possible values of K for i in range(0, m + 1, 1): cnt = 0 # Traverse the array for j in range(0, len(nums), 1): # If current array element is # greater than or equal to i if (nums[j] >= i): cnt += 1 # If i array elements are # greater than or equal to i if (cnt == i): return i # Otherwise return -1 # Driver Codeif __name__ == '__main__': nums = [ 7, 8, 9, 0, 0, 1 ] print(zvalue(nums)) # This code is contributed by SURENDRA_GANGWAR", "e": 30755, "s": 29942, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Function to find K for which// there are exactly K array// elements greater than or equal to Kpublic static int zvalue(int[] nums){ // Finding the largest array element int m = max_element(nums); int cnt = 0; // Possible values of K for(int i = 0; i <= m; i++) { cnt = 0; // Traverse the array for(int j = 0; j < nums.Length; j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // To find maximum Elementpublic static int max_element(int[] nums){ int max = nums[0]; for(int i = 1; i < nums.Length; i++) max = Math.Max(max, nums[i]); return max;} // Driver Codepublic static void Main(String []args){ int[] nums = {7, 8, 9, 0, 0, 1}; Console.WriteLine(zvalue(nums));}} // This code is contributed by 29AjayKumar", "e": 31771, "s": 30755, "text": null }, { "code": "<script> // javascript program for the above approach // Function to find K for which// there are exactly K array// elements greater than or equal to Kfunction zvalue(nums){ // Finding the largest array element var m = max_element(nums); var cnt = 0; // Possible values of K for(i = 0; i <= m; i++) { cnt = 0; // Traverse the array for(j = 0; j < nums.length; j++) { // If current array element is // greater than or equal to i if (nums[j] >= i) cnt++; } // If i array elements are // greater than or equal to i if (cnt == i) return i; } // Otherwise return -1;} // To find maximum Elementfunction max_element(nums){ var max = nums[0]; for(i = 1; i < nums.length; i++) max = Math.max(max, nums[i]); return max;} // Driver Codenums = [ 7, 8, 9, 0, 0, 1 ]; document.write(zvalue(nums)); // This code contributed by shikhasingrajput </script>", "e": 32804, "s": 31771, "text": null }, { "code": null, "e": 32806, "s": 32804, "text": "3" }, { "code": null, "e": 32850, "s": 32806, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 32870, "s": 32850, "text": "Efficient Approach:" }, { "code": null, "e": 33439, "s": 32870, "text": "Find the maximum element in the array and store it.Create a count array with size of (maximum element +1) and initialize to 0.Traverse over the given array and increment the element count of the corresponding index in the count arrayi.e., if (nums[i] == j) then count[j]=count[j]+1Find the suffix sum of the count arrayTraverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of itAgain traverse through the count array, for any index == count[index], return indexElse return -1" }, { "code": null, "e": 33491, "s": 33439, "text": "Find the maximum element in the array and store it." }, { "code": null, "e": 33567, "s": 33491, "text": "Create a count array with size of (maximum element +1) and initialize to 0." }, { "code": null, "e": 33723, "s": 33567, "text": "Traverse over the given array and increment the element count of the corresponding index in the count arrayi.e., if (nums[i] == j) then count[j]=count[j]+1" }, { "code": null, "e": 33772, "s": 33723, "text": "i.e., if (nums[i] == j) then count[j]=count[j]+1" }, { "code": null, "e": 33963, "s": 33772, "text": "Find the suffix sum of the count arrayTraverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it" }, { "code": null, "e": 34116, "s": 33963, "text": "Traverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it" }, { "code": null, "e": 34269, "s": 34116, "text": "Traverse through the count array from right to left and update the count value with the sum of all the remaining array elements count to the right of it" }, { "code": null, "e": 34353, "s": 34269, "text": "Again traverse through the count array, for any index == count[index], return index" }, { "code": null, "e": 34368, "s": 34353, "text": "Else return -1" }, { "code": null, "e": 34372, "s": 34368, "text": "C++" }, { "code": null, "e": 34377, "s": 34372, "text": "Java" }, { "code": null, "e": 34385, "s": 34377, "text": "Python3" }, { "code": null, "e": 34388, "s": 34385, "text": "C#" }, { "code": null, "e": 34399, "s": 34388, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;int solve(vector<int>& nums){ // Finding the maximum element int max = *max_element(nums.begin(), nums.end()); // initialising the count to 0 for all indices int count[max + 1] = { 0 }; // incrementing count of corresponding element in the // count array for (int i = 0; i < nums.size(); i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (int j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1;}// Driver Codeint main(){ vector<int> v = { 2, 0, 0 }; cout << solve(v);} // This code is contributed by Maneesh Gupta NVSS", "e": 35211, "s": 34399, "text": null }, { "code": "// Java code to implement the above approachimport java.io.*;import java.util.Arrays; class GFG { public static int solve(int nums[]) { // Finding the maximum element int max = Arrays.stream(nums).max().getAsInt(); // initialising the count to 0 for all indices int count[] = new int[max + 1]; Arrays.fill(count, 0); // incrementing count of corresponding element in the // count array for (int i = 0; i < nums.length; i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (int j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1; } // Driver Code public static void main (String[] args) { int v[] = new int[]{ 2, 0, 0 }; System.out.println(solve(v)); }} // This code is contributed by Shubham Singh", "e": 36157, "s": 35211, "text": null }, { "code": "def solve(nums): # Finding the maximum element maxx = max(nums) # initialising the count to 0 for all indices count = [0]*(maxx + 1) # incrementing count of corresponding element in the # count array for i in range(len(nums)): count[nums[i]] += 1 # corner case if (count[maxx] == maxx): return maxx # finding suffix sum for j in range(maxx - 1, -1, -1): count[j] += count[j + 1] # Checking the index after updating the count if (j == count[j]): return j return -1 # Driver Codev = [ 2, 0, 0 ]print(solve(v)) # This code is contributed by ShubhamSingh", "e": 36832, "s": 36157, "text": null }, { "code": "// C# code to implement the above approachusing System;using System.Linq; public class GFG{ public static int solve(int[] nums) { // Finding the maximum element int max = nums.Max(); // initialising the count to 0 for all indices int[] count = new int[max + 1]; // incrementing count of corresponding element in the // count array for (int i = 0; i < nums.Length; i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (int j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1; } // Driver Code public static void Main () { int[] v = new int[]{ 2, 0, 0 }; Console.Write(solve(v)); }} // This code is contributed by Shubham Singh", "e": 37702, "s": 36832, "text": null }, { "code": "<script>// Javascript code to implement the above approach function solve(nums){ // Finding the maximum element var max = Math.max.apply(Math, nums); // initialising the count to 0 for all indices var count = new Array(max+1).fill(0); // incrementing count of corresponding element in the // count array for (var i = 0; i < nums.length; i++) { count[nums[i]]++; } // corner case if (count[max] == max) return max; // finding suffix sum for (var j = max - 1; j >= 0; j--) { count[j] += count[j + 1]; // Checking the index after updating the count if (j == count[j]) { return j; } } return -1;} // Driver Codevar v = [ 2, 0, 0 ];document.write(solve(v)); // This code is contributed by Shubham Singh</script>", "e": 38514, "s": 37702, "text": null }, { "code": null, "e": 38516, "s": 38514, "text": "1" }, { "code": null, "e": 38585, "s": 38516, "text": "Time complexity : O (N) where N is maximum(nums.size(), max element)" }, { "code": null, "e": 38621, "s": 38585, "text": "Space complexity : O ( max element)" }, { "code": null, "e": 38639, "s": 38621, "text": "hemanthswarna1506" }, { "code": null, "e": 38651, "s": 38639, "text": "29AjayKumar" }, { "code": null, "e": 38668, "s": 38651, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 38685, "s": 38668, "text": "shikhasingrajput" }, { "code": null, "e": 38696, "s": 38685, "text": "nvssmgupta" }, { "code": null, "e": 38711, "s": 38696, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 38730, "s": 38711, "text": "frequency-counting" }, { "code": null, "e": 38737, "s": 38730, "text": "Arrays" }, { "code": null, "e": 38750, "s": 38737, "text": "Mathematical" }, { "code": null, "e": 38760, "s": 38750, "text": "Searching" }, { "code": null, "e": 38767, "s": 38760, "text": "Arrays" }, { "code": null, "e": 38777, "s": 38767, "text": "Searching" }, { "code": null, "e": 38790, "s": 38777, "text": "Mathematical" }, { "code": null, "e": 38888, "s": 38790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38956, "s": 38888, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38979, "s": 38956, "text": "Introduction to Arrays" }, { "code": null, "e": 39011, "s": 38979, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39025, "s": 39011, "text": "Linear Search" }, { "code": null, "e": 39046, "s": 39025, "text": "Linked List vs Array" }, { "code": null, "e": 39106, "s": 39046, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39121, "s": 39106, "text": "C++ Data Types" }, { "code": null, "e": 39164, "s": 39121, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 39188, "s": 39164, "text": "Merge two sorted arrays" } ]
C# | Char.IsLower() Method - GeeksforGeeks
31 Jan, 2019 In C#, Char.IsLower() is a System.Char struct method which is used to check whether a Unicode character can be categorized as a lowercase letter or not. Valid lowercase letters will be the members of UnicodeCategory: LowercaseLetter. This method can be overloaded by passing different type and number of arguments to it. Char.IsLower(Char) MethodChar.IsLower(String, Int32) Method Char.IsLower(Char) Method Char.IsLower(String, Int32) Method This method is used to check whether the specified Unicode character matches lowercase letter or not. If it matches then it returns True otherwise return False. Syntax: public static bool IsLower(char ch); Parameter: ch: It is required Unicode character of System.char type which is to be checked. Return Type: The method returns True, if it successfully matches any lowercase letter, otherwise returns False. The return type of this method is System.Boolean. Example: // C# program to illustrate the// Char.IsLower(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if g is a // lowercase letter or not char ch1 = 'g'; result = Char.IsLower(ch1); Console.WriteLine(result); // checking if 'G' is a // lowercase letter or not char ch2 = 'G'; result = Char.IsLower(ch2); Console.WriteLine(result); }} True False This method is used to check whether the specified string at specified position matches with any lowercase letter or not. If it matches then it returns True otherwise returns False. Syntax: public static bool IsLower(string str, int index); Parameters: Str: It is the required string of System.String type which is to be evaluate.index: It is the position of character in string to be compared and type of this parameter is System.Int32. Return Type: The method returns True if it successfully matches any lowercase letter at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean. Exceptions: If the value of str is null then this method will give ArgumentNullException If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException. Example: // C# program to illustrate the// Char.IsLower(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for lowercase letter in // a string at a desired position string str1 = "GeeksforGeeks"; result = Char.IsLower(str1, 2); Console.WriteLine(result); // checking for lowercase letter in a // string at a desired position string str2 = "geeksForgeeks"; result = Char.IsLower(str2, 5); Console.WriteLine(result); }} True False Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.IsLower?view=netframework-4.7.2 CSharp-Char-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# Dictionary with examples C# | IsNullOrEmpty() Method C# | Delegates C# | Method Overriding C# | Arrays of Strings C# | Abstract Classes Difference between Ref and Out keywords in C#
[ { "code": null, "e": 25277, "s": 25249, "text": "\n31 Jan, 2019" }, { "code": null, "e": 25598, "s": 25277, "text": "In C#, Char.IsLower() is a System.Char struct method which is used to check whether a Unicode character can be categorized as a lowercase letter or not. Valid lowercase letters will be the members of UnicodeCategory: LowercaseLetter. This method can be overloaded by passing different type and number of arguments to it." }, { "code": null, "e": 25658, "s": 25598, "text": "Char.IsLower(Char) MethodChar.IsLower(String, Int32) Method" }, { "code": null, "e": 25684, "s": 25658, "text": "Char.IsLower(Char) Method" }, { "code": null, "e": 25719, "s": 25684, "text": "Char.IsLower(String, Int32) Method" }, { "code": null, "e": 25880, "s": 25719, "text": "This method is used to check whether the specified Unicode character matches lowercase letter or not. If it matches then it returns True otherwise return False." }, { "code": null, "e": 25888, "s": 25880, "text": "Syntax:" }, { "code": null, "e": 25925, "s": 25888, "text": "public static bool IsLower(char ch);" }, { "code": null, "e": 25936, "s": 25925, "text": "Parameter:" }, { "code": null, "e": 26017, "s": 25936, "text": "ch: It is required Unicode character of System.char type which is to be checked." }, { "code": null, "e": 26179, "s": 26017, "text": "Return Type: The method returns True, if it successfully matches any lowercase letter, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 26188, "s": 26179, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsLower(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if g is a // lowercase letter or not char ch1 = 'g'; result = Char.IsLower(ch1); Console.WriteLine(result); // checking if 'G' is a // lowercase letter or not char ch2 = 'G'; result = Char.IsLower(ch2); Console.WriteLine(result); }}", "e": 26707, "s": 26188, "text": null }, { "code": null, "e": 26719, "s": 26707, "text": "True\nFalse\n" }, { "code": null, "e": 26901, "s": 26719, "text": "This method is used to check whether the specified string at specified position matches with any lowercase letter or not. If it matches then it returns True otherwise returns False." }, { "code": null, "e": 26909, "s": 26901, "text": "Syntax:" }, { "code": null, "e": 26960, "s": 26909, "text": "public static bool IsLower(string str, int index);" }, { "code": null, "e": 26972, "s": 26960, "text": "Parameters:" }, { "code": null, "e": 27157, "s": 26972, "text": "Str: It is the required string of System.String type which is to be evaluate.index: It is the position of character in string to be compared and type of this parameter is System.Int32." }, { "code": null, "e": 27365, "s": 27157, "text": "Return Type: The method returns True if it successfully matches any lowercase letter at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 27377, "s": 27365, "text": "Exceptions:" }, { "code": null, "e": 27454, "s": 27377, "text": "If the value of str is null then this method will give ArgumentNullException" }, { "code": null, "e": 27582, "s": 27454, "text": "If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException." }, { "code": null, "e": 27591, "s": 27582, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsLower(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for lowercase letter in // a string at a desired position string str1 = \"GeeksforGeeks\"; result = Char.IsLower(str1, 2); Console.WriteLine(result); // checking for lowercase letter in a // string at a desired position string str2 = \"geeksForgeeks\"; result = Char.IsLower(str2, 5); Console.WriteLine(result); }}", "e": 28197, "s": 27591, "text": null }, { "code": null, "e": 28209, "s": 28197, "text": "True\nFalse\n" }, { "code": null, "e": 28308, "s": 28209, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.IsLower?view=netframework-4.7.2" }, { "code": null, "e": 28327, "s": 28308, "text": "CSharp-Char-Struct" }, { "code": null, "e": 28341, "s": 28327, "text": "CSharp-method" }, { "code": null, "e": 28344, "s": 28341, "text": "C#" }, { "code": null, "e": 28442, "s": 28344, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28496, "s": 28442, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 28538, "s": 28496, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 28600, "s": 28538, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 28628, "s": 28600, "text": "C# Dictionary with examples" }, { "code": null, "e": 28656, "s": 28628, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 28671, "s": 28656, "text": "C# | Delegates" }, { "code": null, "e": 28694, "s": 28671, "text": "C# | Method Overriding" }, { "code": null, "e": 28717, "s": 28694, "text": "C# | Arrays of Strings" }, { "code": null, "e": 28739, "s": 28717, "text": "C# | Abstract Classes" } ]
Passing arguments to a Tkinter button command
The Button widget in Tkinter is generally used for pushing an event defined in an application. We can bind the events with buttons that allow them to execute and run whenever an action is triggered by the user. However, sharing the data and variables outside the function and events seems difficult sometimes. With the Button widget, we can pass arguments and data that allows the user to share and execute the event. In general, passing the arguments to a button widget allows the event to pick the arguments and use them further in the program. # Import the required library from tkinter import * from tkinter import ttk from tkinter import messagebox # Create an instance of tkinter frame win=Tk() # Set the geometry win.geometry("700x250") # Define a function to update the entry widget def update_name(name): entry.insert(END, ""+str(name)) # Create an entry widget entry=Entry(win, width=35, font=('Calibri 15')) entry.pack() b=ttk.Button(win, text="Insert", command=lambda:update_name("Tutorialspoint")) b.pack(pady=30) win.mainloop() Running the above code will display a window with an Entry widget and a button to insert text in it. Click the button "Insert" to add text in the Entry widget.
[ { "code": null, "e": 1273, "s": 1062, "text": "The Button widget in Tkinter is generally used for pushing an event defined in an application. We can bind the events with buttons that allow them to execute and run whenever an action is triggered by the user." }, { "code": null, "e": 1480, "s": 1273, "text": "However, sharing the data and variables outside the function and events seems difficult sometimes. With the Button widget, we can pass arguments and data that allows the user to share and execute the event." }, { "code": null, "e": 1609, "s": 1480, "text": "In general, passing the arguments to a button widget allows the event to pick the arguments and use them further in the program." }, { "code": null, "e": 2113, "s": 1609, "text": "# Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n# Create an instance of tkinter frame\nwin=Tk()\n\n# Set the geometry\nwin.geometry(\"700x250\")\n\n# Define a function to update the entry widget\ndef update_name(name):\n entry.insert(END, \"\"+str(name))\n\n# Create an entry widget\nentry=Entry(win, width=35, font=('Calibri 15'))\nentry.pack()\n\nb=ttk.Button(win, text=\"Insert\", command=lambda:update_name(\"Tutorialspoint\"))\nb.pack(pady=30)\n\nwin.mainloop()" }, { "code": null, "e": 2214, "s": 2113, "text": "Running the above code will display a window with an Entry widget and a button to insert text in it." }, { "code": null, "e": 2273, "s": 2214, "text": "Click the button \"Insert\" to add text in the Entry widget." } ]
Rakuten Archives - GeeksforGeeks
Rakuten Interview Experience for Associate Software Engineer (Off-Campus) Rakuten India Interview Experience | On-Campus 2021 Rakuten Interview Experience | SDE Intern (Pool Campus) Rakuten Internship Interview Expereince Rakuten India Interview Experience for Technical Intern How to Add External JAR File to an IntelliJ IDEA Project? apply(), lapply(), sapply(), and tapply() in R How to connect MongoDB with ReactJS ? Token, Patterns, and Lexems SDE SHEET - A Complete Guide for SDE Preparation
[ { "code": null, "e": 24204, "s": 24130, "text": "Rakuten Interview Experience for Associate Software Engineer (Off-Campus)" }, { "code": null, "e": 24256, "s": 24204, "text": "Rakuten India Interview Experience | On-Campus 2021" }, { "code": null, "e": 24312, "s": 24256, "text": "Rakuten Interview Experience | SDE Intern (Pool Campus)" }, { "code": null, "e": 24352, "s": 24312, "text": "Rakuten Internship Interview Expereince" }, { "code": null, "e": 24408, "s": 24352, "text": "Rakuten India Interview Experience for Technical Intern" }, { "code": null, "e": 24466, "s": 24408, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 24513, "s": 24466, "text": "apply(), lapply(), sapply(), and tapply() in R" }, { "code": null, "e": 24551, "s": 24513, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 24579, "s": 24551, "text": "Token, Patterns, and Lexems" } ]
DataFrame.to_excel() method in Pandas
16 Jul, 2020 The to_excel() method is used to export the DataFrame to the excel file. To write a single object to the excel file, we have to specify the target file name. If we want to write to multiple sheets, we need to create an ExcelWriter object with target filename and also need to specify the sheet in the file in which we have to write. The multiple sheets can also be written by specifying the unique sheet_name. It is necessary to save the changes for all the data written to the file. Syntax: data.to_excel( excel_writer, sheet_name='Sheet1', \*\*kwargs ) Parameters: One can provide the excel file name or the Excelwrite object. By default the sheet number is 1, one can change it by input the value of argument “sheet_name”. One can provide the name of the columns to store the data by input the value of the argument “columns”. By default the index is labeled with numbers as 0,1,2 ... and so on, one can change it by passing a sequence of the list for the value of the argument “index”. Below is the implementation of the above method : Python3 # importing packages import pandas as pd # dictionary of data dct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # forming dataframedata = pd.DataFrame(dct) # storing into the excel filedata.to_excel("output.xlsx") Output : In the above example, By default index is labeled as 0,1,.... and so on. As our DataFrame has columns names so columns are labeled. By default, it is saved in “Sheet1”. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas 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 Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2020" }, { "code": null, "e": 513, "s": 28, "text": "The to_excel() method is used to export the DataFrame to the excel file. To write a single object to the excel file, we have to specify the target file name. If we want to write to multiple sheets, we need to create an ExcelWriter object with target filename and also need to specify the sheet in the file in which we have to write. The multiple sheets can also be written by specifying the unique sheet_name. It is necessary to save the changes for all the data written to the file." }, { "code": null, "e": 521, "s": 513, "text": "Syntax:" }, { "code": null, "e": 585, "s": 521, "text": "data.to_excel( excel_writer, sheet_name='Sheet1', \\*\\*kwargs )\n" }, { "code": null, "e": 597, "s": 585, "text": "Parameters:" }, { "code": null, "e": 659, "s": 597, "text": "One can provide the excel file name or the Excelwrite object." }, { "code": null, "e": 756, "s": 659, "text": "By default the sheet number is 1, one can change it by input the value of argument “sheet_name”." }, { "code": null, "e": 860, "s": 756, "text": "One can provide the name of the columns to store the data by input the value of the argument “columns”." }, { "code": null, "e": 1020, "s": 860, "text": "By default the index is labeled with numbers as 0,1,2 ... and so on, one can change it by passing a sequence of the list for the value of the argument “index”." }, { "code": null, "e": 1070, "s": 1020, "text": "Below is the implementation of the above method :" }, { "code": null, "e": 1078, "s": 1070, "text": "Python3" }, { "code": "# importing packages import pandas as pd # dictionary of data dct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # forming dataframedata = pd.DataFrame(dct) # storing into the excel filedata.to_excel(\"output.xlsx\")", "e": 1776, "s": 1078, "text": null }, { "code": null, "e": 1785, "s": 1776, "text": "Output :" }, { "code": null, "e": 1807, "s": 1785, "text": "In the above example," }, { "code": null, "e": 1858, "s": 1807, "text": "By default index is labeled as 0,1,.... and so on." }, { "code": null, "e": 1917, "s": 1858, "text": "As our DataFrame has columns names so columns are labeled." }, { "code": null, "e": 1954, "s": 1917, "text": "By default, it is saved in “Sheet1”." }, { "code": null, "e": 1978, "s": 1954, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2010, "s": 1978, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2024, "s": 2010, "text": "Python-pandas" }, { "code": null, "e": 2031, "s": 2024, "text": "Python" }, { "code": null, "e": 2129, "s": 2031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2171, "s": 2129, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2193, "s": 2171, "text": "Enumerate() in Python" }, { "code": null, "e": 2219, "s": 2193, "text": "Python String | replace()" }, { "code": null, "e": 2251, "s": 2219, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2280, "s": 2251, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2307, "s": 2280, "text": "Python Classes and Objects" }, { "code": null, "e": 2328, "s": 2307, "text": "Python OOPs Concepts" }, { "code": null, "e": 2351, "s": 2328, "text": "Introduction To PYTHON" }, { "code": null, "e": 2387, "s": 2351, "text": "Convert integer to string in Python" } ]
Types of Virtual Machines
20 Aug, 2020 In this article, we will study about virtual machines, types of virtual machines, and virtual machine languages. Virtual Machine is like fake computer system operating on your hardware. It partially uses the hardware of your system (like CPU, RAM, disk space, etc.) but its space is completely separated from your main system. Two virtual machines don’t interrupt in each other’s working and functioning nor they can excess each other’s space which gives an illusion that we are using totally different hardware system. More detail at Virtual Machine. Question :Is there any limit to no. of virtual machines one can install? Answer –In general there is no limit because it depends on the hardware of your system. As the VM is using hardware of your system, if it goes out of it’s capacity then it will limit you not to install further virtual machines. Question :Can one access the files of one VM from another? Answer –In general No, but as an advanced hardware feature, we can allow the file-sharing for different virtual machines. Types of Virtual Machines :You can classify virtual machines into two types: 1. System Virtual Machine:These types of virtual machines gives us complete system platform and gives the execution of the complete virtual operating system. Just like virtual box, system virtual machine is providing an environment for an OS to be installed completely. We can see in below image that our hardware of Real Machine is being distributed between two simulated operating systems by Virtual machine monitor. And then some programs, processes are going on in that distributed hardware of simulated machines separately. 2. Process Virtual Machine :While process virtual machines, unlike system virtual machine, does not provide us with the facility to install the virtual operating system completely. Rather it creates virtual environment of that OS while using some app or program and this environment will be destroyed as soon as we exit from that app. Like in below image, there are some apps running on main OS as well some virtual machines are created to run other apps. This shows that as those programs required different OS, process virtual machine provided them with that for the time being those programs are running. Example –Wine software in Linux helps to run Windows applications. Virtual Machine Language :It’s type of language which can be understood by different operating systems. It is platform-independent. Just like to run any programming language (C, python, or java) we need specific compiler that actually converts that code into system understandable code (also known as byte code). The same virtual machine language works. If we want to use code that can be executed on different types of operating systems like (Windows, Linux, etc) then virtual machine language will be helpful. Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. File Allocation Methods Memory Management in Operating System Logical and Physical Address in Operating System Segmentation in Operating System Structures of Directory in Operating System Difference between Internal and External fragmentation Memory Hierarchy Design and its Characteristics Different approaches or Structures of Operating Systems Process Table and Process Control Block (PCB) File Access Methods in Operating System
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Aug, 2020" }, { "code": null, "e": 166, "s": 53, "text": "In this article, we will study about virtual machines, types of virtual machines, and virtual machine languages." }, { "code": null, "e": 605, "s": 166, "text": "Virtual Machine is like fake computer system operating on your hardware. It partially uses the hardware of your system (like CPU, RAM, disk space, etc.) but its space is completely separated from your main system. Two virtual machines don’t interrupt in each other’s working and functioning nor they can excess each other’s space which gives an illusion that we are using totally different hardware system. More detail at Virtual Machine." }, { "code": null, "e": 678, "s": 605, "text": "Question :Is there any limit to no. of virtual machines one can install?" }, { "code": null, "e": 906, "s": 678, "text": "Answer –In general there is no limit because it depends on the hardware of your system. As the VM is using hardware of your system, if it goes out of it’s capacity then it will limit you not to install further virtual machines." }, { "code": null, "e": 965, "s": 906, "text": "Question :Can one access the files of one VM from another?" }, { "code": null, "e": 1087, "s": 965, "text": "Answer –In general No, but as an advanced hardware feature, we can allow the file-sharing for different virtual machines." }, { "code": null, "e": 1164, "s": 1087, "text": "Types of Virtual Machines :You can classify virtual machines into two types:" }, { "code": null, "e": 1693, "s": 1164, "text": "1. System Virtual Machine:These types of virtual machines gives us complete system platform and gives the execution of the complete virtual operating system. Just like virtual box, system virtual machine is providing an environment for an OS to be installed completely. We can see in below image that our hardware of Real Machine is being distributed between two simulated operating systems by Virtual machine monitor. And then some programs, processes are going on in that distributed hardware of simulated machines separately." }, { "code": null, "e": 2301, "s": 1693, "text": "2. Process Virtual Machine :While process virtual machines, unlike system virtual machine, does not provide us with the facility to install the virtual operating system completely. Rather it creates virtual environment of that OS while using some app or program and this environment will be destroyed as soon as we exit from that app. Like in below image, there are some apps running on main OS as well some virtual machines are created to run other apps. This shows that as those programs required different OS, process virtual machine provided them with that for the time being those programs are running." }, { "code": null, "e": 2368, "s": 2301, "text": "Example –Wine software in Linux helps to run Windows applications." }, { "code": null, "e": 2880, "s": 2368, "text": "Virtual Machine Language :It’s type of language which can be understood by different operating systems. It is platform-independent. Just like to run any programming language (C, python, or java) we need specific compiler that actually converts that code into system understandable code (also known as byte code). The same virtual machine language works. If we want to use code that can be executed on different types of operating systems like (Windows, Linux, etc) then virtual machine language will be helpful." }, { "code": null, "e": 2898, "s": 2880, "text": "Operating Systems" }, { "code": null, "e": 2916, "s": 2898, "text": "Operating Systems" }, { "code": null, "e": 3014, "s": 2916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3038, "s": 3014, "text": "File Allocation Methods" }, { "code": null, "e": 3076, "s": 3038, "text": "Memory Management in Operating System" }, { "code": null, "e": 3125, "s": 3076, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 3158, "s": 3125, "text": "Segmentation in Operating System" }, { "code": null, "e": 3202, "s": 3158, "text": "Structures of Directory in Operating System" }, { "code": null, "e": 3257, "s": 3202, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 3305, "s": 3257, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 3361, "s": 3305, "text": "Different approaches or Structures of Operating Systems" }, { "code": null, "e": 3407, "s": 3361, "text": "Process Table and Process Control Block (PCB)" } ]
Remove duplicates from a sorted doubly linked list
20 Jun, 2022 Given a sorted doubly linked list containing n nodes. The problem is removing duplicate nodes from the given list. Examples: Algorithm: removeDuplicates(head_ref, x) if head_ref == NULL return Initialize current = head_ref while current->next != NULL if current->data == current->next->data deleteNode(head_ref, current->next) else current = current->next The algorithm for deleteNode(head_ref, current) (which deletes the node using the pointer to the node) is discussed in this post. C++ Java Python C# Javascript /* C++ implementation to remove duplicates from a sorted doubly linked list */#include <bits/stdc++.h> using namespace std; /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del);} /* function to remove duplicates from a sorted doubly linked list */void removeDuplicates(struct Node** head_ref){ /* if list is empty */ if ((*head_ref) == NULL) return; struct Node* current = *head_ref; struct Node* next; /* traverse the list till the last node */ while (current->next != NULL) { /* Compare current node with next node */ if (current->data == current->next->data) /* delete the node pointed to by 'current->next' */ deleteNode(head_ref, current->next); /* else simply move to the next node */ else current = current->next; }} /* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list */void printList(struct Node* head){ /* if list is empty */ if (head == NULL) cout << "Doubly Linked list empty"; while (head != NULL) { cout << head->data << " "; head = head->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list: 4<->4<->4<->4<->6<->8<->8<->10<->12<->12 */ push(&head, 12); push(&head, 12); push(&head, 10); push(&head, 8); push(&head, 8); push(&head, 6); push(&head, 4); push(&head, 4); push(&head, 4); push(&head, 4); cout << "Original Doubly linked list:n"; printList(head); /* remove duplicate nodes */ removeDuplicates(&head); cout << "\nDoubly linked list after" " removing duplicates:n"; printList(head); return 0;} /* Java implementation to remove duplicates from a sorted doubly linked list */public class removeDuplicatesFromSortedList { /* function to remove duplicates from a sorted doubly linked list */ public static void removeDuplicates(Node head) { /* if list is empty */ if (head== null) return; Node current = head; /* traverse the list till the last node */ while (current.next != null) { /* Compare current node with next node */ if (current.data == current.next.data) /* delete the node pointed to by ' current->next' */ deleteNode(head, current.next); /* else simply move to the next node */ else current = current.next; } } /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ public static void deleteNode(Node head, Node del) { /* base case */ if(head==null || del==null) { return ; } /* If node to be deleted is head node */ if(head==del) { head=del.next; } /* Change next only if node to be deleted is NOT the last node */ if(del.next!=null) { del.next.prev=del.prev; } /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; } /* Function to insert a node at the beginning of the Doubly Linked List */ public static Node push(Node head, int data) { /* allocate node */ Node newNode=new Node(data); /* since we are adding at the beginning, prev is always NULL */ newNode.prev=null; /* link the old list off the new node */ newNode.next =head; /* change prev of head node to new node */ if(head!=null) { head.prev=newNode; } head=newNode; return head; } /* Function to print nodes in a given doubly linked list */ public static void printList(Node head) { if (head == null) System.out.println("Doubly Linked list empty"); while (head != null) { System.out.print(head.data+" ") ; head = head.next; } } public static void main(String args[]) { Node head=null; head=push(head, 12); head=push(head, 12); head=push(head, 10); head=push(head, 8); head=push(head, 8); head=push(head, 6); head=push(head, 4); head=push(head, 4); head=push(head, 4); head=push(head, 4); System.out.println("Original Doubly LinkedList"); printList(head); /* remove duplicate nodes */ removeDuplicates(head); System.out.println("\nDoubly linked list after removing duplicates:"); printList(head); }}class Node{ int data; Node next,prev; Node(int data) { this.data=data; next=null; prev=null; }}//This code is contributed by Gaurav Tiwari # Python implementation to remove duplicates from a# sorted doubly linked list # A linked list nodeclass Node: def __init__(self, new_data): self.data = new_data self.next = None self.prev = None # Function to _delete a node in a Doubly Linked List.# head_ref -. pointer to head node pointer.# _del -. pointer to node to be _deleted.def _deleteNode(head_ref, _del): # base case if (head_ref == None or _del == None): return # If node to be _deleted is head node if (head_ref == _del): head_ref = _del.next # Change next only if node to be _deleted # is NOT the last node if (_del.next != None): _del.next.prev = _del.prev # Change prev only if node to be _deleted # is NOT the first node if (_del.prev != None): _del.prev.next = _del.next return head_ref # function to remove duplicates from a# sorted doubly linked listdef removeDuplicates(head_ref): # if list is empty if ((head_ref) == None): return None current = head_ref next = None # traverse the list till the last node while (current.next != None) : # Compare current node with next node if (current.data == current.next.data): # _delete the node pointed to by # 'current.next' _deleteNode(head_ref, current.next) # else simply move to the next node else: current = current.next return head_ref # Function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # Function to print nodes in a given doubly linked listdef printList(head): # if list is empty if (head == None): print("Doubly Linked list empty") while (head != None) : print(head.data, end = " ") head = head.next # Driver program to test above functions # Start with the empty listhead = None # Create the doubly linked list:# 4<->4<->4<->4<->6<->8<->8<->10<->12<->12head = push(head, 12)head = push(head, 12)head = push(head, 10)head = push(head, 8)head = push(head, 8)head = push(head, 6)head = push(head, 4)head = push(head, 4)head = push(head, 4)head = push(head, 4) print( "Original Doubly linked list:\n")printList(head) # remove duplicate nodeshead = removeDuplicates(head) print("\nDoubly linked list after removing duplicates:")printList(head) # This code is contributed by Arnab Kundu /* C# implementation to remove duplicates from asorted doubly linked list */using System; public class removeDuplicatesFromSortedList{ /* function to remove duplicates from a sorted doubly linked list */ public static void removeDuplicates(Node head) { /* if list is empty */ if (head == null) return; Node current = head; /* traverse the list till the last node */ while (current.next != null) { /* Compare current node with next node */ if (current.data == current.next.data) /* delete the node pointed to by 'current->next' */ deleteNode(head, current.next); /* else simply move to the next node */ else current = current.next; } } /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ public static void deleteNode(Node head, Node del) { /* base case */ if(head == null || del == null) { return ; } /* If node to be deleted is head node */ if(head == del) { head = del.next; } /* Change next only if node to be deleted is NOT the last node */ if(del.next != null) { del.next.prev = del.prev; } /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; } /* Function to insert a node at the beginning of the Doubly Linked List */ public static Node push(Node head, int data) { /* allocate node */ Node newNode = new Node(data); /* since we are adding at the beginning, prev is always NULL */ newNode.prev = null; /* link the old list off the new node */ newNode.next = head; /* change prev of head node to new node */ if(head != null) { head.prev = newNode; } head = newNode; return head; } /* Function to print nodes in a given doubly linked list */ public static void printList(Node head) { if (head == null) Console.WriteLine("Doubly Linked list empty"); while (head != null) { Console.Write(head.data + " ") ; head = head.next; } } // Driver code public static void Main(String []args) { Node head = null; head = push(head, 12); head = push(head, 12); head = push(head, 10); head = push(head, 8); head = push(head, 8); head = push(head, 6); head = push(head, 4); head = push(head, 4); head = push(head, 4); head = push(head, 4); Console.WriteLine("Original Doubly LinkedList"); printList(head); /* remove duplicate nodes */ removeDuplicates(head); Console.WriteLine("\nDoubly linked list after" + "removing duplicates:"); printList(head); }} public class Node{ public int data; public Node next,prev; public Node(int data) { this.data = data; next = null; prev = null; }} // This code is contributed by 29AjayKumar. <script>/* javascript implementation to remove duplicates from a sorted doubly linked list */ class Node { constructor(val){ this.data = val; this.prev = null; this.next = null; } } /* * function to remove duplicates from a sorted doubly linked list */ function removeDuplicates(head) { /* if list is empty */ if (head == null) return; var current = head; /* traverse the list till the last node */ while (current.next != null) { /* Compare current node with next node */ if (current.data == current.next.data) /* * delete the node pointed to by ' current->next' */ deleteNode(head, current.next); /* else simply move to the next node */ else current = current.next; } } /* * Function to delete a node in a Doubly Linked List. head_ref --> pointer to * head node pointer. del --> pointer to node to be deleted. */ function deleteNode(head, del) { /* base case */ if (head == null || del == null) { return; } /* If node to be deleted is head node */ if (head == del) { head = del.next; } /* * Change next only if node to be deleted is NOT the last node */ if (del.next != null) { del.next.prev = del.prev; } /* * Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; } /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(head , data) { /* allocate node */ var newNode = new Node(data); /* * since we are adding at the beginning, prev is always NULL */ newNode.prev = null; /* link the old list off the new node */ newNode.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = newNode; } head = newNode; return head; } /* Function to print nodes in a given doubly linked list */ function printList(head) { if (head == null) document.write("Doubly Linked list empty"); while (head != null) { document.write(head.data + " "); head = head.next; } } var head = null; head = push(head, 12); head = push(head, 12); head = push(head, 10); head = push(head, 8); head = push(head, 8); head = push(head, 6); head = push(head, 4); head = push(head, 4); head = push(head, 4); head = push(head, 4); document.write("Original Doubly LinkedList<br/>"); printList(head); /* remove duplicate nodes */ removeDuplicates(head); document.write("<br/>Doubly linked list after removing duplicates:<br/>"); printList(head); // This code contributed by gauravrajput1</script> Output: Original Doubly linked list: 4 4 4 4 6 8 8 10 12 12 Doubly linked list after removing duplicates: 4 6 8 10 12 Time Complexity: O(n) Space complexity: O(1) since using constant space for pointers This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari 29AjayKumar andrew1234 nirpendrac9 arorakashish0911 GauravRajput1 ankita_saini technophpfij doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Find the middle of a given linked list Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive) Add two numbers represented by linked lists | Set 1 Detect and Remove Loop in a Linked List
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jun, 2022" }, { "code": null, "e": 168, "s": 53, "text": "Given a sorted doubly linked list containing n nodes. The problem is removing duplicate nodes from the given list." }, { "code": null, "e": 179, "s": 168, "text": "Examples: " }, { "code": null, "e": 190, "s": 179, "text": "Algorithm:" }, { "code": null, "e": 490, "s": 190, "text": "removeDuplicates(head_ref, x)\n if head_ref == NULL\n return\n Initialize current = head_ref\n while current->next != NULL\n if current->data == current->next->data\n deleteNode(head_ref, current->next)\n else\n current = current->next" }, { "code": null, "e": 620, "s": 490, "text": "The algorithm for deleteNode(head_ref, current) (which deletes the node using the pointer to the node) is discussed in this post." }, { "code": null, "e": 624, "s": 620, "text": "C++" }, { "code": null, "e": 629, "s": 624, "text": "Java" }, { "code": null, "e": 636, "s": 629, "text": "Python" }, { "code": null, "e": 639, "s": 636, "text": "C#" }, { "code": null, "e": 650, "s": 639, "text": "Javascript" }, { "code": "/* C++ implementation to remove duplicates from a sorted doubly linked list */#include <bits/stdc++.h> using namespace std; /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del);} /* function to remove duplicates from a sorted doubly linked list */void removeDuplicates(struct Node** head_ref){ /* if list is empty */ if ((*head_ref) == NULL) return; struct Node* current = *head_ref; struct Node* next; /* traverse the list till the last node */ while (current->next != NULL) { /* Compare current node with next node */ if (current->data == current->next->data) /* delete the node pointed to by 'current->next' */ deleteNode(head_ref, current->next); /* else simply move to the next node */ else current = current->next; }} /* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list */void printList(struct Node* head){ /* if list is empty */ if (head == NULL) cout << \"Doubly Linked list empty\"; while (head != NULL) { cout << head->data << \" \"; head = head->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list: 4<->4<->4<->4<->6<->8<->8<->10<->12<->12 */ push(&head, 12); push(&head, 12); push(&head, 10); push(&head, 8); push(&head, 8); push(&head, 6); push(&head, 4); push(&head, 4); push(&head, 4); push(&head, 4); cout << \"Original Doubly linked list:n\"; printList(head); /* remove duplicate nodes */ removeDuplicates(&head); cout << \"\\nDoubly linked list after\" \" removing duplicates:n\"; printList(head); return 0;}", "e": 3826, "s": 650, "text": null }, { "code": "/* Java implementation to remove duplicates from a sorted doubly linked list */public class removeDuplicatesFromSortedList { /* function to remove duplicates from a sorted doubly linked list */ public static void removeDuplicates(Node head) { /* if list is empty */ if (head== null) return; Node current = head; /* traverse the list till the last node */ while (current.next != null) { /* Compare current node with next node */ if (current.data == current.next.data) /* delete the node pointed to by ' current->next' */ deleteNode(head, current.next); /* else simply move to the next node */ else current = current.next; } } /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ public static void deleteNode(Node head, Node del) { /* base case */ if(head==null || del==null) { return ; } /* If node to be deleted is head node */ if(head==del) { head=del.next; } /* Change next only if node to be deleted is NOT the last node */ if(del.next!=null) { del.next.prev=del.prev; } /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; } /* Function to insert a node at the beginning of the Doubly Linked List */ public static Node push(Node head, int data) { /* allocate node */ Node newNode=new Node(data); /* since we are adding at the beginning, prev is always NULL */ newNode.prev=null; /* link the old list off the new node */ newNode.next =head; /* change prev of head node to new node */ if(head!=null) { head.prev=newNode; } head=newNode; return head; } /* Function to print nodes in a given doubly linked list */ public static void printList(Node head) { if (head == null) System.out.println(\"Doubly Linked list empty\"); while (head != null) { System.out.print(head.data+\" \") ; head = head.next; } } public static void main(String args[]) { Node head=null; head=push(head, 12); head=push(head, 12); head=push(head, 10); head=push(head, 8); head=push(head, 8); head=push(head, 6); head=push(head, 4); head=push(head, 4); head=push(head, 4); head=push(head, 4); System.out.println(\"Original Doubly LinkedList\"); printList(head); /* remove duplicate nodes */ removeDuplicates(head); System.out.println(\"\\nDoubly linked list after removing duplicates:\"); printList(head); }}class Node{ int data; Node next,prev; Node(int data) { this.data=data; next=null; prev=null; }}//This code is contributed by Gaurav Tiwari", "e": 7033, "s": 3826, "text": null }, { "code": "# Python implementation to remove duplicates from a# sorted doubly linked list # A linked list nodeclass Node: def __init__(self, new_data): self.data = new_data self.next = None self.prev = None # Function to _delete a node in a Doubly Linked List.# head_ref -. pointer to head node pointer.# _del -. pointer to node to be _deleted.def _deleteNode(head_ref, _del): # base case if (head_ref == None or _del == None): return # If node to be _deleted is head node if (head_ref == _del): head_ref = _del.next # Change next only if node to be _deleted # is NOT the last node if (_del.next != None): _del.next.prev = _del.prev # Change prev only if node to be _deleted # is NOT the first node if (_del.prev != None): _del.prev.next = _del.next return head_ref # function to remove duplicates from a# sorted doubly linked listdef removeDuplicates(head_ref): # if list is empty if ((head_ref) == None): return None current = head_ref next = None # traverse the list till the last node while (current.next != None) : # Compare current node with next node if (current.data == current.next.data): # _delete the node pointed to by # 'current.next' _deleteNode(head_ref, current.next) # else simply move to the next node else: current = current.next return head_ref # Function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # Function to print nodes in a given doubly linked listdef printList(head): # if list is empty if (head == None): print(\"Doubly Linked list empty\") while (head != None) : print(head.data, end = \" \") head = head.next # Driver program to test above functions # Start with the empty listhead = None # Create the doubly linked list:# 4<->4<->4<->4<->6<->8<->8<->10<->12<->12head = push(head, 12)head = push(head, 12)head = push(head, 10)head = push(head, 8)head = push(head, 8)head = push(head, 6)head = push(head, 4)head = push(head, 4)head = push(head, 4)head = push(head, 4) print( \"Original Doubly linked list:\\n\")printList(head) # remove duplicate nodeshead = removeDuplicates(head) print(\"\\nDoubly linked list after removing duplicates:\")printList(head) # This code is contributed by Arnab Kundu", "e": 9882, "s": 7033, "text": null }, { "code": "/* C# implementation to remove duplicates from asorted doubly linked list */using System; public class removeDuplicatesFromSortedList{ /* function to remove duplicates from a sorted doubly linked list */ public static void removeDuplicates(Node head) { /* if list is empty */ if (head == null) return; Node current = head; /* traverse the list till the last node */ while (current.next != null) { /* Compare current node with next node */ if (current.data == current.next.data) /* delete the node pointed to by 'current->next' */ deleteNode(head, current.next); /* else simply move to the next node */ else current = current.next; } } /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ public static void deleteNode(Node head, Node del) { /* base case */ if(head == null || del == null) { return ; } /* If node to be deleted is head node */ if(head == del) { head = del.next; } /* Change next only if node to be deleted is NOT the last node */ if(del.next != null) { del.next.prev = del.prev; } /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; } /* Function to insert a node at the beginning of the Doubly Linked List */ public static Node push(Node head, int data) { /* allocate node */ Node newNode = new Node(data); /* since we are adding at the beginning, prev is always NULL */ newNode.prev = null; /* link the old list off the new node */ newNode.next = head; /* change prev of head node to new node */ if(head != null) { head.prev = newNode; } head = newNode; return head; } /* Function to print nodes in a given doubly linked list */ public static void printList(Node head) { if (head == null) Console.WriteLine(\"Doubly Linked list empty\"); while (head != null) { Console.Write(head.data + \" \") ; head = head.next; } } // Driver code public static void Main(String []args) { Node head = null; head = push(head, 12); head = push(head, 12); head = push(head, 10); head = push(head, 8); head = push(head, 8); head = push(head, 6); head = push(head, 4); head = push(head, 4); head = push(head, 4); head = push(head, 4); Console.WriteLine(\"Original Doubly LinkedList\"); printList(head); /* remove duplicate nodes */ removeDuplicates(head); Console.WriteLine(\"\\nDoubly linked list after\" + \"removing duplicates:\"); printList(head); }} public class Node{ public int data; public Node next,prev; public Node(int data) { this.data = data; next = null; prev = null; }} // This code is contributed by 29AjayKumar.", "e": 13284, "s": 9882, "text": null }, { "code": "<script>/* javascript implementation to remove duplicates from a sorted doubly linked list */ class Node { constructor(val){ this.data = val; this.prev = null; this.next = null; } } /* * function to remove duplicates from a sorted doubly linked list */ function removeDuplicates(head) { /* if list is empty */ if (head == null) return; var current = head; /* traverse the list till the last node */ while (current.next != null) { /* Compare current node with next node */ if (current.data == current.next.data) /* * delete the node pointed to by ' current->next' */ deleteNode(head, current.next); /* else simply move to the next node */ else current = current.next; } } /* * Function to delete a node in a Doubly Linked List. head_ref --> pointer to * head node pointer. del --> pointer to node to be deleted. */ function deleteNode(head, del) { /* base case */ if (head == null || del == null) { return; } /* If node to be deleted is head node */ if (head == del) { head = del.next; } /* * Change next only if node to be deleted is NOT the last node */ if (del.next != null) { del.next.prev = del.prev; } /* * Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; } /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(head , data) { /* allocate node */ var newNode = new Node(data); /* * since we are adding at the beginning, prev is always NULL */ newNode.prev = null; /* link the old list off the new node */ newNode.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = newNode; } head = newNode; return head; } /* Function to print nodes in a given doubly linked list */ function printList(head) { if (head == null) document.write(\"Doubly Linked list empty\"); while (head != null) { document.write(head.data + \" \"); head = head.next; } } var head = null; head = push(head, 12); head = push(head, 12); head = push(head, 10); head = push(head, 8); head = push(head, 8); head = push(head, 6); head = push(head, 4); head = push(head, 4); head = push(head, 4); head = push(head, 4); document.write(\"Original Doubly LinkedList<br/>\"); printList(head); /* remove duplicate nodes */ removeDuplicates(head); document.write(\"<br/>Doubly linked list after removing duplicates:<br/>\"); printList(head); // This code contributed by gauravrajput1</script>", "e": 16414, "s": 13284, "text": null }, { "code": null, "e": 16423, "s": 16414, "text": "Output: " }, { "code": null, "e": 16533, "s": 16423, "text": "Original Doubly linked list:\n4 4 4 4 6 8 8 10 12 12\nDoubly linked list after removing duplicates:\n4 6 8 10 12" }, { "code": null, "e": 16555, "s": 16533, "text": "Time Complexity: O(n)" }, { "code": null, "e": 16618, "s": 16555, "text": "Space complexity: O(1) since using constant space for pointers" }, { "code": null, "e": 17040, "s": 16618, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17055, "s": 17040, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 17067, "s": 17055, "text": "29AjayKumar" }, { "code": null, "e": 17078, "s": 17067, "text": "andrew1234" }, { "code": null, "e": 17090, "s": 17078, "text": "nirpendrac9" }, { "code": null, "e": 17107, "s": 17090, "text": "arorakashish0911" }, { "code": null, "e": 17121, "s": 17107, "text": "GauravRajput1" }, { "code": null, "e": 17134, "s": 17121, "text": "ankita_saini" }, { "code": null, "e": 17147, "s": 17134, "text": "technophpfij" }, { "code": null, "e": 17166, "s": 17147, "text": "doubly linked list" }, { "code": null, "e": 17178, "s": 17166, "text": "Linked List" }, { "code": null, "e": 17190, "s": 17178, "text": "Linked List" }, { "code": null, "e": 17288, "s": 17190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17320, "s": 17288, "text": "Introduction to Data Structures" }, { "code": null, "e": 17350, "s": 17320, "text": "Merge two sorted linked lists" }, { "code": null, "e": 17414, "s": 17350, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 17453, "s": 17414, "text": "Find the middle of a given linked list" }, { "code": null, "e": 17474, "s": 17453, "text": "Linked List vs Array" }, { "code": null, "e": 17502, "s": 17474, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 17549, "s": 17502, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 17604, "s": 17549, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 17656, "s": 17604, "text": "Add two numbers represented by linked lists | Set 1" } ]
Remove all consecutive duplicates from the string
15 Nov, 2021 Given a string S, remove all the consecutive duplicates. Note that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters. Examples: Input : aaaaabbbbbb Output : ab Input : geeksforgeeks Output : geksforgeks Input : aabccba Output : abcba Recursive Solution: The above problem can be solved using recursion. If the string is empty, return.Else compare the adjacent characters of the string. If they are same then shift the characters one by one to the left. Call recursion on string SIf they not same then call recursion from S+1 string. If the string is empty, return. Else compare the adjacent characters of the string. If they are same then shift the characters one by one to the left. Call recursion on string S If they not same then call recursion from S+1 string. The recursion tree for the string S = aabcca is shown below. aabcca S = aabcca / abcca S = abcca / bcca S = abcca / cca S = abcca / ca S = abca / a S = abca (Output String) / empty string Below is the implementation of the above approach: C++ Java Python3 C# Javascript // Recursive Program to remove consecutive// duplicates from string S.#include <bits/stdc++.h>using namespace std; // A recursive function that removes// consecutive duplicates from string Svoid removeDuplicates(char* S){ // When string is empty, return if (S[0] == '\0') return; // if the adjacent characters are same if (S[0] == S[1]) { // Shift character by one to left int i = 0; while (S[i] != '\0') { S[i] = S[i + 1]; i++; } // Check on Updated String S removeDuplicates(S); } // If the adjacent characters are not same // Check from S+1 string address removeDuplicates(S + 1);} // Driver Programint main(){ char S1[] = "geeksforgeeks"; removeDuplicates(S1); cout << S1 << endl; char S2[] = "aabcca"; removeDuplicates(S2); cout << S2 << endl; return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { public static String removeConsecutiveDuplicates(String input) { if(input.length()<=1) return input; if(input.charAt(0)==input.charAt(1)) return removeConsecutiveDuplicates(input.substring(1)); else return input.charAt(0) + removeConsecutiveDuplicates(input.substring(1)); } public static void main(String[] args) { String S1 = "geeksforgeeks"; System.out.println(removeConsecutiveDuplicates(S1)); String S2 = "aabcca"; System.out.println(removeConsecutiveDuplicates(S2)); }} # Recursive Program to remove consecutive# duplicates from string S.def removeConsecutiveDuplicates(s): if len(s)<2: return s if s[0]!=s[1]: return s[0]+removeConsecutiveDuplicates(s[1:]) return removeConsecutiveDuplicates(s[1:]) # This code is contributed by direwolf707s1='geeksforgeeks'print(removeConsecutiveDuplicates(s1)) #geksforgekss2='aabcca'print(removeConsecutiveDuplicates(s2)) #ab # This code is contributed by rahulsood707. /*package whatever //do not write package name here */using System; class GFG { public static string removeConsecutiveDuplicates(string input) { if(input.Length <= 1) return input; if(input[0] == input[1]) return removeConsecutiveDuplicates(input.Substring(1)); else return input[0] + removeConsecutiveDuplicates(input.Substring(1)); } public static void Main(String[] args) { string S1 = "geeksforgeeks"; Console.WriteLine(removeConsecutiveDuplicates(S1)); string S2 = "aabcca"; Console.Write(removeConsecutiveDuplicates(S2)); }} // This code is contributed by shivanisinghss2110 <script> function removeConsecutiveDuplicates(input){ if(input.length<=1) return input; if(input[0]==input[1]) return removeConsecutiveDuplicates(input.substring(1)); else return input[0] + removeConsecutiveDuplicates(input.substring(1));} let S1 = "geeksforgeeks";document.write(removeConsecutiveDuplicates(S1)+"<br>"); let S2 = "aabcca";document.write(removeConsecutiveDuplicates(S2)+"<br>"); // This code is contributed by rag2127 </script> geksforgeks abca The worst case time complexity of the above solution is O(n2). The worst case happens when all characters are same. Iterative Solution : The idea is to check if current character is equal to the next character or not . If current character is equal to the next character we’ll ignore it and when it is not equal we will add it to our answer. Since, the last element will not checked we will push it at the end of the string. For eg: s=”aaaaa” when we run the loop str=”” so at the end we’ll add ‘a’ because it is the last element. C++ Java Python3 C# Javascript // C++ program to remove consecutive// duplicates from a given string.#include <bits/stdc++.h>using namespace std; // A iterative function that removes // consecutive duplicates from string Sstring removeDuplicates(string s){ int n = s.length(); string str=""; // We don't need to do anything for // empty string. if (n == 0) return str; // Traversing string for(int i=0;i<n-1;i++){ //checking if s[i] is not same as s[i+1] then add it into str if(s[i]!=s[i+1]){ str+=s[i]; } } //Since the last character will not be inserted in the loop we add it at the end str.push_back(s[n-1]); return str; } // Driver Programint main() { string s1 = "geeksforgeeks"; cout << removeDuplicates(s1) << endl; string s2 = "aabcca"; cout << removeDuplicates(s2) << endl; return 0;} // Java program to remove consecutive// duplicates from a given string.import java.util.*; class GFG{ // A iterative function that removes // consecutive duplicates from string S static void removeDuplicates(char[] S) { int n = S.length; // We don't need to do anything for // empty or single character string. if (n < 2) { return; } // j is used to store index is result // string (or index of current distinct // character) int j = 0; // Traversing string for (int i = 1; i < n; i++) { // If current character S[i] // is different from S[j] if (S[j] != S[i]) { j++; S[j] = S[i]; } } System.out.println(Arrays.copyOfRange(S, 0, j + 1)); } // Driver code public static void main(String[] args) { char S1[] = "geeksforgeeks".toCharArray(); removeDuplicates(S1); char S2[] = "aabcca".toCharArray(); removeDuplicates(S2); }} /* This code contributed by PrinciRaj1992 */ # Python3 program to remove consecutive# duplicates from a given string. # A iterative function that removes# consecutive duplicates from string Sdef removeDuplicates(S): n = len(S) # We don't need to do anything for # empty or single character string. if (n < 2) : return # j is used to store index is result # string (or index of current distinct # character) j = 0 # Traversing string for i in range(n): # If current character S[i] # is different from S[j] if (S[j] != S[i]): j += 1 S[j] = S[i] # Putting string termination # character. j += 1 S = S[:j] return S # Driver Codeif __name__ == '__main__': S1 = "geeksforgeeks" S1 = list(S1.rstrip()) S1 = removeDuplicates(S1) print(*S1, sep = "") S2 = "aabcca" S2 = list(S2.rstrip()) S2 = removeDuplicates(S2) print(*S2, sep = "") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to remove consecutive// duplicates from a given string.using System; class GFG{ // A iterative function that removes // consecutive duplicates from string S static void removeDuplicates(char[] S) { int n = S.Length; // We don't need to do anything for // empty or single character string. if (n < 2) { return; } // j is used to store index is result // string (or index of current distinct // character) int j = 0; // Traversing string for (int i = 1; i < n; i++) { // If current character S[i] // is different from S[j] if (S[j] != S[i]) { j++; S[j] = S[i]; } } char []A = new char[j+1]; Array.Copy(S,0, A, 0, j + 1); Console.WriteLine(A); } // Driver code public static void Main(String[] args) { char []S1 = "geeksforgeeks".ToCharArray(); removeDuplicates(S1); char []S2 = "aabcca".ToCharArray(); removeDuplicates(S2); }} // This code is contributed by 29AjayKumar <script> // JavaScript program for the above approach // duplicates from a given string. // A iterative function that removes // consecutive duplicates from string S const removeDuplicates = (s) => { let n = s.length; let str = ""; // We don't need to do anything for // empty string. if (n == 0) return str; // Traversing string for (let i = 0; i < n - 1; i++) { //checking if s[i] is not same as s[i+1] then add it into str if (s[i] != s[i + 1]) { str += s[i]; } } //Since the last character will not be inserted in the loop we add it at the end str += s[n-1]; return str; } // Driver Program let s1 = "geeksforgeeks"; document.write(`${removeDuplicates(s1)}<br/>`) let s2 = "aabcca"; document.write(removeDuplicates(s2)) // This code is contributed by rakeshsahni </script> geksforgeks abca Time Complexity : O(n) Auxiliary Space : O(1) This article is contributed by Ankur Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SHUBHAMSINGH10 princiraj1992 29AjayKumar nidhi_biet le0 rag2127 ankitachandra09 sagartomar9927 rakeshsahni shivanisinghss2110 direwolf707 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not Length of the longest substring without repeating characters Longest Palindromic Substring | Set 1 Convert string to char array in C++ stringstream in C++ and its Applications Iterate over characters of a string in C++ Program to add two binary strings Python | Check if a Substring is Present in a Given String Convert character array to string in C++ How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Nov, 2021" }, { "code": null, "e": 264, "s": 52, "text": "Given a string S, remove all the consecutive duplicates. Note that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters." }, { "code": null, "e": 275, "s": 264, "text": "Examples: " }, { "code": null, "e": 384, "s": 275, "text": "Input : aaaaabbbbbb\nOutput : ab\n\nInput : geeksforgeeks\nOutput : geksforgeks\n\nInput : aabccba\nOutput : abcba" }, { "code": null, "e": 404, "s": 384, "text": "Recursive Solution:" }, { "code": null, "e": 455, "s": 404, "text": "The above problem can be solved using recursion. " }, { "code": null, "e": 685, "s": 455, "text": "If the string is empty, return.Else compare the adjacent characters of the string. If they are same then shift the characters one by one to the left. Call recursion on string SIf they not same then call recursion from S+1 string." }, { "code": null, "e": 717, "s": 685, "text": "If the string is empty, return." }, { "code": null, "e": 863, "s": 717, "text": "Else compare the adjacent characters of the string. If they are same then shift the characters one by one to the left. Call recursion on string S" }, { "code": null, "e": 917, "s": 863, "text": "If they not same then call recursion from S+1 string." }, { "code": null, "e": 980, "s": 917, "text": "The recursion tree for the string S = aabcca is shown below. " }, { "code": null, "e": 1220, "s": 980, "text": " aabcca S = aabcca\n /\n abcca S = abcca \n /\n bcca S = abcca\n /\n cca S = abcca\n /\n ca S = abca\n /\n a S = abca (Output String)\n /\nempty string" }, { "code": null, "e": 1273, "s": 1220, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1277, "s": 1273, "text": "C++" }, { "code": null, "e": 1282, "s": 1277, "text": "Java" }, { "code": null, "e": 1290, "s": 1282, "text": "Python3" }, { "code": null, "e": 1293, "s": 1290, "text": "C#" }, { "code": null, "e": 1304, "s": 1293, "text": "Javascript" }, { "code": "// Recursive Program to remove consecutive// duplicates from string S.#include <bits/stdc++.h>using namespace std; // A recursive function that removes// consecutive duplicates from string Svoid removeDuplicates(char* S){ // When string is empty, return if (S[0] == '\\0') return; // if the adjacent characters are same if (S[0] == S[1]) { // Shift character by one to left int i = 0; while (S[i] != '\\0') { S[i] = S[i + 1]; i++; } // Check on Updated String S removeDuplicates(S); } // If the adjacent characters are not same // Check from S+1 string address removeDuplicates(S + 1);} // Driver Programint main(){ char S1[] = \"geeksforgeeks\"; removeDuplicates(S1); cout << S1 << endl; char S2[] = \"aabcca\"; removeDuplicates(S2); cout << S2 << endl; return 0;}", "e": 2194, "s": 1304, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static String removeConsecutiveDuplicates(String input) { if(input.length()<=1) return input; if(input.charAt(0)==input.charAt(1)) return removeConsecutiveDuplicates(input.substring(1)); else return input.charAt(0) + removeConsecutiveDuplicates(input.substring(1)); } public static void main(String[] args) { String S1 = \"geeksforgeeks\"; System.out.println(removeConsecutiveDuplicates(S1)); String S2 = \"aabcca\"; System.out.println(removeConsecutiveDuplicates(S2)); }}", "e": 2855, "s": 2194, "text": null }, { "code": "# Recursive Program to remove consecutive# duplicates from string S.def removeConsecutiveDuplicates(s): if len(s)<2: return s if s[0]!=s[1]: return s[0]+removeConsecutiveDuplicates(s[1:]) return removeConsecutiveDuplicates(s[1:]) # This code is contributed by direwolf707s1='geeksforgeeks'print(removeConsecutiveDuplicates(s1)) #geksforgekss2='aabcca'print(removeConsecutiveDuplicates(s2)) #ab # This code is contributed by rahulsood707.", "e": 3316, "s": 2855, "text": null }, { "code": "/*package whatever //do not write package name here */using System; class GFG { public static string removeConsecutiveDuplicates(string input) { if(input.Length <= 1) return input; if(input[0] == input[1]) return removeConsecutiveDuplicates(input.Substring(1)); else return input[0] + removeConsecutiveDuplicates(input.Substring(1)); } public static void Main(String[] args) { string S1 = \"geeksforgeeks\"; Console.WriteLine(removeConsecutiveDuplicates(S1)); string S2 = \"aabcca\"; Console.Write(removeConsecutiveDuplicates(S2)); }} // This code is contributed by shivanisinghss2110", "e": 3997, "s": 3316, "text": null }, { "code": "<script> function removeConsecutiveDuplicates(input){ if(input.length<=1) return input; if(input[0]==input[1]) return removeConsecutiveDuplicates(input.substring(1)); else return input[0] + removeConsecutiveDuplicates(input.substring(1));} let S1 = \"geeksforgeeks\";document.write(removeConsecutiveDuplicates(S1)+\"<br>\"); let S2 = \"aabcca\";document.write(removeConsecutiveDuplicates(S2)+\"<br>\"); // This code is contributed by rag2127 </script>", "e": 4504, "s": 3997, "text": null }, { "code": null, "e": 4521, "s": 4504, "text": "geksforgeks\nabca" }, { "code": null, "e": 4639, "s": 4521, "text": "The worst case time complexity of the above solution is O(n2). The worst case happens when all characters are same. " }, { "code": null, "e": 4660, "s": 4639, "text": "Iterative Solution :" }, { "code": null, "e": 4966, "s": 4660, "text": "The idea is to check if current character is equal to the next character or not . If current character is equal to the next character we’ll ignore it and when it is not equal we will add it to our answer. Since, the last element will not checked we will push it at the end of the string. For eg: s=”aaaaa”" }, { "code": null, "e": 5054, "s": 4966, "text": "when we run the loop str=”” so at the end we’ll add ‘a’ because it is the last element." }, { "code": null, "e": 5058, "s": 5054, "text": "C++" }, { "code": null, "e": 5063, "s": 5058, "text": "Java" }, { "code": null, "e": 5071, "s": 5063, "text": "Python3" }, { "code": null, "e": 5074, "s": 5071, "text": "C#" }, { "code": null, "e": 5085, "s": 5074, "text": "Javascript" }, { "code": "// C++ program to remove consecutive// duplicates from a given string.#include <bits/stdc++.h>using namespace std; // A iterative function that removes // consecutive duplicates from string Sstring removeDuplicates(string s){ int n = s.length(); string str=\"\"; // We don't need to do anything for // empty string. if (n == 0) return str; // Traversing string for(int i=0;i<n-1;i++){ //checking if s[i] is not same as s[i+1] then add it into str if(s[i]!=s[i+1]){ str+=s[i]; } } //Since the last character will not be inserted in the loop we add it at the end str.push_back(s[n-1]); return str; } // Driver Programint main() { string s1 = \"geeksforgeeks\"; cout << removeDuplicates(s1) << endl; string s2 = \"aabcca\"; cout << removeDuplicates(s2) << endl; return 0;}", "e": 5947, "s": 5085, "text": null }, { "code": "// Java program to remove consecutive// duplicates from a given string.import java.util.*; class GFG{ // A iterative function that removes // consecutive duplicates from string S static void removeDuplicates(char[] S) { int n = S.length; // We don't need to do anything for // empty or single character string. if (n < 2) { return; } // j is used to store index is result // string (or index of current distinct // character) int j = 0; // Traversing string for (int i = 1; i < n; i++) { // If current character S[i] // is different from S[j] if (S[j] != S[i]) { j++; S[j] = S[i]; } } System.out.println(Arrays.copyOfRange(S, 0, j + 1)); } // Driver code public static void main(String[] args) { char S1[] = \"geeksforgeeks\".toCharArray(); removeDuplicates(S1); char S2[] = \"aabcca\".toCharArray(); removeDuplicates(S2); }} /* This code contributed by PrinciRaj1992 */", "e": 7076, "s": 5947, "text": null }, { "code": "# Python3 program to remove consecutive# duplicates from a given string. # A iterative function that removes# consecutive duplicates from string Sdef removeDuplicates(S): n = len(S) # We don't need to do anything for # empty or single character string. if (n < 2) : return # j is used to store index is result # string (or index of current distinct # character) j = 0 # Traversing string for i in range(n): # If current character S[i] # is different from S[j] if (S[j] != S[i]): j += 1 S[j] = S[i] # Putting string termination # character. j += 1 S = S[:j] return S # Driver Codeif __name__ == '__main__': S1 = \"geeksforgeeks\" S1 = list(S1.rstrip()) S1 = removeDuplicates(S1) print(*S1, sep = \"\") S2 = \"aabcca\" S2 = list(S2.rstrip()) S2 = removeDuplicates(S2) print(*S2, sep = \"\") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 8101, "s": 7076, "text": null }, { "code": "// C# program to remove consecutive// duplicates from a given string.using System; class GFG{ // A iterative function that removes // consecutive duplicates from string S static void removeDuplicates(char[] S) { int n = S.Length; // We don't need to do anything for // empty or single character string. if (n < 2) { return; } // j is used to store index is result // string (or index of current distinct // character) int j = 0; // Traversing string for (int i = 1; i < n; i++) { // If current character S[i] // is different from S[j] if (S[j] != S[i]) { j++; S[j] = S[i]; } } char []A = new char[j+1]; Array.Copy(S,0, A, 0, j + 1); Console.WriteLine(A); } // Driver code public static void Main(String[] args) { char []S1 = \"geeksforgeeks\".ToCharArray(); removeDuplicates(S1); char []S2 = \"aabcca\".ToCharArray(); removeDuplicates(S2); }} // This code is contributed by 29AjayKumar", "e": 9263, "s": 8101, "text": null }, { "code": "<script> // JavaScript program for the above approach // duplicates from a given string. // A iterative function that removes // consecutive duplicates from string S const removeDuplicates = (s) => { let n = s.length; let str = \"\"; // We don't need to do anything for // empty string. if (n == 0) return str; // Traversing string for (let i = 0; i < n - 1; i++) { //checking if s[i] is not same as s[i+1] then add it into str if (s[i] != s[i + 1]) { str += s[i]; } } //Since the last character will not be inserted in the loop we add it at the end str += s[n-1]; return str; } // Driver Program let s1 = \"geeksforgeeks\"; document.write(`${removeDuplicates(s1)}<br/>`) let s2 = \"aabcca\"; document.write(removeDuplicates(s2)) // This code is contributed by rakeshsahni </script>", "e": 10228, "s": 9263, "text": null }, { "code": null, "e": 10245, "s": 10228, "text": "geksforgeks\nabca" }, { "code": null, "e": 10269, "s": 10245, "text": "Time Complexity : O(n) " }, { "code": null, "e": 10292, "s": 10269, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 10587, "s": 10292, "text": "This article is contributed by Ankur Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 10712, "s": 10587, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10727, "s": 10712, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 10741, "s": 10727, "text": "princiraj1992" }, { "code": null, "e": 10753, "s": 10741, "text": "29AjayKumar" }, { "code": null, "e": 10764, "s": 10753, "text": "nidhi_biet" }, { "code": null, "e": 10768, "s": 10764, "text": "le0" }, { "code": null, "e": 10776, "s": 10768, "text": "rag2127" }, { "code": null, "e": 10792, "s": 10776, "text": "ankitachandra09" }, { "code": null, "e": 10807, "s": 10792, "text": "sagartomar9927" }, { "code": null, "e": 10819, "s": 10807, "text": "rakeshsahni" }, { "code": null, "e": 10838, "s": 10819, "text": "shivanisinghss2110" }, { "code": null, "e": 10850, "s": 10838, "text": "direwolf707" }, { "code": null, "e": 10858, "s": 10850, "text": "Strings" }, { "code": null, "e": 10866, "s": 10858, "text": "Strings" }, { "code": null, "e": 10964, "s": 10866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11021, "s": 10964, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 11082, "s": 11021, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 11120, "s": 11082, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 11156, "s": 11120, "text": "Convert string to char array in C++" }, { "code": null, "e": 11197, "s": 11156, "text": "stringstream in C++ and its Applications" }, { "code": null, "e": 11240, "s": 11197, "text": "Iterate over characters of a string in C++" }, { "code": null, "e": 11274, "s": 11240, "text": "Program to add two binary strings" }, { "code": null, "e": 11333, "s": 11274, "text": "Python | Check if a Substring is Present in a Given String" }, { "code": null, "e": 11374, "s": 11333, "text": "Convert character array to string in C++" } ]
Trigonometric Functions in Java with Examples
27 May, 2019 The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. Java.lang.Math.sin() Method : is an inbuilt method which returns the sine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.sin(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the sine of the specified double value passed.Example 1 : Program demonstrating the use of sin()// Java program for sin() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // sin() method to get the sine value double sinValue = Math.sin(radians); // prints the sine value System.out.println("sin(" + degrees + ") = " + sinValue); }}Output:sin(45.0) = 0.7071067811865475 Java.lang.Math.cos() : is an inbuilt method which returns the cosine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN.Syntax :Math.cos(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the cosine of the specified double value passed.Example 2 : Program demonstrating the use of cos()// Java program for cos() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the cosine value double cosValue = Math.cos(radians); // prints the cosine value System.out.println("cos(" + degrees + ") = " + cosValue); }}Output:cos(45.0) = 0.7071067811865476 Java.lang.Math.tan() : is an inbuilt method which returns the tangent of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.tan(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the tangent of the specified double value passed.Example 3 : Program demonstrating the use of tan()// Java program for tan() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the tangent value double tanValue = Math.tan(radians); // prints the tangent value System.out.println("tan(" + degrees + ") = " + tanValue); }}Output:tan(45.0) = 0.9999999999999999 Java.lang.Math.sin() Method : is an inbuilt method which returns the sine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.sin(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the sine of the specified double value passed.Example 1 : Program demonstrating the use of sin()// Java program for sin() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // sin() method to get the sine value double sinValue = Math.sin(radians); // prints the sine value System.out.println("sin(" + degrees + ") = " + sinValue); }}Output:sin(45.0) = 0.7071067811865475 Syntax : Math.sin(double radians) Parameters :The method takes one mandatory argument in radians. Returns :It returns a double value. The returned value is the sine of the specified double value passed. Example 1 : Program demonstrating the use of sin() // Java program for sin() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // sin() method to get the sine value double sinValue = Math.sin(radians); // prints the sine value System.out.println("sin(" + degrees + ") = " + sinValue); }} Output: sin(45.0) = 0.7071067811865475 Java.lang.Math.cos() : is an inbuilt method which returns the cosine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN.Syntax :Math.cos(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the cosine of the specified double value passed.Example 2 : Program demonstrating the use of cos()// Java program for cos() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the cosine value double cosValue = Math.cos(radians); // prints the cosine value System.out.println("cos(" + degrees + ") = " + cosValue); }}Output:cos(45.0) = 0.7071067811865476 Syntax : Math.cos(double radians) Parameters :The method takes one mandatory argument in radians. Returns :It returns a double value. The returned value is the cosine of the specified double value passed. Example 2 : Program demonstrating the use of cos() // Java program for cos() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the cosine value double cosValue = Math.cos(radians); // prints the cosine value System.out.println("cos(" + degrees + ") = " + cosValue); }} Output: cos(45.0) = 0.7071067811865476 Java.lang.Math.tan() : is an inbuilt method which returns the tangent of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.tan(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the tangent of the specified double value passed.Example 3 : Program demonstrating the use of tan()// Java program for tan() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the tangent value double tanValue = Math.tan(radians); // prints the tangent value System.out.println("tan(" + degrees + ") = " + tanValue); }}Output:tan(45.0) = 0.9999999999999999 Math.tan(double radians) Parameters :The method takes one mandatory argument in radians. Returns :It returns a double value. The returned value is the tangent of the specified double value passed. Example 3 : Program demonstrating the use of tan() // Java program for tan() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the tangent value double tanValue = Math.tan(radians); // prints the tangent value System.out.println("tan(" + degrees + ") = " + tanValue); }} Output: tan(45.0) = 0.9999999999999999 ShubhamMaurya3 Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java Initialize an ArrayList in Java Introduction to Java
[ { "code": null, "e": 28, "s": 0, "text": "\n27 May, 2019" }, { "code": null, "e": 189, "s": 28, "text": "The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions." }, { "code": null, "e": 3256, "s": 189, "text": "Java.lang.Math.sin() Method : is an inbuilt method which returns the sine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.sin(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the sine of the specified double value passed.Example 1 : Program demonstrating the use of sin()// Java program for sin() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // sin() method to get the sine value double sinValue = Math.sin(radians); // prints the sine value System.out.println(\"sin(\" + degrees + \") = \" + sinValue); }}Output:sin(45.0) = 0.7071067811865475\nJava.lang.Math.cos() : is an inbuilt method which returns the cosine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN.Syntax :Math.cos(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the cosine of the specified double value passed.Example 2 : Program demonstrating the use of cos()// Java program for cos() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the cosine value double cosValue = Math.cos(radians); // prints the cosine value System.out.println(\"cos(\" + degrees + \") = \" + cosValue); }}Output:cos(45.0) = 0.7071067811865476\nJava.lang.Math.tan() : is an inbuilt method which returns the tangent of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.tan(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the tangent of the specified double value passed.Example 3 : Program demonstrating the use of tan()// Java program for tan() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the tangent value double tanValue = Math.tan(radians); // prints the tangent value System.out.println(\"tan(\" + degrees + \") = \" + tanValue); }}Output:tan(45.0) = 0.9999999999999999\n" }, { "code": null, "e": 4306, "s": 3256, "text": "Java.lang.Math.sin() Method : is an inbuilt method which returns the sine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.sin(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the sine of the specified double value passed.Example 1 : Program demonstrating the use of sin()// Java program for sin() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // sin() method to get the sine value double sinValue = Math.sin(radians); // prints the sine value System.out.println(\"sin(\" + degrees + \") = \" + sinValue); }}Output:sin(45.0) = 0.7071067811865475\n" }, { "code": null, "e": 4315, "s": 4306, "text": "Syntax :" }, { "code": null, "e": 4340, "s": 4315, "text": "Math.sin(double radians)" }, { "code": null, "e": 4404, "s": 4340, "text": "Parameters :The method takes one mandatory argument in radians." }, { "code": null, "e": 4509, "s": 4404, "text": "Returns :It returns a double value. The returned value is the sine of the specified double value passed." }, { "code": null, "e": 4560, "s": 4509, "text": "Example 1 : Program demonstrating the use of sin()" }, { "code": "// Java program for sin() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // sin() method to get the sine value double sinValue = Math.sin(radians); // prints the sine value System.out.println(\"sin(\" + degrees + \") = \" + sinValue); }}", "e": 5008, "s": 4560, "text": null }, { "code": null, "e": 5016, "s": 5008, "text": "Output:" }, { "code": null, "e": 5048, "s": 5016, "text": "sin(45.0) = 0.7071067811865475\n" }, { "code": null, "e": 6012, "s": 5048, "text": "Java.lang.Math.cos() : is an inbuilt method which returns the cosine of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN.Syntax :Math.cos(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the cosine of the specified double value passed.Example 2 : Program demonstrating the use of cos()// Java program for cos() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the cosine value double cosValue = Math.cos(radians); // prints the cosine value System.out.println(\"cos(\" + degrees + \") = \" + cosValue); }}Output:cos(45.0) = 0.7071067811865476\n" }, { "code": null, "e": 6021, "s": 6012, "text": "Syntax :" }, { "code": null, "e": 6046, "s": 6021, "text": "Math.cos(double radians)" }, { "code": null, "e": 6110, "s": 6046, "text": "Parameters :The method takes one mandatory argument in radians." }, { "code": null, "e": 6217, "s": 6110, "text": "Returns :It returns a double value. The returned value is the cosine of the specified double value passed." }, { "code": null, "e": 6268, "s": 6217, "text": "Example 2 : Program demonstrating the use of cos()" }, { "code": "// Java program for cos() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the cosine value double cosValue = Math.cos(radians); // prints the cosine value System.out.println(\"cos(\" + degrees + \") = \" + cosValue); }}", "e": 6720, "s": 6268, "text": null }, { "code": null, "e": 6728, "s": 6720, "text": "Output:" }, { "code": null, "e": 6760, "s": 6728, "text": "cos(45.0) = 0.7071067811865476\n" }, { "code": null, "e": 7815, "s": 6760, "text": "Java.lang.Math.tan() : is an inbuilt method which returns the tangent of the value passed as an argument. The value passed in this function should be in radians. If the argument is NaN or an infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.Syntax :Math.tan(double radians)Parameters :The method takes one mandatory argument in radians.Returns :It returns a double value. The returned value is the tangent of the specified double value passed.Example 3 : Program demonstrating the use of tan()// Java program for tan() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the tangent value double tanValue = Math.tan(radians); // prints the tangent value System.out.println(\"tan(\" + degrees + \") = \" + tanValue); }}Output:tan(45.0) = 0.9999999999999999\n" }, { "code": null, "e": 7840, "s": 7815, "text": "Math.tan(double radians)" }, { "code": null, "e": 7904, "s": 7840, "text": "Parameters :The method takes one mandatory argument in radians." }, { "code": null, "e": 8012, "s": 7904, "text": "Returns :It returns a double value. The returned value is the tangent of the specified double value passed." }, { "code": null, "e": 8063, "s": 8012, "text": "Example 3 : Program demonstrating the use of tan()" }, { "code": "// Java program for tan() methodimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { double degrees = 45.0; // convert degrees to radians double radians = Math.toRadians(degrees); // cos() method to get the tangent value double tanValue = Math.tan(radians); // prints the tangent value System.out.println(\"tan(\" + degrees + \") = \" + tanValue); }}", "e": 8517, "s": 8063, "text": null }, { "code": null, "e": 8525, "s": 8517, "text": "Output:" }, { "code": null, "e": 8557, "s": 8525, "text": "tan(45.0) = 0.9999999999999999\n" }, { "code": null, "e": 8572, "s": 8557, "text": "ShubhamMaurya3" }, { "code": null, "e": 8590, "s": 8572, "text": "Java-lang package" }, { "code": null, "e": 8595, "s": 8590, "text": "Java" }, { "code": null, "e": 8600, "s": 8595, "text": "Java" }, { "code": null, "e": 8698, "s": 8600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8717, "s": 8698, "text": "Interfaces in Java" }, { "code": null, "e": 8732, "s": 8717, "text": "Stream In Java" }, { "code": null, "e": 8750, "s": 8732, "text": "ArrayList in Java" }, { "code": null, "e": 8770, "s": 8750, "text": "Collections in Java" }, { "code": null, "e": 8794, "s": 8770, "text": "Singleton Class in Java" }, { "code": null, "e": 8826, "s": 8794, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8838, "s": 8826, "text": "Set in Java" }, { "code": null, "e": 8858, "s": 8838, "text": "Stack Class in Java" }, { "code": null, "e": 8890, "s": 8858, "text": "Initialize an ArrayList in Java" } ]
Sliding Window Protocol | Set 1 (Sender Side)
27 Jan, 2022 Prerequisite : Stop and Wait ARQ The Stop and Wait ARQ offers error and flow control, but may cause big performance issues as sender always waits for acknowledgement even if it has next packet ready to send. Consider a situation where you have a high bandwidth connection and propagation delay is also high (you are connected to some server in some other country through a high-speed connection), you can’t use this full speed due to limitations of stop and wait. Sliding Window protocol handles this efficiency issue by sending more than one packet at a time with a larger sequence number. The idea is same as pipelining in architecture. Transmission Delay (Tt) – Time to transmit the packet from host to the outgoing link. If B is the Bandwidth of the link and D is the Data Size to transmit Tt = D/B Propagation Delay (Tp) – It is the time taken by the first bit transferred by the host onto the outgoing link to reach the destination. It depends on the distance d and the wave propagation speed s (depends on the characteristics of the medium). Tp = d/s Efficiency – It is defined as the ratio of total useful time to the total cycle time of a packet. For stop and wait protocol, Total cycle time = Tt(data) + Tp(data) + Tt(acknowledgement) + Tp(acknowledgement) = Tt(data) + Tp(data) + Tp(acknowledgement) = Tt + 2*Tp Since acknowledgements are very less in size, their transmission delay can be neglected. Efficiency = Useful Time / Total Cycle Time = Tt/(Tt + 2*Tp) (For Stop and Wait) = 1/(1+2a) [ Using a = Tp/Tt ] Effective Bandwidth(EB) or Throughput – Number of bits sent per second. EB = Data Size(D) / Total Cycle time(Tt + 2*Tp) Multiplying and dividing by Bandwidth (B), = (1/(1+2a)) * B [ Using a = Tp/Tt ] = Efficiency * Bandwidth Capacity of link – If a channel is Full Duplex, then bits can be transferred in both the directions and without any collisions. Number of bits a channel/Link can hold at maximum is its capacity. Capacity = Bandwidth(B) * Propagation(Tp) For Full Duplex channels, Capacity = 2*Bandwidth(B) * Propagation(Tp) In Stop and Wait protocol, only 1 packet is transmitted onto the link and then sender waits for acknowledgement from the receiver. The problem in this setup is that efficiency is very less as we are not filling the channel with more packets after 1st packet has been put onto the link. Within the total cycle time of Tt + 2*Tp units, we will now calculate the maximum number of packets that sender can transmit on the link before getting an acknowledgement. In Tt units ----> 1 packet is Transmitted. In 1 units ----> 1/Tt packet can be Transmitted. In Tt + 2*Tp units -----> (Tt + 2*Tp)/Tt packets can be Transmitted ------> 1 + 2a [Using a = Tp/Tt] Maximum packets That can be Transmitted in total cycle time = 1+2*a Let me explain now with the help of an example. Consider Tt = 1ms, Tp = 1.5ms. In the picture given below, after sender has transmitted packet 0, it will immediately transmit packets 1, 2, 3. Acknowledgement for 0 will arrive after 2*1.5 = 3ms. In Stop and Wait, in time 1 + 2*1.5 = 4ms, we were transferring one packet only. Here we keep a window of packets that we have transmitted but not yet acknowledged. After we have received the Ack for packet 0, window slides and the next packet can be assigned sequence number 0. We reuse the sequence numbers which we have acknowledged so that header size can be kept minimum as shown in the diagram given below. As we have seen above, Maximum window size = 1 + 2*a where a = Tp/Tt Minimum sequence numbers required = 1 + 2*a. All the packets in the current window will be given a sequence number. Number of bits required to represent the sender window = ceil(log2(1+2*a)). But sometimes number of bits in the protocol headers is pre-defined. Size of sequence number field in header will also determine the maximum number of packets that we can send in total cycle time. If N is the size of sequence number field in the header in bits, then we can have 2N sequence numbers. Window Size ws = min(1+2*a, 2N) If you want to calculate minimum bits required to represent sequence numbers/sender window, it will be ceil(log2(ws)). In this article, we have discussed sending window only. For receiving window, there are 2 protocols namely Go Back N and Selective Repeat which are used to implement pipelining practically. We will be discussing receiving window in set 2. This article has been contributed by Pranjul Ahuja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above niharikatanwar61 VishalPal Data Link Layer Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) UDP Server-Client implementation in C Caesar Cipher in Cryptography Advanced Encryption Standard (AES) Intrusion Detection System (IDS)
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jan, 2022" }, { "code": null, "e": 87, "s": 54, "text": "Prerequisite : Stop and Wait ARQ" }, { "code": null, "e": 518, "s": 87, "text": "The Stop and Wait ARQ offers error and flow control, but may cause big performance issues as sender always waits for acknowledgement even if it has next packet ready to send. Consider a situation where you have a high bandwidth connection and propagation delay is also high (you are connected to some server in some other country through a high-speed connection), you can’t use this full speed due to limitations of stop and wait." }, { "code": null, "e": 693, "s": 518, "text": "Sliding Window protocol handles this efficiency issue by sending more than one packet at a time with a larger sequence number. The idea is same as pipelining in architecture." }, { "code": null, "e": 848, "s": 693, "text": "Transmission Delay (Tt) – Time to transmit the packet from host to the outgoing link. If B is the Bandwidth of the link and D is the Data Size to transmit" }, { "code": null, "e": 863, "s": 848, "text": " Tt = D/B " }, { "code": null, "e": 1109, "s": 863, "text": "Propagation Delay (Tp) – It is the time taken by the first bit transferred by the host onto the outgoing link to reach the destination. It depends on the distance d and the wave propagation speed s (depends on the characteristics of the medium)." }, { "code": null, "e": 1123, "s": 1109, "text": " Tp = d/s " }, { "code": null, "e": 1249, "s": 1123, "text": "Efficiency – It is defined as the ratio of total useful time to the total cycle time of a packet. For stop and wait protocol," }, { "code": null, "e": 1436, "s": 1249, "text": "Total cycle time = Tt(data) + Tp(data) + \n Tt(acknowledgement) + Tp(acknowledgement)\n = Tt(data) + Tp(data) + Tp(acknowledgement)\n = Tt + 2*Tp\n" }, { "code": null, "e": 1525, "s": 1436, "text": "Since acknowledgements are very less in size, their transmission delay can be neglected." }, { "code": null, "e": 1662, "s": 1525, "text": "Efficiency = Useful Time / Total Cycle Time \n = Tt/(Tt + 2*Tp) (For Stop and Wait)\n = 1/(1+2a) [ Using a = Tp/Tt ]\n" }, { "code": null, "e": 1734, "s": 1662, "text": "Effective Bandwidth(EB) or Throughput – Number of bits sent per second." }, { "code": null, "e": 1906, "s": 1734, "text": "EB = Data Size(D) / Total Cycle time(Tt + 2*Tp)\nMultiplying and dividing by Bandwidth (B),\n = (1/(1+2a)) * B [ Using a = Tp/Tt ]\n = Efficiency * Bandwidth\n" }, { "code": null, "e": 2101, "s": 1906, "text": "Capacity of link – If a channel is Full Duplex, then bits can be transferred in both the directions and without any collisions. Number of bits a channel/Link can hold at maximum is its capacity." }, { "code": null, "e": 2227, "s": 2101, "text": " Capacity = Bandwidth(B) * Propagation(Tp)\n \n For Full Duplex channels, \n Capacity = 2*Bandwidth(B) * Propagation(Tp)\n" }, { "code": null, "e": 2685, "s": 2227, "text": "In Stop and Wait protocol, only 1 packet is transmitted onto the link and then sender waits for acknowledgement from the receiver. The problem in this setup is that efficiency is very less as we are not filling the channel with more packets after 1st packet has been put onto the link. Within the total cycle time of Tt + 2*Tp units, we will now calculate the maximum number of packets that sender can transmit on the link before getting an acknowledgement." }, { "code": null, "e": 2933, "s": 2685, "text": " In Tt units ----> 1 packet is Transmitted.\n In 1 units ----> 1/Tt packet can be Transmitted.\n In Tt + 2*Tp units -----> (Tt + 2*Tp)/Tt \n packets can be Transmitted\n ------> 1 + 2a [Using a = Tp/Tt]\n" }, { "code": null, "e": 3001, "s": 2933, "text": "Maximum packets That can be Transmitted in total cycle time = 1+2*a" }, { "code": null, "e": 3049, "s": 3001, "text": "Let me explain now with the help of an example." }, { "code": null, "e": 3080, "s": 3049, "text": "Consider Tt = 1ms, Tp = 1.5ms." }, { "code": null, "e": 3411, "s": 3080, "text": "In the picture given below, after sender has transmitted packet 0, it will immediately transmit packets 1, 2, 3. Acknowledgement for 0 will arrive after 2*1.5 = 3ms. In Stop and Wait, in time 1 + 2*1.5 = 4ms, we were transferring one packet only. Here we keep a window of packets that we have transmitted but not yet acknowledged." }, { "code": null, "e": 3659, "s": 3411, "text": "After we have received the Ack for packet 0, window slides and the next packet can be assigned sequence number 0. We reuse the sequence numbers which we have acknowledged so that header size can be kept minimum as shown in the diagram given below." }, { "code": null, "e": 3682, "s": 3659, "text": "As we have seen above," }, { "code": null, "e": 3780, "s": 3682, "text": " Maximum window size = 1 + 2*a where a = Tp/Tt\n\n Minimum sequence numbers required = 1 + 2*a. " }, { "code": null, "e": 3927, "s": 3780, "text": "All the packets in the current window will be given a sequence number. Number of bits required to represent the sender window = ceil(log2(1+2*a))." }, { "code": null, "e": 4227, "s": 3927, "text": "But sometimes number of bits in the protocol headers is pre-defined. Size of sequence number field in header will also determine the maximum number of packets that we can send in total cycle time. If N is the size of sequence number field in the header in bits, then we can have 2N sequence numbers." }, { "code": null, "e": 4259, "s": 4227, "text": "Window Size ws = min(1+2*a, 2N)" }, { "code": null, "e": 4378, "s": 4259, "text": "If you want to calculate minimum bits required to represent sequence numbers/sender window, it will be ceil(log2(ws))." }, { "code": null, "e": 4617, "s": 4378, "text": "In this article, we have discussed sending window only. For receiving window, there are 2 protocols namely Go Back N and Selective Repeat which are used to implement pipelining practically. We will be discussing receiving window in set 2." }, { "code": null, "e": 4793, "s": 4617, "text": "This article has been contributed by Pranjul Ahuja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 4810, "s": 4793, "text": "niharikatanwar61" }, { "code": null, "e": 4820, "s": 4810, "text": "VishalPal" }, { "code": null, "e": 4836, "s": 4820, "text": "Data Link Layer" }, { "code": null, "e": 4854, "s": 4836, "text": "Computer Networks" }, { "code": null, "e": 4872, "s": 4854, "text": "Computer Networks" }, { "code": null, "e": 4970, "s": 4872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5000, "s": 4970, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5029, "s": 5000, "text": "Socket Programming in Python" }, { "code": null, "e": 5063, "s": 5029, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 5089, "s": 5063, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 5119, "s": 5089, "text": "Wireless Application Protocol" }, { "code": null, "e": 5159, "s": 5119, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 5197, "s": 5159, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 5227, "s": 5197, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 5262, "s": 5227, "text": "Advanced Encryption Standard (AES)" } ]
Python Data analysis and Visualization
Pandas is one of the most popular python library for data science and analytics. Pandas library is used for data manipulation, analysis and cleaning. It is a high-level abstraction over low-level NumPy which is written purely in C. In this section, we will cover some of the most important (most often used) things we need to know as an anayst or a data scientist. We can install the required libraries using pip, simply run below command on your command terminal: pip intall pandas First we need to understand two main basic data structure of pandas .i.e. DataFrame and Series. We need to have solid understanding of these two data structure in order to master pandas. Series is an object which is similar to python built-in type list but differs from it because it has associated lable with each element or index. >>> import pandas as pd >>> my_series = pd.Series([12, 24, 36, 48, 60, 72, 84]) >>> my_series 0 12 1 24 2 36 3 48 4 60 5 72 6 84 dtype: int64 In the above output, the ‘index’ is on the left side and ‘value’ on the right. Also each Series object has data type(dtype), in our case its int64. We can retrieve elements by their index number: >>> my_series[6] 84 To provide index(labels) explicity, use: >>> my_series = pd.Series([12, 24, 36, 48, 60, 72, 84], index =['ind0', 'ind1', 'ind2', 'ind3', 'ind4', 'ind5', 'ind6']) >>> my_series ind0 12 ind1 24 ind2 36 ind3 48 ind4 60 ind5 72 ind6 84 dtype: int64 Also it is very easy to retrieve several elements by their indexes or make group assignment: >>> my_series[['ind0', 'ind3', 'ind6']] ind0 12 ind3 48 ind6 84 dtype: int64 >>> my_series[['ind0', 'ind3', 'ind6']] = 36 >>> my_series ind0 36 ind1 24 ind2 36 ind3 36 ind4 60 ind5 72 ind6 36 dtype: int64 Filtering and math operations are easy as well: >>> my_series[my_series>24] ind0 36 ind2 36 ind3 36 ind4 60 ind5 72 ind6 36 dtype: int64 >>> my_series[my_series < 24] * 2 Series([], dtype: int64) >>> my_series ind0 36 ind1 24 ind2 36 ind3 36 ind4 60 ind5 72 ind6 36 dtype: int64 >>> Below are some other common operations on Series. >>> #Work as dictionaries >>> my_series1 = pd.Series({'a':9, 'b':18, 'c':27, 'd': 36}) >>> my_series1 a 9 b 18 c 27 d 36 dtype: int64 >>> #Label attributes >>> my_series1.name = 'Numbers' >>> my_series1.index.name = 'letters' >>> my_series1 letters a 9 b 18 c 27 d 36 Name: Numbers, dtype: int64 >>> #chaning Index >>> my_series1.index = ['w', 'x', 'y', 'z'] >>> my_series1 w 9 x 18 y 27 z 36 Name: Numbers, dtype: int64 >>> DataFrame acts like a table as it contains rows and columns. Each column in a DataFrame is a Series object and rows consist of elements inside Series. DataFrame can be constructed using built-in Python dicts: >>> df = pd.DataFrame({ 'Country': ['China', 'India', 'Indonesia', 'Pakistan'], 'Population': [1420062022, 1368737513, 269536482, 204596442], 'Area' : [9388211, 2973190, 1811570, 770880] }) >>> df Area Country Population 0 9388211 China 1420062022 1 2973190 India 1368737513 2 1811570 Indonesia 269536482 3 770880 Pakistan 204596442 >>> df['Country'] 0 China 1 India 2 Indonesia 3 Pakistan Name: Country, dtype: object >>> df.columns Index(['Area', 'Country', 'Population'], dtype='object') >>> df.index RangeIndex(start=0, stop=4, step=1) >>> There are several ways to provide row index explicitly. >>> df = pd.DataFrame({ 'Country': ['China', 'India', 'Indonesia', 'Pakistan'], 'Population': [1420062022, 1368737513, 269536482, 204596442], 'Landarea' : [9388211, 2973190, 1811570, 770880] }, index = ['CHA', 'IND', 'IDO', 'PAK']) >>> df Country Landarea Population CHA China 9388211 1420062022 IND India 2973190 1368737513 IDO Indonesia 1811570 269536482 PAK Pakistan 770880 204596442 >>> df.index = ['CHI', 'IND', 'IDO', 'PAK'] >>> df.index.name = 'Country Code' >>> df Country Landarea Population Country Code CHI China 9388211 1420062022 IND India 2973190 1368737513 IDO Indonesia 1811570 269536482 PAK Pakistan 770880 204596442 >>> df['Country'] Country Code CHI China IND India IDO Indonesia PAK Pakistan Name: Country, dtype: object Row access using index can be performed in several ways Using .loc and providing index label Using .iloc and providing index number >>> df.loc['IND'] Country India Landarea 2973190 Population 1368737513 Name: IND, dtype: object >>> df.iloc[1] Country India Landarea 2973190 Population 1368737513 Name: IND, dtype: object >>> >>> df.loc[['CHI', 'IND'], 'Population'] Country Code CHI 1420062022 IND 1368737513 Name: Population, dtype: int64 Pandas supports many popular file formats including CSV, XML, HTML, Excel, SQL, JSON many more. Most commonly CSV file format is used. To read a csv file, just run: >>> df = pd.read_csv('GDP.csv', sep = ',') Named argument sep points to a separator character in CSV file called GDP.csv. In order to group data in pandas we can use .groupby method. To demonstrate the use of aggregates and grouping in pandas I have used the Titanic dataset, you can find the same from below link: https://yadi.sk/d/TfhJdE2k3EyALt >>> titanic_df = pd.read_csv('titanic.csv') >>> print(titanic_df.head()) PassengerID Name PClass Age \ 0 1 Allen, Miss Elisabeth Walton 1st 29.00 1 2 Allison, Miss Helen Loraine 1st 2.00 2 3 Allison, Mr Hudson Joshua Creighton 1st 30.00 3 4 Allison, Mrs Hudson JC (Bessie Waldo Daniels) 1st 25.00 4 5 Allison, Master Hudson Trevor 1st 0.92 Sex Survived SexCode 0 female 1 1 1 female 0 1 2 male 0 0 3 female 0 1 4 male 1 0 >>> Let’s calculate how many passengers (women and men) survived and how many did not, we will use .groupby >>> print(titanic_df.groupby(['Sex', 'Survived'])['PassengerID'].count()) Sex Survived female 0 154 1 308 male 0 709 1 142 Name: PassengerID, dtype: int64 Above data based on cabin class: >>> print(titanic_df.groupby(['PClass', 'Survived'])['PassengerID'].count()) PClass Survived * 0 1 1st 0 129 1 193 2nd 0 160 1 119 3rd 0 573 1 138 Name: PassengerID, dtype: int64 Pandas was created to analyse time series data. In order to illustrate, I have used the amazon 5 years stock prices. You can download it from below link, https://finance.yahoo.com/quote/AMZN/history?period1=1397413800&period2=1555180200&interval=1mo&filter=history&frequency=1mo >>> import pandas as pd >>> amzn_df = pd.read_csv('AMZN.csv', index_col='Date', parse_dates=True) >>> amzn_df = amzn_df.sort_index() >>> print(amzn_df.info()) <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 62 entries, 2014-04-01 to 2019-04-12 Data columns (total 6 columns): Open 62 non-null object High 62 non-null object Low 62 non-null object Close 62 non-null object Adj Close 62 non-null object Volume 62 non-null object dtypes: object(6) memory usage: 1.9+ KB None Above we have created a DataFRame with DatetimeIndex by Date column and then sort it. And the mean closing price is, >>> amzn_df.loc['2015-04', 'Close'].mean() 421.779999 We can use matplotlib library to visualize pandas. Let’s take our amazon stock historical dataset and look into its price movement of specific time period over graph. >>> import matplotlib.pyplot as plt >>> df = pd.read_csv('AMZN.csv', index_col = 'Date' , parse_dates = True) >>> new_df = df.loc['2014-06':'2018-08', ['Close']] >>> new_df=new_df.astype(float) >>> new_df.plot() <matplotlib.axes._subplots.AxesSubplot object at 0x0B9B8930> >>> plt.show()
[ { "code": null, "e": 1427, "s": 1062, "text": "Pandas is one of the most popular python library for data science and analytics. Pandas library is used for data manipulation, analysis and cleaning. It is a high-level abstraction over low-level NumPy which is written purely in C. In this section, we will cover some of the most important (most often used) things we need to know as an anayst or a data scientist." }, { "code": null, "e": 1527, "s": 1427, "text": "We can install the required libraries using pip, simply run below command on your command terminal:" }, { "code": null, "e": 1545, "s": 1527, "text": "pip intall pandas" }, { "code": null, "e": 1732, "s": 1545, "text": "First we need to understand two main basic data structure of pandas .i.e. DataFrame and Series. We need to have solid understanding of these two data structure in order to master pandas." }, { "code": null, "e": 1878, "s": 1732, "text": "Series is an object which is similar to python built-in type list but differs from it because it has associated lable with each element or index." }, { "code": null, "e": 2020, "s": 1878, "text": ">>> import pandas as pd\n>>> my_series = pd.Series([12, 24, 36, 48, 60, 72, 84])\n>>> my_series\n0 12\n1 24\n2 36\n3 48\n4 60\n5 72\n6 84\ndtype: int64" }, { "code": null, "e": 2168, "s": 2020, "text": "In the above output, the ‘index’ is on the left side and ‘value’ on the right. Also each Series object has data type(dtype), in our case its int64." }, { "code": null, "e": 2216, "s": 2168, "text": "We can retrieve elements by their index number:" }, { "code": null, "e": 2236, "s": 2216, "text": ">>> my_series[6]\n84" }, { "code": null, "e": 2277, "s": 2236, "text": "To provide index(labels) explicity, use:" }, { "code": null, "e": 2481, "s": 2277, "text": ">>> my_series = pd.Series([12, 24, 36, 48, 60, 72, 84], index =['ind0', 'ind1', 'ind2', 'ind3', 'ind4', 'ind5', 'ind6'])\n>>> my_series\nind0 12\nind1 24\nind2 36\nind3 48\nind4 60\nind5 72\nind6 84\ndtype: int64" }, { "code": null, "e": 2574, "s": 2481, "text": "Also it is very easy to retrieve several elements by their indexes or make group assignment:" }, { "code": null, "e": 2779, "s": 2574, "text": ">>> my_series[['ind0', 'ind3', 'ind6']]\nind0 12\nind3 48\nind6 84\ndtype: int64\n>>> my_series[['ind0', 'ind3', 'ind6']] = 36\n>>> my_series\nind0 36\nind1 24\nind2 36\nind3 36\nind4 60\nind5 72\nind6 36\ndtype: int64" }, { "code": null, "e": 2827, "s": 2779, "text": "Filtering and math operations are easy as well:" }, { "code": null, "e": 3062, "s": 2827, "text": ">>> my_series[my_series>24]\nind0 36\nind2 36\nind3 36\nind4 60\nind5 72\nind6 36\ndtype: int64\n>>> my_series[my_series < 24] * 2\nSeries([], dtype: int64)\n>>> my_series\nind0 36\nind1 24\nind2 36\nind3 36\nind4 60\nind5 72\nind6 36\ndtype: int64\n>>>" }, { "code": null, "e": 3112, "s": 3062, "text": "Below are some other common operations on Series." }, { "code": null, "e": 3537, "s": 3112, "text": ">>> #Work as dictionaries\n>>> my_series1 = pd.Series({'a':9, 'b':18, 'c':27, 'd': 36})\n>>> my_series1\na 9\nb 18\nc 27\nd 36\ndtype: int64\n>>> #Label attributes\n>>> my_series1.name = 'Numbers'\n>>> my_series1.index.name = 'letters'\n>>> my_series1\nletters\na 9\nb 18\nc 27\nd 36\nName: Numbers, dtype: int64\n>>> #chaning Index\n>>> my_series1.index = ['w', 'x', 'y', 'z']\n>>> my_series1\nw 9\nx 18\ny 27\nz 36\nName: Numbers, dtype: int64\n>>>" }, { "code": null, "e": 3688, "s": 3537, "text": "DataFrame acts like a table as it contains rows and columns. Each column in a DataFrame is a Series object and rows consist of elements inside Series." }, { "code": null, "e": 3746, "s": 3688, "text": "DataFrame can be constructed using built-in Python dicts:" }, { "code": null, "e": 4326, "s": 3746, "text": ">>> df = pd.DataFrame({\n 'Country': ['China', 'India', 'Indonesia', 'Pakistan'],\n 'Population': [1420062022, 1368737513, 269536482, 204596442],\n 'Area' : [9388211, 2973190, 1811570, 770880]\n})\n>>> df\n Area Country Population\n0 9388211 China 1420062022\n1 2973190 India 1368737513\n2 1811570 Indonesia 269536482\n3 770880 Pakistan 204596442\n>>> df['Country']\n0 China\n1 India\n2 Indonesia\n3 Pakistan\nName: Country, dtype: object\n>>> df.columns\nIndex(['Area', 'Country', 'Population'], dtype='object')\n>>> df.index\nRangeIndex(start=0, stop=4, step=1)\n>>>" }, { "code": null, "e": 4382, "s": 4326, "text": "There are several ways to provide row index explicitly." }, { "code": null, "e": 5132, "s": 4382, "text": ">>> df = pd.DataFrame({\n 'Country': ['China', 'India', 'Indonesia', 'Pakistan'],\n 'Population': [1420062022, 1368737513, 269536482, 204596442],\n 'Landarea' : [9388211, 2973190, 1811570, 770880]\n}, index = ['CHA', 'IND', 'IDO', 'PAK'])\n>>> df\nCountry Landarea Population\nCHA China 9388211 1420062022\nIND India 2973190 1368737513\nIDO Indonesia 1811570 269536482\nPAK Pakistan 770880 204596442\n>>> df.index = ['CHI', 'IND', 'IDO', 'PAK']\n>>> df.index.name = 'Country Code'\n>>> df\nCountry Landarea Population\nCountry Code\nCHI China 9388211 1420062022\nIND India 2973190 1368737513\nIDO Indonesia 1811570 269536482\nPAK Pakistan 770880 204596442\n>>> df['Country']\nCountry Code\nCHI China\nIND India\nIDO Indonesia\nPAK Pakistan\nName: Country, dtype: object" }, { "code": null, "e": 5188, "s": 5132, "text": "Row access using index can be performed in several ways" }, { "code": null, "e": 5225, "s": 5188, "text": "Using .loc and providing index label" }, { "code": null, "e": 5264, "s": 5225, "text": "Using .iloc and providing index number" }, { "code": null, "e": 5608, "s": 5264, "text": ">>> df.loc['IND']\nCountry India\nLandarea 2973190\nPopulation 1368737513\nName: IND, dtype: object\n>>> df.iloc[1]\nCountry India\nLandarea 2973190\nPopulation 1368737513\nName: IND, dtype: object\n>>>\n>>> df.loc[['CHI', 'IND'], 'Population']\nCountry Code\nCHI 1420062022\nIND 1368737513\nName: Population, dtype: int64" }, { "code": null, "e": 5743, "s": 5608, "text": "Pandas supports many popular file formats including CSV, XML, HTML, Excel, SQL, JSON many more. Most commonly CSV file format is used." }, { "code": null, "e": 5773, "s": 5743, "text": "To read a csv file, just run:" }, { "code": null, "e": 5816, "s": 5773, "text": ">>> df = pd.read_csv('GDP.csv', sep = ',')" }, { "code": null, "e": 5895, "s": 5816, "text": "Named argument sep points to a separator character in CSV file called GDP.csv." }, { "code": null, "e": 6088, "s": 5895, "text": "In order to group data in pandas we can use .groupby method. To demonstrate the use of aggregates and grouping in pandas I have used the Titanic dataset, you can find the same from below link:" }, { "code": null, "e": 6121, "s": 6088, "text": "https://yadi.sk/d/TfhJdE2k3EyALt" }, { "code": null, "e": 6793, "s": 6121, "text": ">>> titanic_df = pd.read_csv('titanic.csv')\n>>> print(titanic_df.head())\nPassengerID Name PClass \nAge \\\n0 1 Allen, Miss Elisabeth Walton 1st \n29.00\n1 2 Allison, Miss Helen Loraine 1st \n2.00\n2 3 Allison, Mr Hudson Joshua Creighton 1st \n30.00\n3 4 Allison, Mrs Hudson JC (Bessie Waldo Daniels) 1st \n25.00\n4 5 Allison, Master Hudson Trevor 1st 0.92\n\n Sex Survived SexCode\n0 female 1 1\n1 female 0 1\n2 male 0 0\n3 female 0 1\n4 male 1 0\n>>>" }, { "code": null, "e": 6897, "s": 6793, "text": "Let’s calculate how many passengers (women and men) survived and how many did not, we will use .groupby" }, { "code": null, "e": 7136, "s": 6897, "text": ">>> print(titanic_df.groupby(['Sex', 'Survived'])['PassengerID'].count())\nSex Survived\nfemale 0 154\n 1 308\nmale 0 709\n 1 142\nName: PassengerID, dtype: int64" }, { "code": null, "e": 7169, "s": 7136, "text": "Above data based on cabin class:" }, { "code": null, "e": 7498, "s": 7169, "text": ">>> print(titanic_df.groupby(['PClass', 'Survived'])['PassengerID'].count())\nPClass Survived\n* 0 1\n1st 0 129\n 1 193\n2nd 0 160\n 1 119\n3rd 0 573\n 1 138\nName: PassengerID, dtype: int64" }, { "code": null, "e": 7652, "s": 7498, "text": "Pandas was created to analyse time series data. In order to illustrate, I have used the amazon 5 years stock prices. You can download it from below link," }, { "code": null, "e": 7777, "s": 7652, "text": "https://finance.yahoo.com/quote/AMZN/history?period1=1397413800&period2=1555180200&interval=1mo&filter=history&frequency=1mo" }, { "code": null, "e": 8295, "s": 7777, "text": ">>> import pandas as pd\n>>> amzn_df = pd.read_csv('AMZN.csv', index_col='Date', parse_dates=True)\n>>> amzn_df = amzn_df.sort_index()\n>>> print(amzn_df.info())\n<class 'pandas.core.frame.DataFrame'>\nDatetimeIndex: 62 entries, 2014-04-01 to 2019-04-12\nData columns (total 6 columns):\nOpen 62 non-null object\nHigh 62 non-null object\nLow 62 non-null object\nClose 62 non-null object\nAdj Close 62 non-null object\nVolume 62 non-null object\ndtypes: object(6)\nmemory usage: 1.9+ KB\nNone" }, { "code": null, "e": 8381, "s": 8295, "text": "Above we have created a DataFRame with DatetimeIndex by Date column and then sort it." }, { "code": null, "e": 8412, "s": 8381, "text": "And the mean closing price is," }, { "code": null, "e": 8466, "s": 8412, "text": ">>> amzn_df.loc['2015-04', 'Close'].mean()\n421.779999" }, { "code": null, "e": 8633, "s": 8466, "text": "We can use matplotlib library to visualize pandas. Let’s take our amazon stock historical dataset and look into its price movement of specific time period over graph." }, { "code": null, "e": 8921, "s": 8633, "text": ">>> import matplotlib.pyplot as plt\n>>> df = pd.read_csv('AMZN.csv', index_col = 'Date' , parse_dates = True)\n>>> new_df = df.loc['2014-06':'2018-08', ['Close']]\n>>> new_df=new_df.astype(float)\n>>> new_df.plot()\n<matplotlib.axes._subplots.AxesSubplot object at 0x0B9B8930>\n>>> plt.show()" } ]
How to import data from .CSV file into MySQL table using Node.js ? - GeeksforGeeks
19 Jan, 2022 What is .CSV file?The .CSV (Comma Separated Values) files are plain text files that contains a list of data separated by comma(,). It is a format best used for tabular data, row, and columns, exactly like a spreadsheet, just the difference is that the file is in the form of plain text. The idea of a CSV file is to perform export and import complex data from one application to another. Note: Here, we are using sample.csv to demonstrate our program and procedure. In sample.csv we have stored the user’s Name, Age, Email, and City. Data in sample.csv Import CSV into MySQL using Node.js: Create a node.js project using “npm init” and save your .csv file in the same directory. Install two packages “mysql” and “csvtojson” using the following command:npm i mysql csvtojsonmysql driver: This is a node.js driver for mysql. It is written in JavaScript, that does not require compiling. We are using it to establish connection with our MYSQL database and perform queries.csvtojson: Its a csv parser to convert csv to json or column arrays.Now just create a file like index.js and write down the following code: Create a node.js project using “npm init” and save your .csv file in the same directory. Install two packages “mysql” and “csvtojson” using the following command:npm i mysql csvtojsonmysql driver: This is a node.js driver for mysql. It is written in JavaScript, that does not require compiling. We are using it to establish connection with our MYSQL database and perform queries.csvtojson: Its a csv parser to convert csv to json or column arrays. npm i mysql csvtojson mysql driver: This is a node.js driver for mysql. It is written in JavaScript, that does not require compiling. We are using it to establish connection with our MYSQL database and perform queries.csvtojson: Its a csv parser to convert csv to json or column arrays. Now just create a file like index.js and write down the following code: // Importing mysql and csvtojson packages// Requiring moduleconst csvtojson = require('csvtojson');const mysql = require("mysql"); // Database credentialsconst hostname = "localhost", username = "root", password = "root", databsename = "csvtomysql" // Establish connection to the databaselet con = mysql.createConnection({ host: hostname, user: username, password: password, database: databsename,}); con.connect((err) => { if (err) return console.error( 'error: ' + err.message); con.query("DROP TABLE sample", (err, drop) => { // Query to create table "sample" var createStatament = "CREATE TABLE sample(Name char(50), " + "Email char(50), Age int, city char(30))" // Creating table "sample" con.query(createStatament, (err, drop) => { if (err) console.log("ERROR: ", err); }); });}); // CSV file nameconst fileName = "sample.csv"; csvtojson().fromFile(fileName).then(source => { // Fetching the data from each row // and inserting to the table "sample" for (var i = 0; i < source.length; i++) { var Name = source[i]["Name"], Email = source[i]["Email"], Age = source[i]["Age"], City = source[i]["City"] var insertStatement = `INSERT INTO sample values(?, ?, ?, ?)`; var items = [Name, Email, Age, City]; // Inserting data of current row // into database con.query(insertStatement, items, (err, results, fields) => { if (err) { console.log( "Unable to insert item at row ", i + 1); return console.log(err); } }); } console.log("All items stored into database successfully");}); Run index.js file using the following command: node index.js Output of the program in console Sample table in MYSQL database Explanation of code: At the first two lines of code we Import mysql and csvtojson.const csvtojson = require('csvtojson'); const mysql = require("mysql") const csvtojson = require('csvtojson'); const mysql = require("mysql") Line 10 – 23 : We created a connection to our database.hostname = "localhost", username = "root", // Username of Mysql local server password = "root", // Password of Mysql local server databsename = "csvtomysql" // Database we are connecting to hostname = "localhost", username = "root", // Username of Mysql local server password = "root", // Password of Mysql local server databsename = "csvtomysql" // Database we are connecting to Line 23 – 38: We have connected to our database “csvtomysql” and created table named “sample” with desired fields according to our sample.csv file. Line 42 – 64 : We fetched sample.csv located in current directory and converted all the data to JSON.At line 43 all data in sample.csv is converted to JSON and stored in variable “source”Then we loop through each each row and extracted Name, Email, Age and City value from that row. At line 53, we created a array of values in Name, Email, Age and City i.e. the column data of ith row.Then we inserted that data into table using query “INSERT INTO sample values(Name, Email, Age, City)”At line 62 we are showing the inserted data to console. At line 43 all data in sample.csv is converted to JSON and stored in variable “source” Then we loop through each each row and extracted Name, Email, Age and City value from that row. At line 53, we created a array of values in Name, Email, Age and City i.e. the column data of ith row.Then we inserted that data into table using query “INSERT INTO sample values(Name, Email, Age, City)”At line 62 we are showing the inserted data to console. At line 53, we created a array of values in Name, Email, Age and City i.e. the column data of ith row. Then we inserted that data into table using query “INSERT INTO sample values(Name, Email, Age, City)” At line 62 we are showing the inserted data to console. So, this way we can import any data from a .csv file to our MYSQL database. Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property Mongoose find() Function Top 10 Front End Developer Skills That You Need in 2022 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24556, "s": 24528, "text": "\n19 Jan, 2022" }, { "code": null, "e": 24944, "s": 24556, "text": "What is .CSV file?The .CSV (Comma Separated Values) files are plain text files that contains a list of data separated by comma(,). It is a format best used for tabular data, row, and columns, exactly like a spreadsheet, just the difference is that the file is in the form of plain text. The idea of a CSV file is to perform export and import complex data from one application to another." }, { "code": null, "e": 25090, "s": 24944, "text": "Note: Here, we are using sample.csv to demonstrate our program and procedure. In sample.csv we have stored the user’s Name, Age, Email, and City." }, { "code": null, "e": 25109, "s": 25090, "text": "Data in sample.csv" }, { "code": null, "e": 25146, "s": 25109, "text": "Import CSV into MySQL using Node.js:" }, { "code": null, "e": 25665, "s": 25146, "text": "Create a node.js project using “npm init” and save your .csv file in the same directory. Install two packages “mysql” and “csvtojson” using the following command:npm i mysql csvtojsonmysql driver: This is a node.js driver for mysql. It is written in JavaScript, that does not require compiling. We are using it to establish connection with our MYSQL database and perform queries.csvtojson: Its a csv parser to convert csv to json or column arrays.Now just create a file like index.js and write down the following code:" }, { "code": null, "e": 25755, "s": 25665, "text": "Create a node.js project using “npm init” and save your .csv file in the same directory. " }, { "code": null, "e": 26114, "s": 25755, "text": "Install two packages “mysql” and “csvtojson” using the following command:npm i mysql csvtojsonmysql driver: This is a node.js driver for mysql. It is written in JavaScript, that does not require compiling. We are using it to establish connection with our MYSQL database and perform queries.csvtojson: Its a csv parser to convert csv to json or column arrays." }, { "code": null, "e": 26136, "s": 26114, "text": "npm i mysql csvtojson" }, { "code": null, "e": 26401, "s": 26136, "text": "mysql driver: This is a node.js driver for mysql. It is written in JavaScript, that does not require compiling. We are using it to establish connection with our MYSQL database and perform queries.csvtojson: Its a csv parser to convert csv to json or column arrays." }, { "code": null, "e": 26473, "s": 26401, "text": "Now just create a file like index.js and write down the following code:" }, { "code": "// Importing mysql and csvtojson packages// Requiring moduleconst csvtojson = require('csvtojson');const mysql = require(\"mysql\"); // Database credentialsconst hostname = \"localhost\", username = \"root\", password = \"root\", databsename = \"csvtomysql\" // Establish connection to the databaselet con = mysql.createConnection({ host: hostname, user: username, password: password, database: databsename,}); con.connect((err) => { if (err) return console.error( 'error: ' + err.message); con.query(\"DROP TABLE sample\", (err, drop) => { // Query to create table \"sample\" var createStatament = \"CREATE TABLE sample(Name char(50), \" + \"Email char(50), Age int, city char(30))\" // Creating table \"sample\" con.query(createStatament, (err, drop) => { if (err) console.log(\"ERROR: \", err); }); });}); // CSV file nameconst fileName = \"sample.csv\"; csvtojson().fromFile(fileName).then(source => { // Fetching the data from each row // and inserting to the table \"sample\" for (var i = 0; i < source.length; i++) { var Name = source[i][\"Name\"], Email = source[i][\"Email\"], Age = source[i][\"Age\"], City = source[i][\"City\"] var insertStatement = `INSERT INTO sample values(?, ?, ?, ?)`; var items = [Name, Email, Age, City]; // Inserting data of current row // into database con.query(insertStatement, items, (err, results, fields) => { if (err) { console.log( \"Unable to insert item at row \", i + 1); return console.log(err); } }); } console.log(\"All items stored into database successfully\");});", "e": 28269, "s": 26473, "text": null }, { "code": null, "e": 28316, "s": 28269, "text": "Run index.js file using the following command:" }, { "code": null, "e": 28330, "s": 28316, "text": "node index.js" }, { "code": null, "e": 28363, "s": 28330, "text": "Output of the program in console" }, { "code": null, "e": 28394, "s": 28363, "text": "Sample table in MYSQL database" }, { "code": null, "e": 28415, "s": 28394, "text": "Explanation of code:" }, { "code": null, "e": 28548, "s": 28415, "text": "At the first two lines of code we Import mysql and csvtojson.const csvtojson = require('csvtojson');\nconst mysql = require(\"mysql\")" }, { "code": null, "e": 28619, "s": 28548, "text": "const csvtojson = require('csvtojson');\nconst mysql = require(\"mysql\")" }, { "code": null, "e": 28882, "s": 28619, "text": "Line 10 – 23 : We created a connection to our database.hostname = \"localhost\", \nusername = \"root\", // Username of Mysql local server \npassword = \"root\", // Password of Mysql local server\ndatabsename = \"csvtomysql\" // Database we are connecting to" }, { "code": null, "e": 29090, "s": 28882, "text": "hostname = \"localhost\", \nusername = \"root\", // Username of Mysql local server \npassword = \"root\", // Password of Mysql local server\ndatabsename = \"csvtomysql\" // Database we are connecting to" }, { "code": null, "e": 29238, "s": 29090, "text": "Line 23 – 38: We have connected to our database “csvtomysql” and created table named “sample” with desired fields according to our sample.csv file." }, { "code": null, "e": 29782, "s": 29238, "text": "Line 42 – 64 : We fetched sample.csv located in current directory and converted all the data to JSON.At line 43 all data in sample.csv is converted to JSON and stored in variable “source”Then we loop through each each row and extracted Name, Email, Age and City value from that row. At line 53, we created a array of values in Name, Email, Age and City i.e. the column data of ith row.Then we inserted that data into table using query “INSERT INTO sample values(Name, Email, Age, City)”At line 62 we are showing the inserted data to console. " }, { "code": null, "e": 29869, "s": 29782, "text": "At line 43 all data in sample.csv is converted to JSON and stored in variable “source”" }, { "code": null, "e": 30226, "s": 29869, "text": "Then we loop through each each row and extracted Name, Email, Age and City value from that row. At line 53, we created a array of values in Name, Email, Age and City i.e. the column data of ith row.Then we inserted that data into table using query “INSERT INTO sample values(Name, Email, Age, City)”At line 62 we are showing the inserted data to console. " }, { "code": null, "e": 30329, "s": 30226, "text": "At line 53, we created a array of values in Name, Email, Age and City i.e. the column data of ith row." }, { "code": null, "e": 30432, "s": 30329, "text": "Then we inserted that data into table using query “INSERT INTO sample values(Name, Email, Age, City)”" }, { "code": null, "e": 30489, "s": 30432, "text": "At line 62 we are showing the inserted data to console. " }, { "code": null, "e": 30565, "s": 30489, "text": "So, this way we can import any data from a .csv file to our MYSQL database." }, { "code": null, "e": 30578, "s": 30565, "text": "Node.js-Misc" }, { "code": null, "e": 30586, "s": 30578, "text": "Node.js" }, { "code": null, "e": 30603, "s": 30586, "text": "Web Technologies" }, { "code": null, "e": 30701, "s": 30603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30710, "s": 30701, "text": "Comments" }, { "code": null, "e": 30723, "s": 30710, "text": "Old Comments" }, { "code": null, "e": 30780, "s": 30723, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 30819, "s": 30780, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 30846, "s": 30819, "text": "Mongoose Populate() Method" }, { "code": null, "e": 30877, "s": 30846, "text": "Express.js req.params Property" }, { "code": null, "e": 30902, "s": 30877, "text": "Mongoose find() Function" }, { "code": null, "e": 30958, "s": 30902, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31020, "s": 30958, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31063, "s": 31020, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31113, "s": 31063, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Introduction to Explainable AI(XAI) using LIME - GeeksforGeeks
25 Aug, 2021 Motivating Explainable AI The vast field of Artificial Intelligence(AI) has experienced enormous growth in recent years. With newer and more complex models coming each year, AI models have started to surpass human intellect at a pace that no one could have predicted. But as we get more accurate and precise results, it’s becoming harder to explain the reasoning behind the complex mathematical decisions these models take. This mathematical abstraction also doesn’t help the users maintain their trust in a particular model’s decisions. e.g., Say a Deep Learning model takes in an image and predicts with 70% accuracy that a patient has lung cancer. Though the model might have given the correct diagnosis, a doctor can’t really advise a patient confidently as he/she doesn’t know the reasoning behind the said model’s diagnosis. Here’s where Explainable AI(or more popularly known as XAI) comes in! Explainable AI collectively refers to techniques or methods, which help explain a given AI model’s decision-making process. This newly found branch of AI has shown enormous potential, with newer and more sophisticated techniques coming each year. Some of the most famous XAI techniques include SHAP (Shapley Additive exPlanations), DeepSHAP, DeepLIFT, CXplain, and LIME. This article covers LIME in detail. Introducing LIME(or Local Interpretable Model-agnostic Explanations) The beauty of LIME its accessibility and simplicity. The core idea behind LIME though exhaustive is really intuitive and simple! Let’s dive in and see what the name itself represents: Model agnosticism refers to the property of LIME using which it can give explanations for any given supervised learning model by treating as a ‘black-box’ separately. This means that LIME can handle almost any model that exists out there in the wild! Local explanations mean that LIME gives explanations that are locally faithful within the surroundings or vicinity of the observation/sample being explained. Though LIME limits itself to supervised Machine Learning and Deep Learning models in its current state, it is one of the most popular and used XAI methods out there. With a rich open-source API, available in R and Python, LIME boasts a huge user base, with almost 8k stars and 2k forks on its Github repository. How LIME works? Broadly speaking, when given a prediction model and a test sample, LIME does the following steps: Sampling and obtaining a surrogate dataset: LIME provides locally faithful explanations around the vicinity of the instance being explained. By default, it produces 5000 samples(see the num_samples variable) of the feature vector following the normal distribution. Then it obtains the target variable for these 5000 samples using the prediction model, whose decisions it’s trying to explain. Feature Selection from the surrogate dataset: After obtaining the surrogate dataset, it weighs each row according to how close they are from the original sample/observation. Then it uses a feature selection technique like Lasso to obtain the top important features. LIME also employs a Ridge Regression model on the samples using only the obtained features. The outputted prediction should theoretically be similar in magnitude to the one outputted by the original prediction model. This is done to stress the relevance and importance of these obtained features. We won’t really dive into the technical and mathematical details behind the internals of LIME in this article. Still, you can go through the base research paper if you’re interested in it. Now, onto the more interesting part, the code! Installing LIME Coming to the installation part, we can use either pip or conda to install LIME in Python. pip install lime or conda install -c conda-forge lime Before going ahead, here are some key pointers that would help gain a much better understanding of the whole workflow surrounding LIME. LIME in its current state is only able to give explanations for the following type of datasets: Tabular datasets (lime.lime_tabular.LimeTabularExplainer): eg: Regression, classification datasetsImage related datasets (lime.lime_image.LimeImageExplainer)Text related datasets (lime.lime_text.LimeTextExplainer) Tabular datasets (lime.lime_tabular.LimeTabularExplainer): eg: Regression, classification datasets Image related datasets (lime.lime_image.LimeImageExplainer) Text related datasets (lime.lime_text.LimeTextExplainer) Since this is an introductory article, we’ll keep things simple and go ahead with a tabular dataset. More specifically, we’ll be using the Boston House Pricing dataset for our analysis. We’ll be using the Scikit-Learn utility for loading the dataset. As LIME is model agnostic in nature, it can handle almost any model thrown at it. To stress this fact, we’ll be using an Extra-trees regressor through the Scitkit-learn utility as our prediction model whose decisions we’re trying to investigate. As explained above, we’ll be using a tabular dataset for our analysis. To tackle such datasets, LIME’s API offers the LimeTabularExplainer. Syntax: lime.lime_tabular.LimeTabularExplainer(training_data, mode, feature_names, verbose) Parameters: training_data – 2d array consisting of the training dataset mode – Depends on the problem; “classification” or “regression” feature_names – list of titles corresponding to the columns in the training dataset. If not mentioned, it uses the column indices. verbose – if true, print local prediction values from the regression model trained on the samples using only the obtained features Once instantiated, we’ll use a method from the defined explainer object to explain a given test sample. Syntax: explain_instance(data_row, predict_fn, num_features=10, num_samples=5000) Parameters: data_row – 1d array containing values corresponding to the test sample being explained predict_fn – Prediction function used by the prediction model num_features – maximum number of features present in explanation num_samples – size of the neighborhood to learn the linear model For the sake of brevity and conciseness, only some of the arguments have been mentioned in the above two syntaxes. The rest of the arguments, most of which default to some cleverly optimized values, can be checked out by the interested reader at the official LIME documentation. Workflow Data preprocessingTraining an Extra-trees regressor on the datasetObtaining explanations for a given test sample Data preprocessing Training an Extra-trees regressor on the dataset Obtaining explanations for a given test sample Analysis Python # Importing the necessary librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Loading the dataset using sklearnfrom sklearn.datasets import load_bostondata = load_boston() # Displaying relevant information about the dataprint(data['DESCR'][200:1420]) Output: Jupyter notebook output of above code Python # Separating data into feature variable X and target variable y respectivelyfrom sklearn.model_selection import train_test_splitX = data['data']y = data['target'] # Extracting the names of the features from datafeatures = data['feature_names'] # Splitting X & y into training and testing setX_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.90, random_state=50) # Creating a dataframe of the data, for a visual checkdf = pd.concat([pd.DataFrame(X), pd.DataFrame(y)], axis=1)df.columns = np.concatenate((features, np.array(['label'])))print("Shape of data =", df.shape) # Printing the top 5 rows of the dataframedf.head() Output: Jupyter notebook output of above code Python # Instantiating the prediction model - an extra-trees regressorfrom sklearn.ensemble import ExtraTreesRegressorreg = ExtraTreesRegressor(random_state=50) # Fitting the predictino model onto the training setreg.fit(X_train, y_train) # Checking the model's performance on the test setprint('R2 score for the model on test set =', reg.score(X_test, y_test)) Output: Jupyter notebook output of above code Python # Importing the module for LimeTabularExplainerimport lime.lime_tabular # Instantiating the explainer object by passing in the training set, and the extracted featuresexplainer_lime = lime.lime_tabular.LimeTabularExplainer(X_train, feature_names=features, verbose=True, mode='regression') Suppose we want to explore the prediction model’s reasoning behind the prediction it gave for the i’th test vector. Moreover, say we want to visualize the top k features which led to this reasoning. We’re basically asking LIME to explain the decisions behind the predictions for the 10th test vector by displaying the top 5 features which contributed towards the said model’s prediction. Python # Index corresponding to the test vectori = 10 # Number denoting the top featuresk = 5 # Calling the explain_instance method by passing in the:# 1) ith test vector# 2) prediction function used by our prediction model('reg' in this case)# 3) the top features which we want to see, denoted by kexp_lime = explainer_lime.explain_instance( X_test[i], reg.predict, num_features=k) # Finally visualizing the explanationsexp_lime.show_in_notebook() Output: Jupyter notebook output of above code Interpreting the output: There’s plenty of information that LIME outputs! Let’s go step by step and interpret what it’s trying to convey First off, we see three values just above the visualizations:Right: This denotes the prediction given by our prediction model(an extra-trees regressor in this case) for the given test vector.Prediction_local: This denotes the value outputted by a linear model trained on the perturbed samples(obtained by sampling around the test vector following a normal distribution) and using only the top k features outputted by LIME.Intercept: The intercept is the constant part of the prediction given by the above linear model’s prediction for the given test vector. Right: This denotes the prediction given by our prediction model(an extra-trees regressor in this case) for the given test vector.Prediction_local: This denotes the value outputted by a linear model trained on the perturbed samples(obtained by sampling around the test vector following a normal distribution) and using only the top k features outputted by LIME.Intercept: The intercept is the constant part of the prediction given by the above linear model’s prediction for the given test vector. Right: This denotes the prediction given by our prediction model(an extra-trees regressor in this case) for the given test vector. Prediction_local: This denotes the value outputted by a linear model trained on the perturbed samples(obtained by sampling around the test vector following a normal distribution) and using only the top k features outputted by LIME. Intercept: The intercept is the constant part of the prediction given by the above linear model’s prediction for the given test vector. Coming to the visualizations, we can see the colors blue and orange, depicting negative and positive associations, respectively.To interpret the above results, we can conclude that the relatively lower price value(depicted by a bar on the left) of the house depicted by the given vector can be attributed to the following socio-economic reasons:the high value of LSTAT indicating the lower status of a society in terms of education and unemployabilitythe high value of PTRATIO indicating the high value of the number of students per teacherthe high value of DIS indicating the high value of the distance from employment centers. the low value of RM indicating the less amount of room per dwellingWe can also see that the low value of NOX indicates that the low amount of nitric oxide concentration in the air has increased the house’s value to a small extent. To interpret the above results, we can conclude that the relatively lower price value(depicted by a bar on the left) of the house depicted by the given vector can be attributed to the following socio-economic reasons:the high value of LSTAT indicating the lower status of a society in terms of education and unemployabilitythe high value of PTRATIO indicating the high value of the number of students per teacherthe high value of DIS indicating the high value of the distance from employment centers. the low value of RM indicating the less amount of room per dwelling the high value of LSTAT indicating the lower status of a society in terms of education and unemployability the high value of PTRATIO indicating the high value of the number of students per teacher the high value of DIS indicating the high value of the distance from employment centers. the low value of RM indicating the less amount of room per dwelling We can also see that the low value of NOX indicates that the low amount of nitric oxide concentration in the air has increased the house’s value to a small extent. We can see how easy it has become to correlate the decisions taken by a relatively complex prediction model(an extra-trees regressor) in an interpreatable and meaningful way. Let’s try this exercise on one more test vector! Here again we’re asking LIME to explain the decisions behind the predictions for the 47th test vector by displaying the top 5 features which contributed towards the said model’s prediction Python # Index corresponding to the test vectori = 47 # Number denoting the top featuresk = 5 # Calling the explain_instance method by passing in the:# 1) ith test vector# 2) prediction function used by our prediction model('reg' in this case)# 3) the top features which we want to see, denoted by kexp_lime = explainer_lime.explain_instance( X_test[i], reg.predict, num_features=k) # Finally visualizing the explanationsexp_lime.show_in_notebook() Output: Jupyter notebook output of above code Interpreting the output: From the visualizations, we can conclude that the relatively higher price value(depicted by a bar on the left) of the house depicted by the given vector can be attributed to the following socio-economic reasons:The low value of LSTAT indicating the grand status of a society in terms of education and employabilityThe high value of RM indicating the high numbers of room per dwellingThe low value of TAX indicating the low tax-rate of the propertyThe low value of AGE which depicts the newness of the establishment The low value of LSTAT indicating the grand status of a society in terms of education and employability The high value of RM indicating the high numbers of room per dwelling The low value of TAX indicating the low tax-rate of the property The low value of AGE which depicts the newness of the establishment We can also see that the average value of INDUS, which indicates that the low number of non-retails near the society, has decreased the value of the house to a small extent. Summary: This article is a brief introduction to Explainable AI(XAI) using LIME in Python. It’s evident how beneficial LIME could give us a much profound intuition behind a given black-box model’s decision-making process while providing solid insights on the inherent dataset. This makes LIME a useful resource for both AI researchers and data scientists alike! References: https://lime-ml.readthedocs.io/en/latest/https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesRegressor.htmlhttps://scikit-learn.org/0.16/modules/generated/sklearn.datasets.load_boston.html#sklearn.datasets.load_bostonMarco Tulio Ribeiro, Sameer Singh, and Carlos Guestrin. ”why should I trust you?”: Explaining the predictions of any classifier. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, page 1135–1144. Association for Computing Machinery, 2016. https://lime-ml.readthedocs.io/en/latest/ https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesRegressor.html https://scikit-learn.org/0.16/modules/generated/sklearn.datasets.load_boston.html#sklearn.datasets.load_boston Marco Tulio Ribeiro, Sameer Singh, and Carlos Guestrin. ”why should I trust you?”: Explaining the predictions of any classifier. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, page 1135–1144. Association for Computing Machinery, 2016. tovandita12032018 abhishek0719kadiyan Artificial Intelligence data-science Technical Scripter 2020 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Difference between Informed and Uninformed Search in AI Normalization vs Standardization Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24370, "s": 24342, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24396, "s": 24370, "text": "Motivating Explainable AI" }, { "code": null, "e": 24909, "s": 24396, "text": "The vast field of Artificial Intelligence(AI) has experienced enormous growth in recent years. With newer and more complex models coming each year, AI models have started to surpass human intellect at a pace that no one could have predicted. But as we get more accurate and precise results, it’s becoming harder to explain the reasoning behind the complex mathematical decisions these models take. This mathematical abstraction also doesn’t help the users maintain their trust in a particular model’s decisions. " }, { "code": null, "e": 25202, "s": 24909, "text": "e.g., Say a Deep Learning model takes in an image and predicts with 70% accuracy that a patient has lung cancer. Though the model might have given the correct diagnosis, a doctor can’t really advise a patient confidently as he/she doesn’t know the reasoning behind the said model’s diagnosis." }, { "code": null, "e": 25680, "s": 25202, "text": "Here’s where Explainable AI(or more popularly known as XAI) comes in! Explainable AI collectively refers to techniques or methods, which help explain a given AI model’s decision-making process. This newly found branch of AI has shown enormous potential, with newer and more sophisticated techniques coming each year. Some of the most famous XAI techniques include SHAP (Shapley Additive exPlanations), DeepSHAP, DeepLIFT, CXplain, and LIME. This article covers LIME in detail." }, { "code": null, "e": 25750, "s": 25680, "text": "Introducing LIME(or Local Interpretable Model-agnostic Explanations)" }, { "code": null, "e": 25934, "s": 25750, "text": "The beauty of LIME its accessibility and simplicity. The core idea behind LIME though exhaustive is really intuitive and simple! Let’s dive in and see what the name itself represents:" }, { "code": null, "e": 26185, "s": 25934, "text": "Model agnosticism refers to the property of LIME using which it can give explanations for any given supervised learning model by treating as a ‘black-box’ separately. This means that LIME can handle almost any model that exists out there in the wild!" }, { "code": null, "e": 26343, "s": 26185, "text": "Local explanations mean that LIME gives explanations that are locally faithful within the surroundings or vicinity of the observation/sample being explained." }, { "code": null, "e": 26655, "s": 26343, "text": "Though LIME limits itself to supervised Machine Learning and Deep Learning models in its current state, it is one of the most popular and used XAI methods out there. With a rich open-source API, available in R and Python, LIME boasts a huge user base, with almost 8k stars and 2k forks on its Github repository." }, { "code": null, "e": 26671, "s": 26655, "text": "How LIME works?" }, { "code": null, "e": 26769, "s": 26671, "text": "Broadly speaking, when given a prediction model and a test sample, LIME does the following steps:" }, { "code": null, "e": 27161, "s": 26769, "text": "Sampling and obtaining a surrogate dataset: LIME provides locally faithful explanations around the vicinity of the instance being explained. By default, it produces 5000 samples(see the num_samples variable) of the feature vector following the normal distribution. Then it obtains the target variable for these 5000 samples using the prediction model, whose decisions it’s trying to explain." }, { "code": null, "e": 27427, "s": 27161, "text": "Feature Selection from the surrogate dataset: After obtaining the surrogate dataset, it weighs each row according to how close they are from the original sample/observation. Then it uses a feature selection technique like Lasso to obtain the top important features." }, { "code": null, "e": 27724, "s": 27427, "text": "LIME also employs a Ridge Regression model on the samples using only the obtained features. The outputted prediction should theoretically be similar in magnitude to the one outputted by the original prediction model. This is done to stress the relevance and importance of these obtained features." }, { "code": null, "e": 27960, "s": 27724, "text": "We won’t really dive into the technical and mathematical details behind the internals of LIME in this article. Still, you can go through the base research paper if you’re interested in it. Now, onto the more interesting part, the code!" }, { "code": null, "e": 27976, "s": 27960, "text": "Installing LIME" }, { "code": null, "e": 28067, "s": 27976, "text": "Coming to the installation part, we can use either pip or conda to install LIME in Python." }, { "code": null, "e": 28084, "s": 28067, "text": "pip install lime" }, { "code": null, "e": 28087, "s": 28084, "text": "or" }, { "code": null, "e": 28121, "s": 28087, "text": "conda install -c conda-forge lime" }, { "code": null, "e": 28257, "s": 28121, "text": "Before going ahead, here are some key pointers that would help gain a much better understanding of the whole workflow surrounding LIME." }, { "code": null, "e": 28353, "s": 28257, "text": "LIME in its current state is only able to give explanations for the following type of datasets:" }, { "code": null, "e": 28567, "s": 28353, "text": "Tabular datasets (lime.lime_tabular.LimeTabularExplainer): eg: Regression, classification datasetsImage related datasets (lime.lime_image.LimeImageExplainer)Text related datasets (lime.lime_text.LimeTextExplainer)" }, { "code": null, "e": 28666, "s": 28567, "text": "Tabular datasets (lime.lime_tabular.LimeTabularExplainer): eg: Regression, classification datasets" }, { "code": null, "e": 28726, "s": 28666, "text": "Image related datasets (lime.lime_image.LimeImageExplainer)" }, { "code": null, "e": 28783, "s": 28726, "text": "Text related datasets (lime.lime_text.LimeTextExplainer)" }, { "code": null, "e": 29034, "s": 28783, "text": "Since this is an introductory article, we’ll keep things simple and go ahead with a tabular dataset. More specifically, we’ll be using the Boston House Pricing dataset for our analysis. We’ll be using the Scikit-Learn utility for loading the dataset." }, { "code": null, "e": 29280, "s": 29034, "text": "As LIME is model agnostic in nature, it can handle almost any model thrown at it. To stress this fact, we’ll be using an Extra-trees regressor through the Scitkit-learn utility as our prediction model whose decisions we’re trying to investigate." }, { "code": null, "e": 29420, "s": 29280, "text": "As explained above, we’ll be using a tabular dataset for our analysis. To tackle such datasets, LIME’s API offers the LimeTabularExplainer." }, { "code": null, "e": 29513, "s": 29420, "text": "Syntax: lime.lime_tabular.LimeTabularExplainer(training_data, mode, feature_names, verbose)" }, { "code": null, "e": 29525, "s": 29513, "text": "Parameters:" }, { "code": null, "e": 29585, "s": 29525, "text": "training_data – 2d array consisting of the training dataset" }, { "code": null, "e": 29649, "s": 29585, "text": "mode – Depends on the problem; “classification” or “regression”" }, { "code": null, "e": 29780, "s": 29649, "text": "feature_names – list of titles corresponding to the columns in the training dataset. If not mentioned, it uses the column indices." }, { "code": null, "e": 29911, "s": 29780, "text": "verbose – if true, print local prediction values from the regression model trained on the samples using only the obtained features" }, { "code": null, "e": 30015, "s": 29911, "text": "Once instantiated, we’ll use a method from the defined explainer object to explain a given test sample." }, { "code": null, "e": 30097, "s": 30015, "text": "Syntax: explain_instance(data_row, predict_fn, num_features=10, num_samples=5000)" }, { "code": null, "e": 30109, "s": 30097, "text": "Parameters:" }, { "code": null, "e": 30196, "s": 30109, "text": "data_row – 1d array containing values corresponding to the test sample being explained" }, { "code": null, "e": 30258, "s": 30196, "text": "predict_fn – Prediction function used by the prediction model" }, { "code": null, "e": 30323, "s": 30258, "text": "num_features – maximum number of features present in explanation" }, { "code": null, "e": 30388, "s": 30323, "text": "num_samples – size of the neighborhood to learn the linear model" }, { "code": null, "e": 30667, "s": 30388, "text": "For the sake of brevity and conciseness, only some of the arguments have been mentioned in the above two syntaxes. The rest of the arguments, most of which default to some cleverly optimized values, can be checked out by the interested reader at the official LIME documentation." }, { "code": null, "e": 30676, "s": 30667, "text": "Workflow" }, { "code": null, "e": 30789, "s": 30676, "text": "Data preprocessingTraining an Extra-trees regressor on the datasetObtaining explanations for a given test sample" }, { "code": null, "e": 30808, "s": 30789, "text": "Data preprocessing" }, { "code": null, "e": 30857, "s": 30808, "text": "Training an Extra-trees regressor on the dataset" }, { "code": null, "e": 30904, "s": 30857, "text": "Obtaining explanations for a given test sample" }, { "code": null, "e": 30913, "s": 30904, "text": "Analysis" }, { "code": null, "e": 30920, "s": 30913, "text": "Python" }, { "code": "# Importing the necessary librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Loading the dataset using sklearnfrom sklearn.datasets import load_bostondata = load_boston() # Displaying relevant information about the dataprint(data['DESCR'][200:1420])", "e": 31199, "s": 30920, "text": null }, { "code": null, "e": 31207, "s": 31199, "text": "Output:" }, { "code": null, "e": 31245, "s": 31207, "text": "Jupyter notebook output of above code" }, { "code": null, "e": 31252, "s": 31245, "text": "Python" }, { "code": "# Separating data into feature variable X and target variable y respectivelyfrom sklearn.model_selection import train_test_splitX = data['data']y = data['target'] # Extracting the names of the features from datafeatures = data['feature_names'] # Splitting X & y into training and testing setX_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.90, random_state=50) # Creating a dataframe of the data, for a visual checkdf = pd.concat([pd.DataFrame(X), pd.DataFrame(y)], axis=1)df.columns = np.concatenate((features, np.array(['label'])))print(\"Shape of data =\", df.shape) # Printing the top 5 rows of the dataframedf.head()", "e": 31898, "s": 31252, "text": null }, { "code": null, "e": 31906, "s": 31898, "text": "Output:" }, { "code": null, "e": 31944, "s": 31906, "text": "Jupyter notebook output of above code" }, { "code": null, "e": 31951, "s": 31944, "text": "Python" }, { "code": "# Instantiating the prediction model - an extra-trees regressorfrom sklearn.ensemble import ExtraTreesRegressorreg = ExtraTreesRegressor(random_state=50) # Fitting the predictino model onto the training setreg.fit(X_train, y_train) # Checking the model's performance on the test setprint('R2 score for the model on test set =', reg.score(X_test, y_test))", "e": 32306, "s": 31951, "text": null }, { "code": null, "e": 32314, "s": 32306, "text": "Output:" }, { "code": null, "e": 32352, "s": 32314, "text": "Jupyter notebook output of above code" }, { "code": null, "e": 32359, "s": 32352, "text": "Python" }, { "code": "# Importing the module for LimeTabularExplainerimport lime.lime_tabular # Instantiating the explainer object by passing in the training set, and the extracted featuresexplainer_lime = lime.lime_tabular.LimeTabularExplainer(X_train, feature_names=features, verbose=True, mode='regression')", "e": 32758, "s": 32359, "text": null }, { "code": null, "e": 32874, "s": 32758, "text": "Suppose we want to explore the prediction model’s reasoning behind the prediction it gave for the i’th test vector." }, { "code": null, "e": 32957, "s": 32874, "text": "Moreover, say we want to visualize the top k features which led to this reasoning." }, { "code": null, "e": 33146, "s": 32957, "text": "We’re basically asking LIME to explain the decisions behind the predictions for the 10th test vector by displaying the top 5 features which contributed towards the said model’s prediction." }, { "code": null, "e": 33153, "s": 33146, "text": "Python" }, { "code": "# Index corresponding to the test vectori = 10 # Number denoting the top featuresk = 5 # Calling the explain_instance method by passing in the:# 1) ith test vector# 2) prediction function used by our prediction model('reg' in this case)# 3) the top features which we want to see, denoted by kexp_lime = explainer_lime.explain_instance( X_test[i], reg.predict, num_features=k) # Finally visualizing the explanationsexp_lime.show_in_notebook()", "e": 33607, "s": 33153, "text": null }, { "code": null, "e": 33615, "s": 33607, "text": "Output:" }, { "code": null, "e": 33653, "s": 33615, "text": "Jupyter notebook output of above code" }, { "code": null, "e": 33678, "s": 33653, "text": "Interpreting the output:" }, { "code": null, "e": 33790, "s": 33678, "text": "There’s plenty of information that LIME outputs! Let’s go step by step and interpret what it’s trying to convey" }, { "code": null, "e": 34348, "s": 33790, "text": "First off, we see three values just above the visualizations:Right: This denotes the prediction given by our prediction model(an extra-trees regressor in this case) for the given test vector.Prediction_local: This denotes the value outputted by a linear model trained on the perturbed samples(obtained by sampling around the test vector following a normal distribution) and using only the top k features outputted by LIME.Intercept: The intercept is the constant part of the prediction given by the above linear model’s prediction for the given test vector." }, { "code": null, "e": 34845, "s": 34348, "text": "Right: This denotes the prediction given by our prediction model(an extra-trees regressor in this case) for the given test vector.Prediction_local: This denotes the value outputted by a linear model trained on the perturbed samples(obtained by sampling around the test vector following a normal distribution) and using only the top k features outputted by LIME.Intercept: The intercept is the constant part of the prediction given by the above linear model’s prediction for the given test vector." }, { "code": null, "e": 34976, "s": 34845, "text": "Right: This denotes the prediction given by our prediction model(an extra-trees regressor in this case) for the given test vector." }, { "code": null, "e": 35208, "s": 34976, "text": "Prediction_local: This denotes the value outputted by a linear model trained on the perturbed samples(obtained by sampling around the test vector following a normal distribution) and using only the top k features outputted by LIME." }, { "code": null, "e": 35344, "s": 35208, "text": "Intercept: The intercept is the constant part of the prediction given by the above linear model’s prediction for the given test vector." }, { "code": null, "e": 36204, "s": 35344, "text": "Coming to the visualizations, we can see the colors blue and orange, depicting negative and positive associations, respectively.To interpret the above results, we can conclude that the relatively lower price value(depicted by a bar on the left) of the house depicted by the given vector can be attributed to the following socio-economic reasons:the high value of LSTAT indicating the lower status of a society in terms of education and unemployabilitythe high value of PTRATIO indicating the high value of the number of students per teacherthe high value of DIS indicating the high value of the distance from employment centers. the low value of RM indicating the less amount of room per dwellingWe can also see that the low value of NOX indicates that the low amount of nitric oxide concentration in the air has increased the house’s value to a small extent." }, { "code": null, "e": 36773, "s": 36204, "text": "To interpret the above results, we can conclude that the relatively lower price value(depicted by a bar on the left) of the house depicted by the given vector can be attributed to the following socio-economic reasons:the high value of LSTAT indicating the lower status of a society in terms of education and unemployabilitythe high value of PTRATIO indicating the high value of the number of students per teacherthe high value of DIS indicating the high value of the distance from employment centers. the low value of RM indicating the less amount of room per dwelling" }, { "code": null, "e": 36880, "s": 36773, "text": "the high value of LSTAT indicating the lower status of a society in terms of education and unemployability" }, { "code": null, "e": 36970, "s": 36880, "text": "the high value of PTRATIO indicating the high value of the number of students per teacher" }, { "code": null, "e": 37060, "s": 36970, "text": "the high value of DIS indicating the high value of the distance from employment centers. " }, { "code": null, "e": 37128, "s": 37060, "text": "the low value of RM indicating the less amount of room per dwelling" }, { "code": null, "e": 37292, "s": 37128, "text": "We can also see that the low value of NOX indicates that the low amount of nitric oxide concentration in the air has increased the house’s value to a small extent." }, { "code": null, "e": 37516, "s": 37292, "text": "We can see how easy it has become to correlate the decisions taken by a relatively complex prediction model(an extra-trees regressor) in an interpreatable and meaningful way. Let’s try this exercise on one more test vector!" }, { "code": null, "e": 37705, "s": 37516, "text": "Here again we’re asking LIME to explain the decisions behind the predictions for the 47th test vector by displaying the top 5 features which contributed towards the said model’s prediction" }, { "code": null, "e": 37714, "s": 37707, "text": "Python" }, { "code": "# Index corresponding to the test vectori = 47 # Number denoting the top featuresk = 5 # Calling the explain_instance method by passing in the:# 1) ith test vector# 2) prediction function used by our prediction model('reg' in this case)# 3) the top features which we want to see, denoted by kexp_lime = explainer_lime.explain_instance( X_test[i], reg.predict, num_features=k) # Finally visualizing the explanationsexp_lime.show_in_notebook()", "e": 38168, "s": 37714, "text": null }, { "code": null, "e": 38176, "s": 38168, "text": "Output:" }, { "code": null, "e": 38214, "s": 38176, "text": "Jupyter notebook output of above code" }, { "code": null, "e": 38239, "s": 38214, "text": "Interpreting the output:" }, { "code": null, "e": 38754, "s": 38239, "text": "From the visualizations, we can conclude that the relatively higher price value(depicted by a bar on the left) of the house depicted by the given vector can be attributed to the following socio-economic reasons:The low value of LSTAT indicating the grand status of a society in terms of education and employabilityThe high value of RM indicating the high numbers of room per dwellingThe low value of TAX indicating the low tax-rate of the propertyThe low value of AGE which depicts the newness of the establishment" }, { "code": null, "e": 38858, "s": 38754, "text": "The low value of LSTAT indicating the grand status of a society in terms of education and employability" }, { "code": null, "e": 38928, "s": 38858, "text": "The high value of RM indicating the high numbers of room per dwelling" }, { "code": null, "e": 38993, "s": 38928, "text": "The low value of TAX indicating the low tax-rate of the property" }, { "code": null, "e": 39061, "s": 38993, "text": "The low value of AGE which depicts the newness of the establishment" }, { "code": null, "e": 39235, "s": 39061, "text": "We can also see that the average value of INDUS, which indicates that the low number of non-retails near the society, has decreased the value of the house to a small extent." }, { "code": null, "e": 39244, "s": 39235, "text": "Summary:" }, { "code": null, "e": 39597, "s": 39244, "text": "This article is a brief introduction to Explainable AI(XAI) using LIME in Python. It’s evident how beneficial LIME could give us a much profound intuition behind a given black-box model’s decision-making process while providing solid insights on the inherent dataset. This makes LIME a useful resource for both AI researchers and data scientists alike!" }, { "code": null, "e": 39609, "s": 39597, "text": "References:" }, { "code": null, "e": 40142, "s": 39609, "text": "https://lime-ml.readthedocs.io/en/latest/https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesRegressor.htmlhttps://scikit-learn.org/0.16/modules/generated/sklearn.datasets.load_boston.html#sklearn.datasets.load_bostonMarco Tulio Ribeiro, Sameer Singh, and Carlos Guestrin. ”why should I trust you?”: Explaining the predictions of any classifier. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, page 1135–1144. Association for Computing Machinery, 2016." }, { "code": null, "e": 40184, "s": 40142, "text": "https://lime-ml.readthedocs.io/en/latest/" }, { "code": null, "e": 40276, "s": 40184, "text": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesRegressor.html" }, { "code": null, "e": 40387, "s": 40276, "text": "https://scikit-learn.org/0.16/modules/generated/sklearn.datasets.load_boston.html#sklearn.datasets.load_boston" }, { "code": null, "e": 40678, "s": 40387, "text": "Marco Tulio Ribeiro, Sameer Singh, and Carlos Guestrin. ”why should I trust you?”: Explaining the predictions of any classifier. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, page 1135–1144. Association for Computing Machinery, 2016." }, { "code": null, "e": 40696, "s": 40678, "text": "tovandita12032018" }, { "code": null, "e": 40716, "s": 40696, "text": "abhishek0719kadiyan" }, { "code": null, "e": 40740, "s": 40716, "text": "Artificial Intelligence" }, { "code": null, "e": 40753, "s": 40740, "text": "data-science" }, { "code": null, "e": 40777, "s": 40753, "text": "Technical Scripter 2020" }, { "code": null, "e": 40794, "s": 40777, "text": "Machine Learning" }, { "code": null, "e": 40801, "s": 40794, "text": "Python" }, { "code": null, "e": 40818, "s": 40801, "text": "Machine Learning" }, { "code": null, "e": 40916, "s": 40818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40925, "s": 40916, "text": "Comments" }, { "code": null, "e": 40938, "s": 40925, "text": "Old Comments" }, { "code": null, "e": 40971, "s": 40938, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 41010, "s": 40971, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 41045, "s": 41010, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 41101, "s": 41045, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 41134, "s": 41101, "text": "Normalization vs Standardization" }, { "code": null, "e": 41162, "s": 41134, "text": "Read JSON file using Python" }, { "code": null, "e": 41212, "s": 41162, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 41234, "s": 41212, "text": "Python map() function" } ]
FloatField - Django Forms - GeeksforGeeks
13 Feb, 2020 FloatField in Django Forms is a integer field, for taking input of floating point numbers from user. The default widget for this input is NumberInput.It normalizes to: A Python float. It validates that the given value is a float. It uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace is allowed, as in Python’s float() function. FloatField has following optional arguments: max_length and min_length :- If provided, these arguments ensure that the data is at most or at least the given length. Syntax field_name = forms.FloatField(**options) Illustration of FloatField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into forms.py file of geeks app. from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.FloatField( ) Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context) Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type = "submit" value = "Submit"></form> Finally, a URL to map to this view in urls.py from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),] Let’s run the server and check what has actually happened, Run Python manage.py runserver Thus, an geeks_field FloatField is created by replacing “_” with ” “. It is a field to input floating point numbers from the user. FloatField is used for input of float numbers in the database. One can input date of Marks, percentage, etc. Till now we have discussed how to implement FloatField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} if request.method == "POST": form = GeeksForm(request.POST) if form.is_valid(): temp = form.cleaned_data.get("geeks_field") print(type(temp)) else: form = GeeksForm() context['form'] = form return render(request, "home.html", context) Let’s try something other than a number in a FloatField. So it accepts a valid float number input only otherwise validation errors will be seen. Now let’s try entering a valid floating number into the field.Float data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose. Let’s check what type of temp variable is ? Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to FloatField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 24322, "s": 24294, "text": "\n13 Feb, 2020" }, { "code": null, "e": 24718, "s": 24322, "text": "FloatField in Django Forms is a integer field, for taking input of floating point numbers from user. The default widget for this input is NumberInput.It normalizes to: A Python float. It validates that the given value is a float. It uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace is allowed, as in Python’s float() function." }, { "code": null, "e": 24763, "s": 24718, "text": "FloatField has following optional arguments:" }, { "code": null, "e": 24883, "s": 24763, "text": "max_length and min_length :- If provided, these arguments ensure that the data is at most or at least the given length." }, { "code": null, "e": 24890, "s": 24883, "text": "Syntax" }, { "code": null, "e": 24931, "s": 24890, "text": "field_name = forms.FloatField(**options)" }, { "code": null, "e": 25042, "s": 24931, "text": "Illustration of FloatField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 25129, "s": 25042, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 25180, "s": 25129, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25213, "s": 25180, "text": "How to Create an App in Django ?" }, { "code": null, "e": 25271, "s": 25213, "text": "Enter the following code into forms.py file of geeks app." }, { "code": "from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.FloatField( )", "e": 25381, "s": 25271, "text": null }, { "code": null, "e": 25417, "s": 25381, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 25655, "s": 25417, "text": null }, { "code": null, "e": 25788, "s": 25655, "text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)", "e": 26000, "s": 25788, "text": null }, { "code": null, "e": 26286, "s": 26000, "text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html." }, { "code": "<form method=\"POST\"> {% csrf_token %} {{ form.as_p }} <input type = \"submit\" value = \"Submit\"></form>", "e": 26397, "s": 26286, "text": null }, { "code": null, "e": 26443, "s": 26397, "text": "Finally, a URL to map to this view in urls.py" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]", "e": 26577, "s": 26443, "text": null }, { "code": null, "e": 26640, "s": 26577, "text": "Let’s run the server and check what has actually happened, Run" }, { "code": null, "e": 26667, "s": 26640, "text": "Python manage.py runserver" }, { "code": null, "e": 26798, "s": 26667, "text": "Thus, an geeks_field FloatField is created by replacing “_” with ” “. It is a field to input floating point numbers from the user." }, { "code": null, "e": 27140, "s": 26798, "text": "FloatField is used for input of float numbers in the database. One can input date of Marks, percentage, etc. Till now we have discussed how to implement FloatField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} if request.method == \"POST\": form = GeeksForm(request.POST) if form.is_valid(): temp = form.cleaned_data.get(\"geeks_field\") print(type(temp)) else: form = GeeksForm() context['form'] = form return render(request, \"home.html\", context)", "e": 27560, "s": 27140, "text": null }, { "code": null, "e": 27617, "s": 27560, "text": "Let’s try something other than a number in a FloatField." }, { "code": null, "e": 28054, "s": 27617, "text": "So it accepts a valid float number input only otherwise validation errors will be seen. Now let’s try entering a valid floating number into the field.Float data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose. Let’s check what type of temp variable is ?" }, { "code": null, "e": 28482, "s": 28054, "text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to FloatField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:" }, { "code": null, "e": 28494, "s": 28482, "text": "NaveenArora" }, { "code": null, "e": 28507, "s": 28494, "text": "Django-forms" }, { "code": null, "e": 28521, "s": 28507, "text": "Python Django" }, { "code": null, "e": 28528, "s": 28521, "text": "Python" }, { "code": null, "e": 28626, "s": 28528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28644, "s": 28626, "text": "Python Dictionary" }, { "code": null, "e": 28679, "s": 28644, "text": "Read a file line by line in Python" }, { "code": null, "e": 28711, "s": 28679, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28741, "s": 28711, "text": "Iterate over a list in Python" }, { "code": null, "e": 28783, "s": 28741, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28809, "s": 28783, "text": "Python String | replace()" }, { "code": null, "e": 28852, "s": 28809, "text": "Python program to convert a list to string" }, { "code": null, "e": 28889, "s": 28852, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28933, "s": 28889, "text": "Reading and Writing to text files in Python" } ]
Time Series - Exponential Smoothing
In this chapter, we will talk about the techniques involved in exponential smoothing of time series. Exponential Smoothing is a technique for smoothing univariate time-series by assigning exponentially decreasing weights to data over a time period. Mathematically, the value of variable at time ‘t+1’ given value at time t, y_(t+1|t) is defined as − yt+1|t=αyt+α⟮1−α⟯yt−1+α⟮1−α⟯2yt−2+...+y1 where,0≤α≤1 is the smoothing parameter, and y1,....,yt are previous values of network traffic at times 1, 2, 3, ... ,t. This is a simple method to model a time series with no clear trend or seasonality. But exponential smoothing can also be used for time series with trend and seasonality. Triple Exponential Smoothing (TES) or Holt's Winter method, applies exponential smoothing three times - level smoothing lt, trend smoothing bt, and seasonal smoothing St, with α, β∗ and γ as smoothing parameters with ‘m’ as the frequency of the seasonality, i.e. the number of seasons in a year. According to the nature of the seasonal component, TES has two categories − Holt-Winter's Additive Method − When the seasonality is additive in nature. Holt-Winter's Additive Method − When the seasonality is additive in nature. Holt-Winter’s Multiplicative Method − When the seasonality is multiplicative in nature. Holt-Winter’s Multiplicative Method − When the seasonality is multiplicative in nature. For non-seasonal time series, we only have trend smoothing and level smoothing, which is called Holt’s Linear Trend Method. Let’s try applying triple exponential smoothing on our data. In [316]: from statsmodels.tsa.holtwinters import ExponentialSmoothing model = ExponentialSmoothing(train.values, trend= ) model_fit = model.fit() In [322]: predictions_ = model_fit.predict(len(test)) In [325]: plt.plot(test.values) plt.plot(predictions_[1:1871]) Out[325]: [<matplotlib.lines.Line2D at 0x1eab00f1cf8>] Here, we have trained the model once with training set and then we keep on making predictions. A more realistic approach is to re-train the model after one or more time step(s). As we get the prediction for time ‘t+1’ from training data ‘til time ‘t’, the next prediction for time ‘t+2’ can be made using the training data ‘til time ‘t+1’ as the actual value at ‘t+1’ will be known then. This methodology of making predictions for one or more future steps and then re-training the model is called rolling forecast or walk forward validation. 16 Lectures 2 hours Malhar Lathkar 21 Lectures 2.5 hours Sasha Miller 19 Lectures 1 hours Sasha Miller 94 Lectures 13 hours Abhishek And Pukhraj 12 Lectures 2 hours Prof. Paul Cline, Ed.D 11 Lectures 1 hours Prof. Paul Cline, Ed.D Print Add Notes Bookmark this page
[ { "code": null, "e": 2242, "s": 2141, "text": "In this chapter, we will talk about the techniques involved in exponential smoothing of time series." }, { "code": null, "e": 2390, "s": 2242, "text": "Exponential Smoothing is a technique for smoothing univariate time-series by assigning exponentially decreasing weights to data over a time period." }, { "code": null, "e": 2491, "s": 2390, "text": "Mathematically, the value of variable at time ‘t+1’ given value at time t, y_(t+1|t) is defined as −" }, { "code": null, "e": 2532, "s": 2491, "text": "yt+1|t=αyt+α⟮1−α⟯yt−1+α⟮1−α⟯2yt−2+...+y1" }, { "code": null, "e": 2576, "s": 2532, "text": "where,0≤α≤1 is the smoothing parameter, and" }, { "code": null, "e": 2652, "s": 2576, "text": "y1,....,yt are previous values of network traffic at times 1, 2, 3, ... ,t." }, { "code": null, "e": 2822, "s": 2652, "text": "This is a simple method to model a time series with no clear trend or seasonality. But exponential smoothing can also be used for time series with trend and seasonality." }, { "code": null, "e": 3118, "s": 2822, "text": "Triple Exponential Smoothing (TES) or Holt's Winter method, applies exponential smoothing three times - level smoothing lt, trend smoothing bt, and seasonal smoothing St, with α, β∗ and γ as smoothing parameters with ‘m’ as the frequency of the seasonality, i.e. the number of seasons in a year." }, { "code": null, "e": 3194, "s": 3118, "text": "According to the nature of the seasonal component, TES has two categories −" }, { "code": null, "e": 3270, "s": 3194, "text": "Holt-Winter's Additive Method − When the seasonality is additive in nature." }, { "code": null, "e": 3346, "s": 3270, "text": "Holt-Winter's Additive Method − When the seasonality is additive in nature." }, { "code": null, "e": 3434, "s": 3346, "text": "Holt-Winter’s Multiplicative Method − When the seasonality is multiplicative in nature." }, { "code": null, "e": 3522, "s": 3434, "text": "Holt-Winter’s Multiplicative Method − When the seasonality is multiplicative in nature." }, { "code": null, "e": 3646, "s": 3522, "text": "For non-seasonal time series, we only have trend smoothing and level smoothing, which is called Holt’s Linear Trend Method." }, { "code": null, "e": 3707, "s": 3646, "text": "Let’s try applying triple exponential smoothing on our data." }, { "code": null, "e": 3717, "s": 3707, "text": "In [316]:" }, { "code": null, "e": 3856, "s": 3717, "text": "from statsmodels.tsa.holtwinters import ExponentialSmoothing\n\nmodel = ExponentialSmoothing(train.values, trend= )\nmodel_fit = model.fit()\n" }, { "code": null, "e": 3866, "s": 3856, "text": "In [322]:" }, { "code": null, "e": 3911, "s": 3866, "text": "predictions_ = model_fit.predict(len(test))\n" }, { "code": null, "e": 3921, "s": 3911, "text": "In [325]:" }, { "code": null, "e": 3975, "s": 3921, "text": "plt.plot(test.values)\nplt.plot(predictions_[1:1871])\n" }, { "code": null, "e": 3985, "s": 3975, "text": "Out[325]:" }, { "code": null, "e": 4031, "s": 3985, "text": "[<matplotlib.lines.Line2D at 0x1eab00f1cf8>]\n" }, { "code": null, "e": 4573, "s": 4031, "text": "Here, we have trained the model once with training set and then we keep on making predictions. A more realistic approach is to re-train the model after one or more time step(s). As we get the prediction for time ‘t+1’ from training data ‘til time ‘t’, the next prediction for time ‘t+2’ can be made using the training data ‘til time ‘t+1’ as the actual value at ‘t+1’ will be known then. This methodology of making predictions for one or more future steps and then re-training the model is called rolling forecast or walk forward validation." }, { "code": null, "e": 4606, "s": 4573, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4622, "s": 4606, "text": " Malhar Lathkar" }, { "code": null, "e": 4657, "s": 4622, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4671, "s": 4657, "text": " Sasha Miller" }, { "code": null, "e": 4704, "s": 4671, "text": "\n 19 Lectures \n 1 hours \n" }, { "code": null, "e": 4718, "s": 4704, "text": " Sasha Miller" }, { "code": null, "e": 4752, "s": 4718, "text": "\n 94 Lectures \n 13 hours \n" }, { "code": null, "e": 4774, "s": 4752, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4807, "s": 4774, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4831, "s": 4807, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 4864, "s": 4831, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 4888, "s": 4864, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 4895, "s": 4888, "text": " Print" }, { "code": null, "e": 4906, "s": 4895, "text": " Add Notes" } ]
Sum of the series 1, 3, 6, 10... (Triangular Numbers) in C++
In this problem, we are given a number n which is given the n of elements of the series 1, 3, 6, 10 ... (triangular number). Our task is to create a program to calculate the sum of the series. Let’s brush up about triangular numbers before calculating the sum. Triangular numbers are those numbers that can be represented in the form of a triangle. A triangle is formed in such a way that the first row has one point, second has two, and so on. Input n = 4 Output Explanation − sum = T1 + T2 + T3 + T4 = 1 + 3 + 6 + 10 = 20 A simple approach to solve this problem is to find all n triangle numbers. And adding them to the sum variable one by one. Initialise sum = 0. Step 1: loop for i = 0 to n. And follow steps 2 and 3 Step 2: for each value of i, calculate the triangular numbers using the formula, t[i] = ∑ i = i*(i+1)/2. Step 3: Update sum value, sum += t[i]. Step 4: return sum. Program to illustrate the working of our solution, Live Demo #include <iostream> using namespace std; int calcSeriesSum(int n) { int sum = 0; for (int i=1; i<=n; i++) sum += i*(i+1)/2; return sum; } int main() { int n = 6; cout<<"Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is "<<calcSeriesSum(n); return 0; } Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is 56 This is not the most effective solution as it takes O(n), time complexity. A more effective solution is by using the direct formula for the sum. If Ti is the i-th triangular number. Then, T1 = 1 T2 = 3 T3 = 6 Tn = n*(n+1) /2 Sum of all triangular numbers is sum = 1 + 3 + 6 + 10 + ... sum = T1 + T2 + T3 + ... + Tn sum = ∑ (Ti) , i -> 0 to n sum = ∑ (n)(n+1)/2 sum = 1⁄2 ∑ n2 + n sum = 1⁄2 ∑n^2 + ∑ n sum = 1⁄2 [ (n*(n+1)*(2n+1)/6) + (n*(n+1)/2) ] sum = 1⁄2 (n*(n+1)/2)*[ (2n+1)/3 + 1 ] sum = 1⁄4 [n*(n+1)]*[(2n+1+3)/3] sum = 1⁄4 [n*(n+1)]*[(2n+4)/3] sum = 1⁄4 [n*(n+1)]*[2(n+2)/3] sum= 1⁄6 [n*(n+1)*(n+2)] This is the general formula for the sum of triangle numbers. Program to illustrate the working of our solution, Live Demo #include <iostream> using namespace std; int calcSeriesSum(int n) { return ( ( n*(n + 1)*(n + 2) )/6); } int main() { int n = 6; cout<<"Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is "<<calcSeriesSum(n); return 0; } Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is 56
[ { "code": null, "e": 1255, "s": 1062, "text": "In this problem, we are given a number n which is given the n of elements of the series 1, 3, 6, 10 ... (triangular number). Our task is to create a program to calculate the sum of the series." }, { "code": null, "e": 1323, "s": 1255, "text": "Let’s brush up about triangular numbers before calculating the sum." }, { "code": null, "e": 1411, "s": 1323, "text": "Triangular numbers are those numbers that can be represented in the form of a triangle." }, { "code": null, "e": 1507, "s": 1411, "text": "A triangle is formed in such a way that the first row has one point, second has two, and so on." }, { "code": null, "e": 1513, "s": 1507, "text": "Input" }, { "code": null, "e": 1519, "s": 1513, "text": "n = 4" }, { "code": null, "e": 1526, "s": 1519, "text": "Output" }, { "code": null, "e": 1586, "s": 1526, "text": "Explanation − sum = T1 + T2 + T3 + T4 = 1 + 3 + 6 + 10 = 20" }, { "code": null, "e": 1709, "s": 1586, "text": "A simple approach to solve this problem is to find all n triangle numbers. And adding them to the sum variable one by one." }, { "code": null, "e": 1947, "s": 1709, "text": "Initialise sum = 0.\nStep 1: loop for i = 0 to n. And follow steps 2 and 3\nStep 2: for each value of i, calculate the triangular numbers using the formula, t[i] = ∑ i = i*(i+1)/2.\nStep 3: Update sum value, sum += t[i].\nStep 4: return sum." }, { "code": null, "e": 1998, "s": 1947, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 2009, "s": 1998, "text": " Live Demo" }, { "code": null, "e": 2290, "s": 2009, "text": "#include <iostream>\nusing namespace std;\nint calcSeriesSum(int n) {\n int sum = 0;\n for (int i=1; i<=n; i++)\n sum += i*(i+1)/2;\n return sum;\n}\nint main() {\n int n = 6;\n cout<<\"Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is \"<<calcSeriesSum(n);\n return 0;\n}" }, { "code": null, "e": 2351, "s": 2290, "text": "Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is 56" }, { "code": null, "e": 2426, "s": 2351, "text": "This is not the most effective solution as it takes O(n), time complexity." }, { "code": null, "e": 2496, "s": 2426, "text": "A more effective solution is by using the direct formula for the sum." }, { "code": null, "e": 2539, "s": 2496, "text": "If Ti is the i-th triangular number. Then," }, { "code": null, "e": 2546, "s": 2539, "text": "T1 = 1" }, { "code": null, "e": 2553, "s": 2546, "text": "T2 = 3" }, { "code": null, "e": 2560, "s": 2553, "text": "T3 = 6" }, { "code": null, "e": 2576, "s": 2560, "text": "Tn = n*(n+1) /2" }, { "code": null, "e": 2609, "s": 2576, "text": "Sum of all triangular numbers is" }, { "code": null, "e": 2958, "s": 2609, "text": "sum = 1 + 3 + 6 + 10 + ...\nsum = T1 + T2 + T3 + ... + Tn\nsum = ∑ (Ti) , i -> 0 to n\nsum = ∑ (n)(n+1)/2\nsum = 1⁄2 ∑ n2 + n\nsum = 1⁄2 ∑n^2 + ∑ n\nsum = 1⁄2 [ (n*(n+1)*(2n+1)/6) + (n*(n+1)/2) ]\nsum = 1⁄2 (n*(n+1)/2)*[ (2n+1)/3 + 1 ]\nsum = 1⁄4 [n*(n+1)]*[(2n+1+3)/3]\nsum = 1⁄4 [n*(n+1)]*[(2n+4)/3]\nsum = 1⁄4 [n*(n+1)]*[2(n+2)/3]\nsum= 1⁄6 [n*(n+1)*(n+2)]" }, { "code": null, "e": 3019, "s": 2958, "text": "This is the general formula for the sum of triangle numbers." }, { "code": null, "e": 3070, "s": 3019, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 3080, "s": 3070, "text": "Live Demo" }, { "code": null, "e": 3319, "s": 3080, "text": "#include <iostream>\nusing namespace std;\nint calcSeriesSum(int n) {\n return ( ( n*(n + 1)*(n + 2) )/6);\n}\nint main() {\n int n = 6;\n cout<<\"Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is \"<<calcSeriesSum(n);\n return 0;\n}" }, { "code": null, "e": 3380, "s": 3319, "text": "Sum of the series 1, 3, 6, 10 ... (Triangular Numbers) is 56" } ]
How to hide Firefox window (Selenium WebDriver)?
We can hide the Firefox window in Selenium webdriver. This can be done by making the browser headless. We shall achieve this with the FirefoxOptions class. We shall then create an object option of that class. We have to make the browser setting options.headless to True value. This driver object shall then receive this information. We need to have the import statement: from selenium.webdriver.firefox.options import Options as FirefoxOptions for adding the FirefoxOptions class. options = webdriver.FirefoxOptions() options.headless = True Code Implementation. from selenium import webdriver from selenium.webdriver.firefox.options import Options as FirefoxOptions #object of FirefoxOptions options = webdriver.FirefoxOptions() #setting headless parameter options.headless = True driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe", options=options) driver.implicitly_wait(0.8) driver.get("https://www.tutorialspoint.com/tutorialslibrary.htm") #identify element n = driver.find_element_by_xpath("//*[text()='Library']") #perform click n.click(); print("Page title after click: " + driver.title) driver.quit()
[ { "code": null, "e": 1271, "s": 1062, "text": "We can hide the Firefox window in Selenium webdriver. This can be done by making the browser headless. We shall achieve this with the FirefoxOptions class. We shall then create an object option of that class." }, { "code": null, "e": 1543, "s": 1271, "text": "We have to make the browser setting options.headless to True value. This driver object shall then receive this information. We need to have the import statement: from selenium.webdriver.firefox.options import Options as FirefoxOptions for adding the FirefoxOptions class." }, { "code": null, "e": 1604, "s": 1543, "text": "options = webdriver.FirefoxOptions()\noptions.headless = True" }, { "code": null, "e": 1625, "s": 1604, "text": "Code Implementation." }, { "code": null, "e": 2186, "s": 1625, "text": "from selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\n#object of FirefoxOptions\noptions = webdriver.FirefoxOptions()\n#setting headless parameter\noptions.headless = True\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\", options=options)\ndriver.implicitly_wait(0.8)\ndriver.get(\"https://www.tutorialspoint.com/tutorialslibrary.htm\")\n#identify element\nn = driver.find_element_by_xpath(\"//*[text()='Library']\")\n#perform click\nn.click();\nprint(\"Page title after click: \" + driver.title)\ndriver.quit()" } ]
Insertion Sort List C++
Suppose we have a linked list, we have to perform the insertion sort on this list. So if the list is like [9,45,23,71,80,55], sorted list is [9,23,45,55,71,80]. To solve this, we will follow these steps − dummy := new Node with some random value dummy := new Node with some random value node := given list node := given list while node is not null,newNode = next of node, dummyHead := next of dummy, prevDummyHead := dummywhile true −if dummyHead is not present, value of dummyHead > value of nodenext of node := dummyHeadnext of prevDummyHead := nodebreak the loopprevDummyHead := dymmyHead, and dummyHead = next of dummy headnode := nextNode while node is not null, newNode = next of node, dummyHead := next of dummy, prevDummyHead := dummy newNode = next of node, dummyHead := next of dummy, prevDummyHead := dummy while true −if dummyHead is not present, value of dummyHead > value of nodenext of node := dummyHeadnext of prevDummyHead := nodebreak the loopprevDummyHead := dymmyHead, and dummyHead = next of dummy head while true − if dummyHead is not present, value of dummyHead > value of nodenext of node := dummyHeadnext of prevDummyHead := nodebreak the loop if dummyHead is not present, value of dummyHead > value of node next of node := dummyHead next of node := dummyHead next of prevDummyHead := node next of prevDummyHead := node break the loop break the loop prevDummyHead := dymmyHead, and dummyHead = next of dummy head prevDummyHead := dymmyHead, and dummyHead = next of dummy head node := nextNode node := nextNode return next of dummy Let us see the following implementation to get better understanding − class Solution { public: ListNode* insertionSortList(ListNode* a) { ListNode* dummy = new ListNode(-1); ListNode* node = a; ListNode* nextNode; ListNode* dummyHead; ListNode* prevDummyHead; while(node != NULL){ nextNode = node->next; dummyHead = dummy->next; prevDummyHead = dummy; while(1){ if(!dummyHead || dummyHead->val > node->val){ node->next = dummyHead; prevDummyHead->next = node; //cout << prevDummyHead->val << " " << node->val << endl; break; } } prevDummyHead = dummyHead; dummyHead = dummyHead->next; } node = nextNode; } return dummy->next; } [9,45,23,71,80,55] [9,23,45,55,71,80]
[ { "code": null, "e": 1223, "s": 1062, "text": "Suppose we have a linked list, we have to perform the insertion sort on this list. So if the list is like [9,45,23,71,80,55], sorted list is [9,23,45,55,71,80]." }, { "code": null, "e": 1267, "s": 1223, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1308, "s": 1267, "text": "dummy := new Node with some random value" }, { "code": null, "e": 1349, "s": 1308, "text": "dummy := new Node with some random value" }, { "code": null, "e": 1368, "s": 1349, "text": "node := given list" }, { "code": null, "e": 1387, "s": 1368, "text": "node := given list" }, { "code": null, "e": 1706, "s": 1387, "text": "while node is not null,newNode = next of node, dummyHead := next of dummy, prevDummyHead := dummywhile true −if dummyHead is not present, value of dummyHead > value of nodenext of node := dummyHeadnext of prevDummyHead := nodebreak the loopprevDummyHead := dymmyHead, and dummyHead = next of dummy headnode := nextNode" }, { "code": null, "e": 1730, "s": 1706, "text": "while node is not null," }, { "code": null, "e": 1805, "s": 1730, "text": "newNode = next of node, dummyHead := next of dummy, prevDummyHead := dummy" }, { "code": null, "e": 1880, "s": 1805, "text": "newNode = next of node, dummyHead := next of dummy, prevDummyHead := dummy" }, { "code": null, "e": 2086, "s": 1880, "text": "while true −if dummyHead is not present, value of dummyHead > value of nodenext of node := dummyHeadnext of prevDummyHead := nodebreak the loopprevDummyHead := dymmyHead, and dummyHead = next of dummy head" }, { "code": null, "e": 2099, "s": 2086, "text": "while true −" }, { "code": null, "e": 2231, "s": 2099, "text": "if dummyHead is not present, value of dummyHead > value of nodenext of node := dummyHeadnext of prevDummyHead := nodebreak the loop" }, { "code": null, "e": 2295, "s": 2231, "text": "if dummyHead is not present, value of dummyHead > value of node" }, { "code": null, "e": 2321, "s": 2295, "text": "next of node := dummyHead" }, { "code": null, "e": 2347, "s": 2321, "text": "next of node := dummyHead" }, { "code": null, "e": 2377, "s": 2347, "text": "next of prevDummyHead := node" }, { "code": null, "e": 2407, "s": 2377, "text": "next of prevDummyHead := node" }, { "code": null, "e": 2422, "s": 2407, "text": "break the loop" }, { "code": null, "e": 2437, "s": 2422, "text": "break the loop" }, { "code": null, "e": 2500, "s": 2437, "text": "prevDummyHead := dymmyHead, and dummyHead = next of dummy head" }, { "code": null, "e": 2563, "s": 2500, "text": "prevDummyHead := dymmyHead, and dummyHead = next of dummy head" }, { "code": null, "e": 2580, "s": 2563, "text": "node := nextNode" }, { "code": null, "e": 2597, "s": 2580, "text": "node := nextNode" }, { "code": null, "e": 2618, "s": 2597, "text": "return next of dummy" }, { "code": null, "e": 2688, "s": 2618, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3453, "s": 2688, "text": "class Solution {\n public:\n ListNode* insertionSortList(ListNode* a) {\n ListNode* dummy = new ListNode(-1);\n ListNode* node = a;\n ListNode* nextNode;\n ListNode* dummyHead;\n ListNode* prevDummyHead;\n while(node != NULL){\n nextNode = node->next;\n dummyHead = dummy->next;\n prevDummyHead = dummy;\n while(1){\n if(!dummyHead || dummyHead->val > node->val){\n node->next = dummyHead;\n prevDummyHead->next = node;\n //cout << prevDummyHead->val << \" \" << node->val << endl;\n break;\n }\n }\n prevDummyHead = dummyHead;\n dummyHead = dummyHead->next;\n }\n node = nextNode;\n }\n return dummy->next;\n}" }, { "code": null, "e": 3472, "s": 3453, "text": "[9,45,23,71,80,55]" }, { "code": null, "e": 3491, "s": 3472, "text": "[9,23,45,55,71,80]" } ]
What is the purpose of a default constructor in Java?
A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. There are two types of constructors namely − parameterized constructors − Constructors with arguments. no-arg constructors − Constructors without arguments. Live Demo public class Sample{ int num; Sample(){ num = 100; } Sample(int num){ this.num = num; } public static void main(String args[]){ System.out.println(new Sample().num); System.out.println(new Sample(1000).num); } } 100 1000 It is recommended to provide any of the above-mentioned contractors while defining a class. If not Java compiler provides a no-argument, default constructor on your behalf. This is a constructor initializes the variables of the class with their respective default values (i.e. null for objects, 0.0 for float and double, false for boolean, 0 for byte, short, int and, long). If you observe the following example, we are not providing any constructor to it. public class Sample{ int num; public static void main(String args[]){ System.out.println(new Sample().num); } } If you compile and run the above program the default constructor initializes the integer variable num with 0 and, you will get 0 as result. The javap command displays information about the fields, constructors, and methods of a class. If you (after compiling it) run the above class using javap command, you can observe the default constructor added by the compiler as shown below: D:\>javap Sample Compiled from "Sample.java" public class Sample { int num; public Sample(); public static void main(java.lang.String[]); }
[ { "code": null, "e": 1291, "s": 1062, "text": "A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. There are two types of constructors namely −" }, { "code": null, "e": 1349, "s": 1291, "text": "parameterized constructors − Constructors with arguments." }, { "code": null, "e": 1403, "s": 1349, "text": "no-arg constructors − Constructors without arguments." }, { "code": null, "e": 1414, "s": 1403, "text": " Live Demo" }, { "code": null, "e": 1671, "s": 1414, "text": "public class Sample{\n int num;\n Sample(){\n num = 100;\n }\n Sample(int num){\n this.num = num;\n }\n public static void main(String args[]){\n System.out.println(new Sample().num);\n System.out.println(new Sample(1000).num);\n }\n}" }, { "code": null, "e": 1680, "s": 1671, "text": "100\n1000" }, { "code": null, "e": 1853, "s": 1680, "text": "It is recommended to provide any of the above-mentioned contractors while defining a class. If not Java compiler provides a no-argument, default constructor on your behalf." }, { "code": null, "e": 2055, "s": 1853, "text": "This is a constructor initializes the variables of the class with their respective default values (i.e. null for objects, 0.0 for float and double, false for boolean, 0 for byte, short, int and, long)." }, { "code": null, "e": 2137, "s": 2055, "text": "If you observe the following example, we are not providing any constructor to it." }, { "code": null, "e": 2264, "s": 2137, "text": "public class Sample{\n int num;\n public static void main(String args[]){\n System.out.println(new Sample().num);\n }\n}" }, { "code": null, "e": 2404, "s": 2264, "text": "If you compile and run the above program the default constructor initializes the integer variable num with 0 and, you will get 0 as result." }, { "code": null, "e": 2646, "s": 2404, "text": "The javap command displays information about the fields, constructors, and methods of a class. If you (after compiling it) run the above class using javap command, you can observe the default constructor added by the compiler as shown below:" }, { "code": null, "e": 2795, "s": 2646, "text": "D:\\>javap Sample\nCompiled from \"Sample.java\"\npublic class Sample {\n int num;\n public Sample();\n public static void main(java.lang.String[]);\n}" } ]
Arduino - Mouse Button Control
Using the Mouse library, you can control a computer's onscreen cursor with an Arduino Leonardo, Micro, or Due. This particular example uses five pushbuttons to move the onscreen cursor. Four of the buttons are directional (up, down, left, right) and one is for a left mouse click. Cursor movement from Arduino is always relative. Every time an input is read, the cursor's position is updated relative to its current position. Whenever one of the directional buttons is pressed, Arduino will move the mouse, mapping a HIGH input to a range of 5 in the appropriate direction. The fifth button is for controlling a left-click from the mouse. When the button is released, the computer will recognize the event. You will need the following components − 1 × Breadboard 1 × Arduino Leonardo, Micro or Due board 5 × 10k ohm resistor 5 × momentary pushbuttons Follow the circuit diagram and hook up the components on the breadboard as shown in the image below. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. For this example, you need to use Arduino IDE 1.6.7 /* Button Mouse Control For Leonardo and Due boards only .Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due. Hardware: * 5 pushbuttons attached to D2, D3, D4, D5, D6 The mouse movement is always relative. This sketch reads four pushbuttons, and uses them to set the movement of the mouse. WARNING: When you use the Mouse.move() command, the Arduino takes over your mouse! Make sure you have control before you use the mouse commands. */ #include "Mouse.h" // set pin numbers for the five buttons: const int upButton = 2; const int downButton = 3; const int leftButton = 4; const int rightButton = 5; const int mouseButton = 6; int range = 5; // output range of X or Y movement; affects movement speed int responseDelay = 10; // response delay of the mouse, in ms void setup() { // initialize the buttons' inputs: pinMode(upButton, INPUT); pinMode(downButton, INPUT); pinMode(leftButton, INPUT); pinMode(rightButton, INPUT); pinMode(mouseButton, INPUT); // initialize mouse control: Mouse.begin(); } void loop() { // read the buttons: int upState = digitalRead(upButton); int downState = digitalRead(downButton); int rightState = digitalRead(rightButton); int leftState = digitalRead(leftButton); int clickState = digitalRead(mouseButton); // calculate the movement distance based on the button states: int xDistance = (leftState - rightState) * range; int yDistance = (upState - downState) * range; // if X or Y is non-zero, move: if ((xDistance != 0) || (yDistance != 0)) { Mouse.move(xDistance, yDistance, 0); } // if the mouse button is pressed: if (clickState == HIGH) { // if the mouse is not pressed, press it: if (!Mouse.isPressed(MOUSE_LEFT)) { Mouse.press(MOUSE_LEFT); } } else { // else the mouse button is not pressed: // if the mouse is pressed, release it: if (Mouse.isPressed(MOUSE_LEFT)) { Mouse.release(MOUSE_LEFT); } } // a delay so the mouse does not move too fast: delay(responseDelay); } Connect your board to your computer with a micro-USB cable. The buttons are connected to digital inputs from pins 2 to 6. Make sure you use 10k pull-down resistors. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2981, "s": 2870, "text": "Using the Mouse library, you can control a computer's onscreen cursor with an Arduino Leonardo, Micro, or Due." }, { "code": null, "e": 3296, "s": 2981, "text": "This particular example uses five pushbuttons to move the onscreen cursor. Four of the buttons are directional (up, down, left, right) and one is for a left mouse click. Cursor movement from Arduino is always relative. Every time an input is read, the cursor's position is updated relative to its current position." }, { "code": null, "e": 3444, "s": 3296, "text": "Whenever one of the directional buttons is pressed, Arduino will move the mouse, mapping a HIGH input to a range of 5 in the appropriate direction." }, { "code": null, "e": 3577, "s": 3444, "text": "The fifth button is for controlling a left-click from the mouse. When the button is released, the computer will recognize the event." }, { "code": null, "e": 3618, "s": 3577, "text": "You will need the following components −" }, { "code": null, "e": 3633, "s": 3618, "text": "1 × Breadboard" }, { "code": null, "e": 3674, "s": 3633, "text": "1 × Arduino Leonardo, Micro or Due board" }, { "code": null, "e": 3695, "s": 3674, "text": "5 × 10k ohm resistor" }, { "code": null, "e": 3721, "s": 3695, "text": "5 × momentary pushbuttons" }, { "code": null, "e": 3822, "s": 3721, "text": "Follow the circuit diagram and hook up the components on the breadboard as shown in the image below." }, { "code": null, "e": 3968, "s": 3822, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New." }, { "code": null, "e": 4020, "s": 3968, "text": "For this example, you need to use Arduino IDE 1.6.7" }, { "code": null, "e": 6152, "s": 4020, "text": "/*\n Button Mouse Control\n For Leonardo and Due boards only .Controls the mouse from \n five pushbuttons on an Arduino Leonardo, Micro or Due.\n Hardware:\n * 5 pushbuttons attached to D2, D3, D4, D5, D6\n The mouse movement is always relative. This sketch reads\n four pushbuttons, and uses them to set the movement of the mouse.\n WARNING: When you use the Mouse.move() command, the Arduino takes\n over your mouse! Make sure you have control before you use the mouse commands.\n*/\n\n#include \"Mouse.h\"\n// set pin numbers for the five buttons:\nconst int upButton = 2;\nconst int downButton = 3;\nconst int leftButton = 4;\nconst int rightButton = 5;\nconst int mouseButton = 6;\nint range = 5; // output range of X or Y movement; affects movement speed\nint responseDelay = 10; // response delay of the mouse, in ms\n\nvoid setup() {\n // initialize the buttons' inputs:\n pinMode(upButton, INPUT);\n pinMode(downButton, INPUT);\n pinMode(leftButton, INPUT);\n pinMode(rightButton, INPUT);\n pinMode(mouseButton, INPUT);\n // initialize mouse control:\n Mouse.begin();\n}\n\nvoid loop() {\n // read the buttons:\n int upState = digitalRead(upButton);\n int downState = digitalRead(downButton);\n int rightState = digitalRead(rightButton);\n int leftState = digitalRead(leftButton);\n int clickState = digitalRead(mouseButton);\n // calculate the movement distance based on the button states:\n int xDistance = (leftState - rightState) * range;\n int yDistance = (upState - downState) * range;\n // if X or Y is non-zero, move:\n if ((xDistance != 0) || (yDistance != 0)) {\n Mouse.move(xDistance, yDistance, 0);\n }\n\n // if the mouse button is pressed:\n if (clickState == HIGH) {\n // if the mouse is not pressed, press it:\n if (!Mouse.isPressed(MOUSE_LEFT)) {\n Mouse.press(MOUSE_LEFT);\n }\n } else { // else the mouse button is not pressed:\n // if the mouse is pressed, release it:\n if (Mouse.isPressed(MOUSE_LEFT)) {\n Mouse.release(MOUSE_LEFT);\n }\n }\n // a delay so the mouse does not move too fast:\n delay(responseDelay);\n}" }, { "code": null, "e": 6317, "s": 6152, "text": "Connect your board to your computer with a micro-USB cable. The buttons are connected to digital inputs from pins 2 to 6. Make sure you use 10k pull-down resistors." }, { "code": null, "e": 6352, "s": 6317, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6363, "s": 6352, "text": " Amit Rana" }, { "code": null, "e": 6396, "s": 6363, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 6407, "s": 6396, "text": " Amit Rana" }, { "code": null, "e": 6440, "s": 6407, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6453, "s": 6440, "text": " Ashraf Said" }, { "code": null, "e": 6488, "s": 6453, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6501, "s": 6488, "text": " Ashraf Said" }, { "code": null, "e": 6533, "s": 6501, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 6546, "s": 6533, "text": " Ashraf Said" }, { "code": null, "e": 6577, "s": 6546, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 6590, "s": 6577, "text": " Ashraf Said" }, { "code": null, "e": 6597, "s": 6590, "text": " Print" }, { "code": null, "e": 6608, "s": 6597, "text": " Add Notes" } ]
Cyber Security - Types of Enumeration - GeeksforGeeks
14 Jan, 2022 Enumeration is fundamentally checking. An attacker sets up a functioning associated with the objective host. The weaknesses are then tallied and evaluated. It is done mostly to look for assaults and dangers to the objective framework. Enumeration is utilized to gather usernames, hostname, IP addresses, passwords, arrangements, and so on. At the point when a functioning connection with the objective host is set up, hackers oversee the objective framework. They at that point take private data and information. Now and again, aggressors have additionally been discovered changing the setup of the objective frameworks. The manner in which the connection is set up to the host decides the information or data the attacker will have the option to get to. In this section, we will be discussing the various types of Enumerations. 1. NetBIOS(Network Basic Input Output System) Enumeration: NetBIOS name is an exceptional 16 ASCII character string used to distinguish the organization gadgets over TCP/IP, 15 characters are utilized for the gadget name and the sixteenth character is saved for the administration or name record type. Programmers utilize the NetBIOS enumeration to get a rundown of PCs that have a place with a specific domain, a rundown of offers on the individual hosts in the organization, and strategies and passwords. NetBIOS name goal isn’t supported by Microsoft for Internet Protocol Version 6. The initial phase in specifying a Windows framework is to exploit the NetBIOS API. It was initially an Application Programming Interface(API) for custom programming to get to LAN assets. Windows utilizes NetBIOS for document and printer sharing. A hacker who finds a Windows OS with port 139 open, can verify what assets can be gotten to or seen on the far off framework. In any case, to count the NetBIOS names, the distant framework probably empowered document and printer sharing. This sort of enumeration may empower the programmer to peruse or keep in touch with the distant PC framework, contingent upon the accessibility of offers, or dispatch a DoS. NetBIOS name list: Nbtstat Utility: In Windows, it shows NetBIOS over TCP/IP (NetBT) convention insights, NetBIOS name tables for both the neighborhood and distant PCs, and the NetBIOS name reserve. This utility allows a resuscitate of the NetBIOS name cache and the names selected with Windows Internet Name Service. The sentence structure for Nbtstat: nbtstat [-a RemoteName] [-A IPAddress] [-c] [-n] [-r] [-R] [-RR] [-s] [-S] [Interval] The table appeared beneath shows different Nbtstat boundaries: 2. SNMP(Simple Network Management Protocol) Enumeration: SNMP enumeration is a cycle of specifying client records and gadgets on an objective framework utilizing SNMP. SNMP comprises a manager and a specialist; specialists are inserted on each organization gadget, and the trough is introduced on a different PC. SNMP holds two passwords to get to and design the SNMP specialist from the administration station. Read Community String is public of course; permits review of gadget/framework setup. Read/Write people group string is private of course; permits far off altering of arrangement. Hackers utilize these default network strings to remove data about a gadget. Hackers list SNMP to remove data about organization assets, for example, has, switches, gadgets, shares, and so on, and network data, for example, ARP tables, directing tables, traffic, and so forth. SNMP utilizes dispersed engineering containing SNMP agents, managers, and a few related parts. Orders related with SNMP include: GetRequest, GetNextRequest, GetResponse, SetRequest, Trap. Given below is the communication between the SNMP agent and manager: SNMP Enumeration tools are utilized to examine a solitary IP address or a scope of IP addresses of SNMP empowered organization gadgets to screen, analyze, and investigate security dangers. Instances of this sort of instruments incorporate NetScanTolls Pro, SoftPerfect Network Scanner, SNMP Informant, and so forth 3. LDAP Enumeration: Lightweight Directory Access Protocol is an Internet Protocol for getting to dispersed registry administrations. Registry administrations may give any coordinated arrangement of records, regularly in a hierarchical and sensible structure, for example, a corporate email index. A customer starts an LDAP meeting by associating with a Directory System Agent on TCP port 389 and afterward sends an activity solicitation to the DSA. Data is sent between the customer and the worker utilizing Basic Encoding Rules. Programmer inquiries LDAP administration to assemble information such as substantial usernames, addresses, division subtleties, and so on that can be additionally used to perform assaults. There are numerous LDAP enumeration apparatuses that entrance the registry postings inside Active Directory or other catalog administrations. Utilizing these devices, assailants can identify data, for example, substantial usernames, addresses, division subtleties, and so forth from various LDAP workers. Examples of these kinds of tools include LDAP Admin Tool, Active Directory Explorer, LDAP Admin, etc. 4. NTP Enumeration: Network Time Protocol is intended to synchronize clocks of arranged PCs. It utilizes UDP port 123 as its essential method for correspondence. NTP can check time to inside 10 milliseconds (1/100 seconds) over the public web. It can accomplish correctness of 200 microseconds or better in a neighborhood under ideal conditions. Executives regularly disregard the NTP worker regarding security. Be that as it may, whenever questioned appropriately, it can give important organization data to the programmers. Hackers inquiries NTP workers to assemble significant data, for example, a list of hosts associated with NTP workers, Clients’ IP addresses in an organization, their framework names and Oss, and Internal IPs can likewise be gotten if NTP worker is in the demilitarized zone. NTP enumeration tools are utilized to screen the working of SNTP and NTP workers present in the organization and furthermore help in the configuration and confirmation of availability from the time customer to the NTP workers. 5. SMTP Enumeration: Mail frameworks ordinarily use SMTP with POP3 and IMAP that empowers clients to spare the messages in the worker letter drop and download them once in a while from the mainframe. SMTP utilizes Mail Exchange (MX) workers to coordinate the mail through DNS. It runs on TCP port 25. SMTP provides 3 built-in commands: VRFY, EXPN, RCPT TO. These servers respond differently to the commands for valid and invalid users from which we can determine valid users on SMTP servers. Hackers can legitimately associate with SMTP through telnet brief and gather a rundown of substantial clients on the mainframe. Hackers can perform SMTP enumeration using command-line utilities such as telnet, netcat, etc., or by using tools such as Metasploit, Nmap, NetScanTools Pro, etc. 6. DNS Enumeration using Zone Transfer: It is a cycle for finding the DNS worker and the records of an objective organization. A hacker can accumulate significant organization data, for example, DNS worker names, hostname, machine names, usernames, IPs, and so forth of the objectives. In DNS Zone Transfer enumeration, a hacker tries to retrieve a copy of the entire zone file for a domain from the DNS server. In order to execute a zone transfer, the hacker sends a zone transfer request to the DNS server pretending to be a client; the DNS then sends a portion of its database as a zone to you. This zone may contain a ton of data about the DNS zone organization. 7. IPsec Enumeration: IPsec utilizes ESP (Encapsulation Security Payload), AH (Authentication Header), and IKE (Internet Key Exchange) to make sure about the correspondence between virtual private organization (VPN) end focuses. Most IPsec-based VPNs use the Internet Security Association and Key Management Protocol, a piece of IKE, to establish, arrange, alter, and erase Security Associations and cryptographic keys in a VPN climate. A straightforward checking for ISAKMP at the UDP port 500 can demonstrate the presence of a VPN passage. Hackers can research further utilizing an apparatus, for example, IKE-output to identify the delicate information including encryption and hashing calculation, authentication type, key conveyance calculation, and so forth. 8. VoIP(Voice over IP) Enumeration: VoIP uses the SIP (Session Initiation Protocol) protocol to enable voice and video calls over an IP network. SIP administration by and large uses UDP/TCP ports 2000, 2001, 5050, 5061. VoIP enumeration provides sensitive information such as VoIP gateway/servers, IP-PBX systems, client software, and user extensions. This information can be used to launch various VoIP attacks such as DoS, Session Hijacking, Caller ID spoofing, Eavesdropping, Spamming over Internet Telephony, VoIP phishing, etc. 9. RPC Enumeration: Remote Procedure Call permits customers and workers to impart in disseminated customer/worker programs. Counting RPC endpoints empower aggressors to recognize any weak administrations on these administration ports. In networks ensured by firewalls and other security establishments, this portmapper is regularly sifted. Along these lines, hackers filter high port reaches to recognize RPC administrations that are available to coordinate an assault. 10. Unix/Linux User Enumeration: One of the most vital steps for conducting an enumeration is to perform this kind of enumeration. This provides a list of users along with details like username, hostname, start date and time of each session, etc. We can use command-line utilities to perform Linux user enumeration like users, rwho, finger, etc. 11. SMB Enumeration: SMB list is significant expertise for any pen-tester. Prior to figuring out how to count SMB, we should initially realize what SMB is. SMB represents server message block. It’s a convention for sharing assets like records, printers, by and large, any asset which should be retrievable or made accessible by the server. It fundamentally runs on port 445 or port 139 relying upon the server. It is quite accessible in windows, so windows clients don’t have to arrange anything extra as such other than essential set up. In Linux in any case, it is somewhat extraordinary. To make it work for Linux, you have to introduce a samba server since Linux locally doesn’t utilize SMB convention. Clearly, some kind of confirmation will be set up like a username and secret word, and just certain assets made shareable. So dislike everybody can get to everything, a solid confirmation. The main evident defect is utilizing default certifications or effectively guessable and sometimes even no verification for access of significant assets of the server. Administrators should make a point to utilize solid passwords for clients who need to get to assets utilizing SMB. The subsequent blemish is the samba server. Samba servers are infamous for being hugely vulnerable. There are several countermeasures which can be taken into account for the mitigation of several kinds of enumeration: 1. NetBIOS Enumeration: Disable SMB and NetBIOS. Use a network firewall. Prefer Windows firewall/ software firewalls. Disable sharing. 2. SNMP Enumeration: Eliminate the specialist or shut off the SNMP administration. In the event that stopping SNMP isn’t a choice, at that point change the default network string names. Move up to SNMP3, which encodes passwords and messages. Actualize the Group Policy security alternative. 3. LDAP Enumeration: Utilize SSL technology to encrypt the traffic. Select a username unique in relation to your email address and empower account lockout. 4. NTP Enumeration: Configure MD5 Layer. Configure NTP Authentication. Upgrade NTP version. 5. SMTP Enumeration: Ignore email messages to unknown recipients. Disable open relay feature. Breaking point the number of acknowledged associations from a source to forestall brute force exploits. Not to include sensitive mail server and localhost information in mail responses. 6. DNS Enumeration Using Zone Transfer: Incapacitate the DNS Zone moves to the untrusted hosts. Make sure that the private hosts and their IP addresses are not published in DNS zone files of the public DNS server. Use premium DNS regulation services that hide sensitive information such as host information from the public. Utilize standard organization administrator contacts for DNS enlistment to maintain a strategic distance from social designing assaults. Avoid publishing Private IP address information into the zone file. Disable Zone Transfer for untrusted hosts. Hide Sensitive information from public hosts. 7. IPsec Enumeration: Preshared keys utilized with both fundamental and forceful mode IKE key trade components are available to sniffing and disconnected savage power granulating assaults to bargain the shared mystery. You should utilize advanced testaments or two-factor validation components to refute these dangers. Pre-shared keys and forceful mode IKE uphold is a catastrophe waiting to happen. On the off chance that you should uphold forceful mode IKE, utilize advanced declarations for verification. Forcefully firewall and channel traffic coursing through VPN encrypted tunnel so that, in case of a trade-off, network access is restricted. This point is particularly significant while giving versatile clients network access, instead of branch workplaces. Where conceivable, limit inbound IPsec security relationship to explicit IP addresses. This guarantees that regardless of whether an aggressor bargains a preshared key, she can only with significant effort access the VPN. 8. VoIP(Voice over IP) Enumeration: This hack can be smothered by actualizing SIPS (SIP over TLS) and confirming SIP queries and reactions (which can incorporate uprightness insurance). The utilization of SIPS and the verification of reactions can stifle many related hacks including eavesdropping and message or client pantomime. The utilization of digest confirmation joined with the utilization of TLS between SIP telephones and SIP intermediaries can give a station through which clients can safely validate inside their SIP domain. Voicemail messages can be changed over to message records and parsed by ordinary spam channels. This can just shield clients from SPIT voicemails. 9. RPC Enumeration: Try not to run rexd, users, or rwalld RPC administrations, since they are of negligible utilization and give aggressors both valuable data and direct admittance to your hosts. In high-security conditions, don’t offer any RPC administrations to the public Internet. Because of the unpredictability of these administrations, almost certainly, zero-day misuse contents will be accessible to assailants before fixed data is delivered. To limit the danger of inner or confided in hacks against vital RPC administrations, (for example, NFS segments, including statd, lockd, and mountd), introduce the most recent seller security patches. Forcefully channel egress traffic, where conceivable, to guarantee that regardless of whether an assault against an RPC administration is effective, an associate back shell can’t be brought forth to the hacker. 10. Unix/Linux User Enumeration: Keep the kernel fixed and refreshed. Never run any service as root except if truly required, particularly the web, information base, and record mainframes. SUID digit ought not to be set to any program which lets you getaway to the shell. You should never set SUID cycle on any record supervisor/compiler/mediator as an aggressor can undoubtedly peruse/overwrite any documents present on the framework. Try not to give sudo rights to any program which lets you break to the shell. 11. SMB Enumeration: Impair SMB convention on Web and DNS mainframes. Debilitate SMB convention web confronting mainframes. Handicap ports TCP 139 and TCP 445 utilized by the SMB convention. Restrict anonymous access through the RestrictNull Access parameter from the Windows Registry. ruhelaa48 rkbhola5 Cyber-security Advanced Computer Subject Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Copying Files to and from Docker Containers ML | Stochastic Gradient Descent (SGD) Principal Component Analysis with Python Fuzzy Logic | Introduction How to create a REST API using Java Spring Boot Layers of OSI Model RSA Algorithm in Cryptography TCP/IP Model TCP Server-Client implementation in C Basics of Computer Networking
[ { "code": null, "e": 24174, "s": 24146, "text": "\n14 Jan, 2022" }, { "code": null, "e": 24929, "s": 24174, "text": "Enumeration is fundamentally checking. An attacker sets up a functioning associated with the objective host. The weaknesses are then tallied and evaluated. It is done mostly to look for assaults and dangers to the objective framework. Enumeration is utilized to gather usernames, hostname, IP addresses, passwords, arrangements, and so on. At the point when a functioning connection with the objective host is set up, hackers oversee the objective framework. They at that point take private data and information. Now and again, aggressors have additionally been discovered changing the setup of the objective frameworks. The manner in which the connection is set up to the host decides the information or data the attacker will have the option to get to." }, { "code": null, "e": 25003, "s": 24929, "text": "In this section, we will be discussing the various types of Enumerations." }, { "code": null, "e": 25063, "s": 25003, "text": "1. NetBIOS(Network Basic Input Output System) Enumeration: " }, { "code": null, "e": 25306, "s": 25063, "text": "NetBIOS name is an exceptional 16 ASCII character string used to distinguish the organization gadgets over TCP/IP, 15 characters are utilized for the gadget name and the sixteenth character is saved for the administration or name record type." }, { "code": null, "e": 25511, "s": 25306, "text": "Programmers utilize the NetBIOS enumeration to get a rundown of PCs that have a place with a specific domain, a rundown of offers on the individual hosts in the organization, and strategies and passwords." }, { "code": null, "e": 25591, "s": 25511, "text": "NetBIOS name goal isn’t supported by Microsoft for Internet Protocol Version 6." }, { "code": null, "e": 25837, "s": 25591, "text": "The initial phase in specifying a Windows framework is to exploit the NetBIOS API. It was initially an Application Programming Interface(API) for custom programming to get to LAN assets. Windows utilizes NetBIOS for document and printer sharing." }, { "code": null, "e": 26249, "s": 25837, "text": "A hacker who finds a Windows OS with port 139 open, can verify what assets can be gotten to or seen on the far off framework. In any case, to count the NetBIOS names, the distant framework probably empowered document and printer sharing. This sort of enumeration may empower the programmer to peruse or keep in touch with the distant PC framework, contingent upon the accessibility of offers, or dispatch a DoS." }, { "code": null, "e": 26268, "s": 26249, "text": "NetBIOS name list:" }, { "code": null, "e": 26603, "s": 26268, "text": "Nbtstat Utility: In Windows, it shows NetBIOS over TCP/IP (NetBT) convention insights, NetBIOS name tables for both the neighborhood and distant PCs, and the NetBIOS name reserve. This utility allows a resuscitate of the NetBIOS name cache and the names selected with Windows Internet Name Service. The sentence structure for Nbtstat:" }, { "code": null, "e": 26689, "s": 26603, "text": "nbtstat [-a RemoteName] [-A IPAddress] [-c] [-n] [-r] [-R] [-RR] [-s] [-S] [Interval]" }, { "code": null, "e": 26752, "s": 26689, "text": "The table appeared beneath shows different Nbtstat boundaries:" }, { "code": null, "e": 26810, "s": 26752, "text": "2. SNMP(Simple Network Management Protocol) Enumeration: " }, { "code": null, "e": 27066, "s": 26810, "text": "SNMP enumeration is a cycle of specifying client records and gadgets on an objective framework utilizing SNMP. SNMP comprises a manager and a specialist; specialists are inserted on each organization gadget, and the trough is introduced on a different PC." }, { "code": null, "e": 27344, "s": 27066, "text": "SNMP holds two passwords to get to and design the SNMP specialist from the administration station. Read Community String is public of course; permits review of gadget/framework setup. Read/Write people group string is private of course; permits far off altering of arrangement." }, { "code": null, "e": 27621, "s": 27344, "text": "Hackers utilize these default network strings to remove data about a gadget. Hackers list SNMP to remove data about organization assets, for example, has, switches, gadgets, shares, and so on, and network data, for example, ARP tables, directing tables, traffic, and so forth." }, { "code": null, "e": 27809, "s": 27621, "text": "SNMP utilizes dispersed engineering containing SNMP agents, managers, and a few related parts. Orders related with SNMP include: GetRequest, GetNextRequest, GetResponse, SetRequest, Trap." }, { "code": null, "e": 27878, "s": 27809, "text": "Given below is the communication between the SNMP agent and manager:" }, { "code": null, "e": 28193, "s": 27878, "text": "SNMP Enumeration tools are utilized to examine a solitary IP address or a scope of IP addresses of SNMP empowered organization gadgets to screen, analyze, and investigate security dangers. Instances of this sort of instruments incorporate NetScanTolls Pro, SoftPerfect Network Scanner, SNMP Informant, and so forth" }, { "code": null, "e": 28214, "s": 28193, "text": "3. LDAP Enumeration:" }, { "code": null, "e": 28327, "s": 28214, "text": "Lightweight Directory Access Protocol is an Internet Protocol for getting to dispersed registry administrations." }, { "code": null, "e": 28491, "s": 28327, "text": "Registry administrations may give any coordinated arrangement of records, regularly in a hierarchical and sensible structure, for example, a corporate email index." }, { "code": null, "e": 28643, "s": 28491, "text": "A customer starts an LDAP meeting by associating with a Directory System Agent on TCP port 389 and afterward sends an activity solicitation to the DSA." }, { "code": null, "e": 28724, "s": 28643, "text": "Data is sent between the customer and the worker utilizing Basic Encoding Rules." }, { "code": null, "e": 28913, "s": 28724, "text": "Programmer inquiries LDAP administration to assemble information such as substantial usernames, addresses, division subtleties, and so on that can be additionally used to perform assaults." }, { "code": null, "e": 29218, "s": 28913, "text": "There are numerous LDAP enumeration apparatuses that entrance the registry postings inside Active Directory or other catalog administrations. Utilizing these devices, assailants can identify data, for example, substantial usernames, addresses, division subtleties, and so forth from various LDAP workers." }, { "code": null, "e": 29320, "s": 29218, "text": "Examples of these kinds of tools include LDAP Admin Tool, Active Directory Explorer, LDAP Admin, etc." }, { "code": null, "e": 29340, "s": 29320, "text": "4. NTP Enumeration:" }, { "code": null, "e": 29413, "s": 29340, "text": "Network Time Protocol is intended to synchronize clocks of arranged PCs." }, { "code": null, "e": 29482, "s": 29413, "text": "It utilizes UDP port 123 as its essential method for correspondence." }, { "code": null, "e": 29564, "s": 29482, "text": "NTP can check time to inside 10 milliseconds (1/100 seconds) over the public web." }, { "code": null, "e": 29666, "s": 29564, "text": "It can accomplish correctness of 200 microseconds or better in a neighborhood under ideal conditions." }, { "code": null, "e": 29846, "s": 29666, "text": "Executives regularly disregard the NTP worker regarding security. Be that as it may, whenever questioned appropriately, it can give important organization data to the programmers." }, { "code": null, "e": 30121, "s": 29846, "text": "Hackers inquiries NTP workers to assemble significant data, for example, a list of hosts associated with NTP workers, Clients’ IP addresses in an organization, their framework names and Oss, and Internal IPs can likewise be gotten if NTP worker is in the demilitarized zone." }, { "code": null, "e": 30348, "s": 30121, "text": "NTP enumeration tools are utilized to screen the working of SNTP and NTP workers present in the organization and furthermore help in the configuration and confirmation of availability from the time customer to the NTP workers." }, { "code": null, "e": 30369, "s": 30348, "text": "5. SMTP Enumeration:" }, { "code": null, "e": 30548, "s": 30369, "text": "Mail frameworks ordinarily use SMTP with POP3 and IMAP that empowers clients to spare the messages in the worker letter drop and download them once in a while from the mainframe." }, { "code": null, "e": 30649, "s": 30548, "text": "SMTP utilizes Mail Exchange (MX) workers to coordinate the mail through DNS. It runs on TCP port 25." }, { "code": null, "e": 30705, "s": 30649, "text": "SMTP provides 3 built-in commands: VRFY, EXPN, RCPT TO." }, { "code": null, "e": 30840, "s": 30705, "text": "These servers respond differently to the commands for valid and invalid users from which we can determine valid users on SMTP servers." }, { "code": null, "e": 30968, "s": 30840, "text": "Hackers can legitimately associate with SMTP through telnet brief and gather a rundown of substantial clients on the mainframe." }, { "code": null, "e": 31131, "s": 30968, "text": "Hackers can perform SMTP enumeration using command-line utilities such as telnet, netcat, etc., or by using tools such as Metasploit, Nmap, NetScanTools Pro, etc." }, { "code": null, "e": 31171, "s": 31131, "text": "6. DNS Enumeration using Zone Transfer:" }, { "code": null, "e": 31258, "s": 31171, "text": "It is a cycle for finding the DNS worker and the records of an objective organization." }, { "code": null, "e": 31417, "s": 31258, "text": "A hacker can accumulate significant organization data, for example, DNS worker names, hostname, machine names, usernames, IPs, and so forth of the objectives." }, { "code": null, "e": 31543, "s": 31417, "text": "In DNS Zone Transfer enumeration, a hacker tries to retrieve a copy of the entire zone file for a domain from the DNS server." }, { "code": null, "e": 31798, "s": 31543, "text": "In order to execute a zone transfer, the hacker sends a zone transfer request to the DNS server pretending to be a client; the DNS then sends a portion of its database as a zone to you. This zone may contain a ton of data about the DNS zone organization." }, { "code": null, "e": 31820, "s": 31798, "text": "7. IPsec Enumeration:" }, { "code": null, "e": 32027, "s": 31820, "text": "IPsec utilizes ESP (Encapsulation Security Payload), AH (Authentication Header), and IKE (Internet Key Exchange) to make sure about the correspondence between virtual private organization (VPN) end focuses." }, { "code": null, "e": 32235, "s": 32027, "text": "Most IPsec-based VPNs use the Internet Security Association and Key Management Protocol, a piece of IKE, to establish, arrange, alter, and erase Security Associations and cryptographic keys in a VPN climate." }, { "code": null, "e": 32340, "s": 32235, "text": "A straightforward checking for ISAKMP at the UDP port 500 can demonstrate the presence of a VPN passage." }, { "code": null, "e": 32563, "s": 32340, "text": "Hackers can research further utilizing an apparatus, for example, IKE-output to identify the delicate information including encryption and hashing calculation, authentication type, key conveyance calculation, and so forth." }, { "code": null, "e": 32599, "s": 32563, "text": "8. VoIP(Voice over IP) Enumeration:" }, { "code": null, "e": 32708, "s": 32599, "text": "VoIP uses the SIP (Session Initiation Protocol) protocol to enable voice and video calls over an IP network." }, { "code": null, "e": 32783, "s": 32708, "text": "SIP administration by and large uses UDP/TCP ports 2000, 2001, 5050, 5061." }, { "code": null, "e": 32915, "s": 32783, "text": "VoIP enumeration provides sensitive information such as VoIP gateway/servers, IP-PBX systems, client software, and user extensions." }, { "code": null, "e": 33096, "s": 32915, "text": "This information can be used to launch various VoIP attacks such as DoS, Session Hijacking, Caller ID spoofing, Eavesdropping, Spamming over Internet Telephony, VoIP phishing, etc." }, { "code": null, "e": 33116, "s": 33096, "text": "9. RPC Enumeration:" }, { "code": null, "e": 33220, "s": 33116, "text": "Remote Procedure Call permits customers and workers to impart in disseminated customer/worker programs." }, { "code": null, "e": 33331, "s": 33220, "text": "Counting RPC endpoints empower aggressors to recognize any weak administrations on these administration ports." }, { "code": null, "e": 33566, "s": 33331, "text": "In networks ensured by firewalls and other security establishments, this portmapper is regularly sifted. Along these lines, hackers filter high port reaches to recognize RPC administrations that are available to coordinate an assault." }, { "code": null, "e": 33599, "s": 33566, "text": "10. Unix/Linux User Enumeration:" }, { "code": null, "e": 33813, "s": 33599, "text": "One of the most vital steps for conducting an enumeration is to perform this kind of enumeration. This provides a list of users along with details like username, hostname, start date and time of each session, etc." }, { "code": null, "e": 33912, "s": 33813, "text": "We can use command-line utilities to perform Linux user enumeration like users, rwho, finger, etc." }, { "code": null, "e": 33933, "s": 33912, "text": "11. SMB Enumeration:" }, { "code": null, "e": 34105, "s": 33933, "text": "SMB list is significant expertise for any pen-tester. Prior to figuring out how to count SMB, we should initially realize what SMB is. SMB represents server message block." }, { "code": null, "e": 34323, "s": 34105, "text": "It’s a convention for sharing assets like records, printers, by and large, any asset which should be retrievable or made accessible by the server. It fundamentally runs on port 445 or port 139 relying upon the server." }, { "code": null, "e": 34619, "s": 34323, "text": "It is quite accessible in windows, so windows clients don’t have to arrange anything extra as such other than essential set up. In Linux in any case, it is somewhat extraordinary. To make it work for Linux, you have to introduce a samba server since Linux locally doesn’t utilize SMB convention." }, { "code": null, "e": 34808, "s": 34619, "text": "Clearly, some kind of confirmation will be set up like a username and secret word, and just certain assets made shareable. So dislike everybody can get to everything, a solid confirmation." }, { "code": null, "e": 35191, "s": 34808, "text": "The main evident defect is utilizing default certifications or effectively guessable and sometimes even no verification for access of significant assets of the server. Administrators should make a point to utilize solid passwords for clients who need to get to assets utilizing SMB. The subsequent blemish is the samba server. Samba servers are infamous for being hugely vulnerable." }, { "code": null, "e": 35309, "s": 35191, "text": "There are several countermeasures which can be taken into account for the mitigation of several kinds of enumeration:" }, { "code": null, "e": 35333, "s": 35309, "text": "1. NetBIOS Enumeration:" }, { "code": null, "e": 35358, "s": 35333, "text": "Disable SMB and NetBIOS." }, { "code": null, "e": 35382, "s": 35358, "text": "Use a network firewall." }, { "code": null, "e": 35427, "s": 35382, "text": "Prefer Windows firewall/ software firewalls." }, { "code": null, "e": 35444, "s": 35427, "text": "Disable sharing." }, { "code": null, "e": 35465, "s": 35444, "text": "2. SNMP Enumeration:" }, { "code": null, "e": 35527, "s": 35465, "text": "Eliminate the specialist or shut off the SNMP administration." }, { "code": null, "e": 35630, "s": 35527, "text": "In the event that stopping SNMP isn’t a choice, at that point change the default network string names." }, { "code": null, "e": 35686, "s": 35630, "text": "Move up to SNMP3, which encodes passwords and messages." }, { "code": null, "e": 35735, "s": 35686, "text": "Actualize the Group Policy security alternative." }, { "code": null, "e": 35756, "s": 35735, "text": "3. LDAP Enumeration:" }, { "code": null, "e": 35803, "s": 35756, "text": "Utilize SSL technology to encrypt the traffic." }, { "code": null, "e": 35891, "s": 35803, "text": "Select a username unique in relation to your email address and empower account lockout." }, { "code": null, "e": 35911, "s": 35891, "text": "4. NTP Enumeration:" }, { "code": null, "e": 35932, "s": 35911, "text": "Configure MD5 Layer." }, { "code": null, "e": 35962, "s": 35932, "text": "Configure NTP Authentication." }, { "code": null, "e": 35983, "s": 35962, "text": "Upgrade NTP version." }, { "code": null, "e": 36004, "s": 35983, "text": "5. SMTP Enumeration:" }, { "code": null, "e": 36049, "s": 36004, "text": "Ignore email messages to unknown recipients." }, { "code": null, "e": 36077, "s": 36049, "text": "Disable open relay feature." }, { "code": null, "e": 36181, "s": 36077, "text": "Breaking point the number of acknowledged associations from a source to forestall brute force exploits." }, { "code": null, "e": 36263, "s": 36181, "text": "Not to include sensitive mail server and localhost information in mail responses." }, { "code": null, "e": 36303, "s": 36263, "text": "6. DNS Enumeration Using Zone Transfer:" }, { "code": null, "e": 36359, "s": 36303, "text": "Incapacitate the DNS Zone moves to the untrusted hosts." }, { "code": null, "e": 36477, "s": 36359, "text": "Make sure that the private hosts and their IP addresses are not published in DNS zone files of the public DNS server." }, { "code": null, "e": 36587, "s": 36477, "text": "Use premium DNS regulation services that hide sensitive information such as host information from the public." }, { "code": null, "e": 36724, "s": 36587, "text": "Utilize standard organization administrator contacts for DNS enlistment to maintain a strategic distance from social designing assaults." }, { "code": null, "e": 36792, "s": 36724, "text": "Avoid publishing Private IP address information into the zone file." }, { "code": null, "e": 36835, "s": 36792, "text": "Disable Zone Transfer for untrusted hosts." }, { "code": null, "e": 36881, "s": 36835, "text": "Hide Sensitive information from public hosts." }, { "code": null, "e": 36903, "s": 36881, "text": "7. IPsec Enumeration:" }, { "code": null, "e": 37200, "s": 36903, "text": "Preshared keys utilized with both fundamental and forceful mode IKE key trade components are available to sniffing and disconnected savage power granulating assaults to bargain the shared mystery. You should utilize advanced testaments or two-factor validation components to refute these dangers." }, { "code": null, "e": 37389, "s": 37200, "text": "Pre-shared keys and forceful mode IKE uphold is a catastrophe waiting to happen. On the off chance that you should uphold forceful mode IKE, utilize advanced declarations for verification." }, { "code": null, "e": 37646, "s": 37389, "text": "Forcefully firewall and channel traffic coursing through VPN encrypted tunnel so that, in case of a trade-off, network access is restricted. This point is particularly significant while giving versatile clients network access, instead of branch workplaces." }, { "code": null, "e": 37868, "s": 37646, "text": "Where conceivable, limit inbound IPsec security relationship to explicit IP addresses. This guarantees that regardless of whether an aggressor bargains a preshared key, she can only with significant effort access the VPN." }, { "code": null, "e": 37904, "s": 37868, "text": "8. VoIP(Voice over IP) Enumeration:" }, { "code": null, "e": 38054, "s": 37904, "text": "This hack can be smothered by actualizing SIPS (SIP over TLS) and confirming SIP queries and reactions (which can incorporate uprightness insurance)." }, { "code": null, "e": 38199, "s": 38054, "text": "The utilization of SIPS and the verification of reactions can stifle many related hacks including eavesdropping and message or client pantomime." }, { "code": null, "e": 38405, "s": 38199, "text": "The utilization of digest confirmation joined with the utilization of TLS between SIP telephones and SIP intermediaries can give a station through which clients can safely validate inside their SIP domain." }, { "code": null, "e": 38552, "s": 38405, "text": "Voicemail messages can be changed over to message records and parsed by ordinary spam channels. This can just shield clients from SPIT voicemails." }, { "code": null, "e": 38572, "s": 38552, "text": "9. RPC Enumeration:" }, { "code": null, "e": 38748, "s": 38572, "text": "Try not to run rexd, users, or rwalld RPC administrations, since they are of negligible utilization and give aggressors both valuable data and direct admittance to your hosts." }, { "code": null, "e": 39003, "s": 38748, "text": "In high-security conditions, don’t offer any RPC administrations to the public Internet. Because of the unpredictability of these administrations, almost certainly, zero-day misuse contents will be accessible to assailants before fixed data is delivered." }, { "code": null, "e": 39204, "s": 39003, "text": "To limit the danger of inner or confided in hacks against vital RPC administrations, (for example, NFS segments, including statd, lockd, and mountd), introduce the most recent seller security patches." }, { "code": null, "e": 39415, "s": 39204, "text": "Forcefully channel egress traffic, where conceivable, to guarantee that regardless of whether an assault against an RPC administration is effective, an associate back shell can’t be brought forth to the hacker." }, { "code": null, "e": 39448, "s": 39415, "text": "10. Unix/Linux User Enumeration:" }, { "code": null, "e": 39485, "s": 39448, "text": "Keep the kernel fixed and refreshed." }, { "code": null, "e": 39604, "s": 39485, "text": "Never run any service as root except if truly required, particularly the web, information base, and record mainframes." }, { "code": null, "e": 39687, "s": 39604, "text": "SUID digit ought not to be set to any program which lets you getaway to the shell." }, { "code": null, "e": 39851, "s": 39687, "text": "You should never set SUID cycle on any record supervisor/compiler/mediator as an aggressor can undoubtedly peruse/overwrite any documents present on the framework." }, { "code": null, "e": 39929, "s": 39851, "text": "Try not to give sudo rights to any program which lets you break to the shell." }, { "code": null, "e": 39950, "s": 39929, "text": "11. SMB Enumeration:" }, { "code": null, "e": 39999, "s": 39950, "text": "Impair SMB convention on Web and DNS mainframes." }, { "code": null, "e": 40053, "s": 39999, "text": "Debilitate SMB convention web confronting mainframes." }, { "code": null, "e": 40120, "s": 40053, "text": "Handicap ports TCP 139 and TCP 445 utilized by the SMB convention." }, { "code": null, "e": 40215, "s": 40120, "text": "Restrict anonymous access through the RestrictNull Access parameter from the Windows Registry." }, { "code": null, "e": 40225, "s": 40215, "text": "ruhelaa48" }, { "code": null, "e": 40234, "s": 40225, "text": "rkbhola5" }, { "code": null, "e": 40249, "s": 40234, "text": "Cyber-security" }, { "code": null, "e": 40275, "s": 40249, "text": "Advanced Computer Subject" }, { "code": null, "e": 40293, "s": 40275, "text": "Computer Networks" }, { "code": null, "e": 40311, "s": 40293, "text": "Computer Networks" }, { "code": null, "e": 40409, "s": 40311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40418, "s": 40409, "text": "Comments" }, { "code": null, "e": 40431, "s": 40418, "text": "Old Comments" }, { "code": null, "e": 40475, "s": 40431, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 40514, "s": 40475, "text": "ML | Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 40555, "s": 40514, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 40582, "s": 40555, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 40630, "s": 40582, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 40650, "s": 40630, "text": "Layers of OSI Model" }, { "code": null, "e": 40680, "s": 40650, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 40693, "s": 40680, "text": "TCP/IP Model" }, { "code": null, "e": 40731, "s": 40693, "text": "TCP Server-Client implementation in C" } ]
GATE | GATE-CS-2017 (Set 1) | Question 19 - GeeksforGeeks
28 Jun, 2021 Consider a database that has the relation schema EMP (EmpId, EmpName, and DeptName). An instance of the schema EMP and a SQL query on it are given below. The output of executing the SQL query is _______. Note: This questions appeared as Numerical Answer Type.(A) 1.2(B) 2.3(C) 2.6(D) 3.1Answer: (C)Explanation: Output of Query will be: DeptName Number AA 4 AB 3 AC 3 AD 2 AE 1 4 + 3 + 3 + 2 + 1 = 13 / 5 = 2.6 Therefore, option C is correctQuiz of this Question GATE-CS-2017 (Set 1) GATE-GATE-CS-2017 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE-IT-2004 | Question 83 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2007 | Question 17 GATE | GATE-IT-2004 | Question 12 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 64
[ { "code": null, "e": 24488, "s": 24460, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24642, "s": 24488, "text": "Consider a database that has the relation schema EMP (EmpId, EmpName, and DeptName). An instance of the schema EMP and a SQL query on it are given below." }, { "code": null, "e": 24692, "s": 24642, "text": "The output of executing the SQL query is _______." }, { "code": null, "e": 24824, "s": 24692, "text": "Note: This questions appeared as Numerical Answer Type.(A) 1.2(B) 2.3(C) 2.6(D) 3.1Answer: (C)Explanation: Output of Query will be:" }, { "code": null, "e": 24971, "s": 24824, "text": "\nDeptName Number\n\nAA 4\n\nAB 3\n\nAC 3\n\nAD 2\n\nAE 1\n\n4 + 3 + 3 + 2 + 1 = 13 / 5 = 2.6\n\n" }, { "code": null, "e": 25023, "s": 24971, "text": "Therefore, option C is correctQuiz of this Question" }, { "code": null, "e": 25044, "s": 25023, "text": "GATE-CS-2017 (Set 1)" }, { "code": null, "e": 25070, "s": 25044, "text": "GATE-GATE-CS-2017 (Set 1)" }, { "code": null, "e": 25075, "s": 25070, "text": "GATE" }, { "code": null, "e": 25173, "s": 25075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25182, "s": 25173, "text": "Comments" }, { "code": null, "e": 25195, "s": 25182, "text": "Old Comments" }, { "code": null, "e": 25237, "s": 25195, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25271, "s": 25237, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25305, "s": 25271, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25347, "s": 25305, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25389, "s": 25347, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25431, "s": 25389, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 25465, "s": 25431, "text": "GATE | GATE-CS-2007 | Question 17" }, { "code": null, "e": 25499, "s": 25465, "text": "GATE | GATE-IT-2004 | Question 12" }, { "code": null, "e": 25541, "s": 25499, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" } ]
Why an interface doesn't have a constructor whereas an abstract class have a constructor in Java?
A Constructor is to initialize the non-static members of a particular class with respect to an object. An Interface in Java doesn't have a constructor because all data members in interfaces are public static final by default, they are constants (assign the values at the time of declaration). There are no data members in an interface to initialize them through the constructor. In order to call a method, we need an object, since the methods in the interface don’t have a body there is no need for calling the methods in an interface. Since we cannot call the methods in the interface, there is no need of creating an object for an interface and there is no need of having a constructor in it. interface Addition { int add(int i, int j); } public class Test implements Addition { public int add(int i, int j) { int k = i+j; return k; } public static void main(String args[]) { Test t = new Test(); System.out.println("k value is:" + t.add(10,20)); } } k value is:30 The purpose of the constructor in a class is used to initialize fields but not to build objects. When we try to create a new instance of an abstract superclass, the compiler will give an error. However, we can inherit an abstract class and make use of its constructor by setting its variables. abstract class Employee { public String empName; abstract double calcSalary(); Employee(String name) { this.empName = name; // Constructor of abstract class } } class Manager extends Employee { Manager(String name) { super(name); // setting the name in the constructor of subclass } double calcSalary() { return 50000; } } public class Test { public static void main(String args[]) { Employee e = new Manager("Adithya"); System.out.println("Manager Name is:" + e.empName); System.out.println("Salary is:" + e.calcSalary()); } } Manager Name is:Adithya Salary is:50000.0
[ { "code": null, "e": 1165, "s": 1062, "text": "A Constructor is to initialize the non-static members of a particular class with respect to an object." }, { "code": null, "e": 1355, "s": 1165, "text": "An Interface in Java doesn't have a constructor because all data members in interfaces are public static final by default, they are constants (assign the values at the time of declaration)." }, { "code": null, "e": 1441, "s": 1355, "text": "There are no data members in an interface to initialize them through the constructor." }, { "code": null, "e": 1598, "s": 1441, "text": "In order to call a method, we need an object, since the methods in the interface don’t have a body there is no need for calling the methods in an interface." }, { "code": null, "e": 1757, "s": 1598, "text": "Since we cannot call the methods in the interface, there is no need of creating an object for an interface and there is no need of having a constructor in it." }, { "code": null, "e": 2054, "s": 1757, "text": "interface Addition {\n int add(int i, int j);\n}\npublic class Test implements Addition {\n public int add(int i, int j) {\n int k = i+j;\n return k;\n }\n public static void main(String args[]) {\n Test t = new Test();\n System.out.println(\"k value is:\" + t.add(10,20));\n }\n}" }, { "code": null, "e": 2068, "s": 2054, "text": "k value is:30" }, { "code": null, "e": 2165, "s": 2068, "text": "The purpose of the constructor in a class is used to initialize fields but not to build objects." }, { "code": null, "e": 2262, "s": 2165, "text": "When we try to create a new instance of an abstract superclass, the compiler will give an error." }, { "code": null, "e": 2362, "s": 2262, "text": "However, we can inherit an abstract class and make use of its constructor by setting its variables." }, { "code": null, "e": 2958, "s": 2362, "text": "abstract class Employee {\n public String empName;\n abstract double calcSalary();\n Employee(String name) {\n this.empName = name; // Constructor of abstract class \n }\n}\nclass Manager extends Employee {\n Manager(String name) {\n super(name); // setting the name in the constructor of subclass\n }\n double calcSalary() {\n return 50000;\n }\n}\npublic class Test {\n public static void main(String args[]) {\n Employee e = new Manager(\"Adithya\");\n System.out.println(\"Manager Name is:\" + e.empName);\n System.out.println(\"Salary is:\" + e.calcSalary());\n }\n}" }, { "code": null, "e": 3000, "s": 2958, "text": "Manager Name is:Adithya\nSalary is:50000.0" } ]
Setting up LaTeX on your Atom Editor | by Jingles (Hong Jing) | Towards Data Science
In this tutorial, I will guide you through setting up a LaTeX editor on Atom, and here are some reasons and benefits for doing so: preview your work side by side as you save your work fast, generate previews in 3-seconds clicking on the preview will bring your cursor to the syntax’s location Dropbox and GitHub integration for backup and working with collaborators Free LaTeX is a document preparation system that is widely used in academia for publishing scientific documents. Authors use markup syntax to define the structure of a document, to stylise text, to insert images, to add citations and cross-references. Because there are so many publishers, each having their design standards. For example, 18pt Times Roman for the title, 12pt Times Italic for the name, and so on. The purpose of LaTeX is to let authors focus on the writing and not wasting time following publishers’ document design guidelines. Authors simply download publishers’ LaTeX template and start writing. If you’re new to TeX or just want to use LaTeX for a one-time project, the quickest way to get started is using online services like Papeeria, Overleaf, and LaTeX base. They offer the ability to edit, preview, and download your work in PDF format. Since there are online solutions, so why set up a LaTeX editor on your machine? Unless you are paying for their plans, the free tier has some limitations, let me list a few: Limited private documents [Papeeria], or no private document [Latex base]No GitHub integration [Overleaf], or only public repositories [Papeeria]No collaborators [Overleaf]Need to be online. Limited private documents [Papeeria], or no private document [Latex base] No GitHub integration [Overleaf], or only public repositories [Papeeria] No collaborators [Overleaf] Need to be online. Personally, I choose to set up LaTeX on my local so that my co-authors and I can work on the same LaTeX document and sync with private GitHub repositories. Secondly, unlike online services, generating a preview on a local machine is much quicker too. When I will hit Cmd+S, the preview will be generated in less than 3-seconds. In this section, I will guide you through setting up a LaTex editor on Atom on macOS. The setup consists of 4 parts: setup TeX distributions setup Atom install Latexmk install packages in Atom On OS X, download MacTeX. As of April 2020, the distribution is MacTeX-2020. You can choose to download the full package, which is 4GB. It contains all the files that most users need, and you don’t have to face the daunting task of searching for missing components. Highly recommended. If you don’t want to install the entire MacTeX distribution — which is pretty big, and if you are someone like me who prefers to select what gets installed, you can download BasicTeX, which is only 80MB. BasicTeX contains the TeX Live distribution that suffices the need to generate PDF from .tex files; it does not include GUI applications, Ghostscript, and other libraries. But this means that you have to search and download all the packages you may need. I will cover this later. MacTeX is for OS X. But if you are on Linux or Windows, download TeX Live. Atom is a beautiful text editor that is available on OS X, Windows, and Linux. It has a package manager that allows you to install thousands of open source packages that add new features and functionality to your editor. You can easily browse your project files on a single interface. You can split your interface into multiple panes to edit/reference code across files. Download and install Atom. Latexmk is needed to automate the process of generating a LaTeX document. Nothing to explain here, we need this to work. The installation is simple, from the Terminal, type: sudo tlmgr install latexmk This will prompt you for your password and install the latexmk package. These packages enable you to use Atom as a LaTeX editor. Compile. Latex package compiles LaTeX documents from within Atom. It will execute Latexmk to build your work. Preview PDF. PDF View package enables you to view PDF files in Atom. This allows you to preview your work side-by-side. Clicking on the preview will bring your cursor to the syntax’s location. Syntax highlighting. Language-LaTeX package does LaTeX syntax highlighting in Atom. It is particularly useful to help you check that your syntax has valid LaTeX grammar. At this point, you should have a working LaTeX editor on your Atom. I recommend a few changes to the configurations. Go to Atom -> Preferences -> Packages. Go to Settings of the latex package and: [check] Build on Save (or stick to default using the build shortcut) [uncheck] Open Result after Successful Build [uncheck] Open Result in Background Under Output Directory, type “build” In language-latex package: [check] Soft Wrap If you have download BasicTeX, chances are you have to download packages that publishers use in their templates. The easiest way is to Google search for the missing packages, or search Comprehensive TEX Archive Network (CTAN). For example, algorithmic is one of the commonly used packages, and we might see this in the document. \usepackage{algorithmic} To install packages, open the Terminal, type: sudo tlmgr install algorithms There you go! I hope you enjoy your LaTeX editor and love Atom even more. Want to thank all the open-source contributors for Atom, atom-latex, atom-pdf-view, language-latex.
[ { "code": null, "e": 303, "s": 172, "text": "In this tutorial, I will guide you through setting up a LaTeX editor on Atom, and here are some reasons and benefits for doing so:" }, { "code": null, "e": 356, "s": 303, "text": "preview your work side by side as you save your work" }, { "code": null, "e": 393, "s": 356, "text": "fast, generate previews in 3-seconds" }, { "code": null, "e": 465, "s": 393, "text": "clicking on the preview will bring your cursor to the syntax’s location" }, { "code": null, "e": 538, "s": 465, "text": "Dropbox and GitHub integration for backup and working with collaborators" }, { "code": null, "e": 543, "s": 538, "text": "Free" }, { "code": null, "e": 790, "s": 543, "text": "LaTeX is a document preparation system that is widely used in academia for publishing scientific documents. Authors use markup syntax to define the structure of a document, to stylise text, to insert images, to add citations and cross-references." }, { "code": null, "e": 1153, "s": 790, "text": "Because there are so many publishers, each having their design standards. For example, 18pt Times Roman for the title, 12pt Times Italic for the name, and so on. The purpose of LaTeX is to let authors focus on the writing and not wasting time following publishers’ document design guidelines. Authors simply download publishers’ LaTeX template and start writing." }, { "code": null, "e": 1401, "s": 1153, "text": "If you’re new to TeX or just want to use LaTeX for a one-time project, the quickest way to get started is using online services like Papeeria, Overleaf, and LaTeX base. They offer the ability to edit, preview, and download your work in PDF format." }, { "code": null, "e": 1481, "s": 1401, "text": "Since there are online solutions, so why set up a LaTeX editor on your machine?" }, { "code": null, "e": 1575, "s": 1481, "text": "Unless you are paying for their plans, the free tier has some limitations, let me list a few:" }, { "code": null, "e": 1766, "s": 1575, "text": "Limited private documents [Papeeria], or no private document [Latex base]No GitHub integration [Overleaf], or only public repositories [Papeeria]No collaborators [Overleaf]Need to be online." }, { "code": null, "e": 1840, "s": 1766, "text": "Limited private documents [Papeeria], or no private document [Latex base]" }, { "code": null, "e": 1913, "s": 1840, "text": "No GitHub integration [Overleaf], or only public repositories [Papeeria]" }, { "code": null, "e": 1941, "s": 1913, "text": "No collaborators [Overleaf]" }, { "code": null, "e": 1960, "s": 1941, "text": "Need to be online." }, { "code": null, "e": 2116, "s": 1960, "text": "Personally, I choose to set up LaTeX on my local so that my co-authors and I can work on the same LaTeX document and sync with private GitHub repositories." }, { "code": null, "e": 2288, "s": 2116, "text": "Secondly, unlike online services, generating a preview on a local machine is much quicker too. When I will hit Cmd+S, the preview will be generated in less than 3-seconds." }, { "code": null, "e": 2405, "s": 2288, "text": "In this section, I will guide you through setting up a LaTex editor on Atom on macOS. The setup consists of 4 parts:" }, { "code": null, "e": 2429, "s": 2405, "text": "setup TeX distributions" }, { "code": null, "e": 2440, "s": 2429, "text": "setup Atom" }, { "code": null, "e": 2456, "s": 2440, "text": "install Latexmk" }, { "code": null, "e": 2481, "s": 2456, "text": "install packages in Atom" }, { "code": null, "e": 2767, "s": 2481, "text": "On OS X, download MacTeX. As of April 2020, the distribution is MacTeX-2020. You can choose to download the full package, which is 4GB. It contains all the files that most users need, and you don’t have to face the daunting task of searching for missing components. Highly recommended." }, { "code": null, "e": 3251, "s": 2767, "text": "If you don’t want to install the entire MacTeX distribution — which is pretty big, and if you are someone like me who prefers to select what gets installed, you can download BasicTeX, which is only 80MB. BasicTeX contains the TeX Live distribution that suffices the need to generate PDF from .tex files; it does not include GUI applications, Ghostscript, and other libraries. But this means that you have to search and download all the packages you may need. I will cover this later." }, { "code": null, "e": 3326, "s": 3251, "text": "MacTeX is for OS X. But if you are on Linux or Windows, download TeX Live." }, { "code": null, "e": 3724, "s": 3326, "text": "Atom is a beautiful text editor that is available on OS X, Windows, and Linux. It has a package manager that allows you to install thousands of open source packages that add new features and functionality to your editor. You can easily browse your project files on a single interface. You can split your interface into multiple panes to edit/reference code across files. Download and install Atom." }, { "code": null, "e": 3898, "s": 3724, "text": "Latexmk is needed to automate the process of generating a LaTeX document. Nothing to explain here, we need this to work. The installation is simple, from the Terminal, type:" }, { "code": null, "e": 3925, "s": 3898, "text": "sudo tlmgr install latexmk" }, { "code": null, "e": 3997, "s": 3925, "text": "This will prompt you for your password and install the latexmk package." }, { "code": null, "e": 4054, "s": 3997, "text": "These packages enable you to use Atom as a LaTeX editor." }, { "code": null, "e": 4164, "s": 4054, "text": "Compile. Latex package compiles LaTeX documents from within Atom. It will execute Latexmk to build your work." }, { "code": null, "e": 4357, "s": 4164, "text": "Preview PDF. PDF View package enables you to view PDF files in Atom. This allows you to preview your work side-by-side. Clicking on the preview will bring your cursor to the syntax’s location." }, { "code": null, "e": 4527, "s": 4357, "text": "Syntax highlighting. Language-LaTeX package does LaTeX syntax highlighting in Atom. It is particularly useful to help you check that your syntax has valid LaTeX grammar." }, { "code": null, "e": 4724, "s": 4527, "text": "At this point, you should have a working LaTeX editor on your Atom. I recommend a few changes to the configurations. Go to Atom -> Preferences -> Packages. Go to Settings of the latex package and:" }, { "code": null, "e": 4793, "s": 4724, "text": "[check] Build on Save (or stick to default using the build shortcut)" }, { "code": null, "e": 4838, "s": 4793, "text": "[uncheck] Open Result after Successful Build" }, { "code": null, "e": 4874, "s": 4838, "text": "[uncheck] Open Result in Background" }, { "code": null, "e": 4911, "s": 4874, "text": "Under Output Directory, type “build”" }, { "code": null, "e": 4938, "s": 4911, "text": "In language-latex package:" }, { "code": null, "e": 4956, "s": 4938, "text": "[check] Soft Wrap" }, { "code": null, "e": 5183, "s": 4956, "text": "If you have download BasicTeX, chances are you have to download packages that publishers use in their templates. The easiest way is to Google search for the missing packages, or search Comprehensive TEX Archive Network (CTAN)." }, { "code": null, "e": 5285, "s": 5183, "text": "For example, algorithmic is one of the commonly used packages, and we might see this in the document." }, { "code": null, "e": 5310, "s": 5285, "text": "\\usepackage{algorithmic}" }, { "code": null, "e": 5356, "s": 5310, "text": "To install packages, open the Terminal, type:" }, { "code": null, "e": 5386, "s": 5356, "text": "sudo tlmgr install algorithms" } ]
Elasticsearch - API Conventions
Application Programming Interface (API) in web is a group of function calls or other programming instructions to access the software component in that particular web application. For example, Facebook API helps a developer to create applications by accessing data or other functionalities from Facebook; it can be date of birth or status update. Elasticsearch provides a REST API, which is accessed by JSON over HTTP. Elasticsearch uses some conventions which we shall discuss now. Most of the operations, mainly searching and other operations, in APIs are for one or more than one indices. This helps the user to search in multiple places or all the available data by just executing a query once. Many different notations are used to perform operations in multiple indices. We will discuss a few of them here in this chapter. POST /index1,index2,index3/_search { "query":{ "query_string":{ "query":"any_string" } } } JSON objects from index1, index2, index3 having any_string in it. POST /_all/_search { "query":{ "query_string":{ "query":"any_string" } } } JSON objects from all indices and having any_string in it. POST /school*/_search { "query":{ "query_string":{ "query":"CBSE" } } } JSON objects from all indices which start with school having CBSE in it. Alternatively, you can use the following code as well − POST /school*,-schools_gov /_search { "query":{ "query_string":{ "query":"CBSE" } } } JSON objects from all indices which start with “school” but not from schools_gov and having CBSE in it. There are also some URL query string parameters − ignore_unavailable − No error will occur or no operation will be stopped, if the one or more index(es) present in the URL does not exist. For example, schools index exists, but book_shops does not exist. POST /school*,book_shops/_search { "query":{ "query_string":{ "query":"CBSE" } } } { "error":{ "root_cause":[{ "type":"index_not_found_exception", "reason":"no such index", "resource.type":"index_or_alias", "resource.id":"book_shops", "index":"book_shops" }], "type":"index_not_found_exception", "reason":"no such index", "resource.type":"index_or_alias", "resource.id":"book_shops", "index":"book_shops" },"status":404 } Consider the following code − POST /school*,book_shops/_search?ignore_unavailable = true { "query":{ "query_string":{ "query":"CBSE" } } } JSON objects from all indices which start with school having CBSE in it. true value of this parameter will prevent error, if a URL with wildcard results in no indices. For example, there is no index that starts with schools_pri − POST /schools_pri*/_search?allow_no_indices = true { "query":{ "match_all":{} } } { "took":1,"timed_out": false, "_shards":{"total":0, "successful":0, "failed":0}, "hits":{"total":0, "max_score":0.0, "hits":[]} } This parameter decides whether the wildcards need to be expanded to open indices or closed indices or perform both. The value of this parameter can be open and closed or none and all. For example, close index schools − POST /schools/_close {"acknowledged":true} Consider the following code − POST /school*/_search?expand_wildcards = closed { "query":{ "match_all":{} } } { "error":{ "root_cause":[{ "type":"index_closed_exception", "reason":"closed", "index":"schools" }], "type":"index_closed_exception", "reason":"closed", "index":"schools" }, "status":403 } Elasticsearch offers a functionality to search indices according to date and time. We need to specify date and time in a specific format. For example, accountdetail-2015.12.30, index will store the bank account details of 30th December 2015. Mathematical operations can be performed to get details for a particular date or a range of date and time. Format for date math index name − <static_name{date_math_expr{date_format|time_zone}}> /<accountdetail-{now-2d{YYYY.MM.dd|utc}}>/_search static_name is a part of expression which remains the same in every date math index like account detail. date_math_expr contains the mathematical expression that determines the date and time dynamically like now-2d. date_format contains the format in which the date is written in index like YYYY.MM.dd. If today’s date is 30th December 2015, then <accountdetail-{now-2d{YYYY.MM.dd}}> will return accountdetail-2015.12.28. We will now see some of the common options available in Elasticsearch that can be used to get the response in a specified format. We can get response in a well-formatted JSON object by just appending a URL query parameter, i.e., pretty = true. POST /schools/_search?pretty = true { "query":{ "match_all":{} } } .......................... { "_index" : "schools", "_type" : "school", "_id" : "1", "_score" : 1.0, "_source":{ "name":"Central School", "description":"CBSE Affiliation", "street":"Nagan", "city":"paprola", "state":"HP", "zip":"176115", "location": [31.8955385, 76.8380405], "fees":2000, "tags":["Senior Secondary", "beautiful campus"], "rating":"3.5" } } ...................... This option can change the statistical responses either into human readable form (If human = true) or computer readable form (if human = false). For example, if human = true then distance_kilometer = 20KM and if human = false then distance_meter = 20000, when response needs to be used by another computer program. We can filter the response to less fields by adding them in the field_path parameter. For example, POST /schools/_search?filter_path = hits.total { "query":{ "match_all":{} } } {"hits":{"total":3}} 14 Lectures 5 hours Manuj Aggarwal 20 Lectures 1 hours Faizan Tayyab Print Add Notes Bookmark this page
[ { "code": null, "e": 2927, "s": 2581, "text": "Application Programming Interface (API) in web is a group of function calls or other programming instructions to access the software component in that particular web application. For example, Facebook API helps a developer to create applications by accessing data or other functionalities from Facebook; it can be date of birth or status update." }, { "code": null, "e": 3063, "s": 2927, "text": "Elasticsearch provides a REST API, which is accessed by JSON over HTTP. Elasticsearch uses some conventions which we shall discuss now." }, { "code": null, "e": 3408, "s": 3063, "text": "Most of the operations, mainly searching and other operations, in APIs are for one or more than one indices. This helps the user to search in multiple places or all the available data by just executing a query once. Many different notations are used to perform operations in multiple indices. We will discuss a few of them here in this chapter." }, { "code": null, "e": 3444, "s": 3408, "text": "POST /index1,index2,index3/_search\n" }, { "code": null, "e": 3528, "s": 3444, "text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"any_string\"\n }\n }\n}\n" }, { "code": null, "e": 3594, "s": 3528, "text": "JSON objects from index1, index2, index3 having any_string in it." }, { "code": null, "e": 3614, "s": 3594, "text": "POST /_all/_search\n" }, { "code": null, "e": 3698, "s": 3614, "text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"any_string\"\n }\n }\n}\n" }, { "code": null, "e": 3757, "s": 3698, "text": "JSON objects from all indices and having any_string in it." }, { "code": null, "e": 3780, "s": 3757, "text": "POST /school*/_search\n" }, { "code": null, "e": 3858, "s": 3780, "text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n" }, { "code": null, "e": 3931, "s": 3858, "text": "JSON objects from all indices which start with school having CBSE in it." }, { "code": null, "e": 3987, "s": 3931, "text": "Alternatively, you can use the following code as well −" }, { "code": null, "e": 4024, "s": 3987, "text": "POST /school*,-schools_gov /_search\n" }, { "code": null, "e": 4102, "s": 4024, "text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n" }, { "code": null, "e": 4206, "s": 4102, "text": "JSON objects from all indices which start with “school” but not from schools_gov and having CBSE in it." }, { "code": null, "e": 4256, "s": 4206, "text": "There are also some URL query string parameters −" }, { "code": null, "e": 4460, "s": 4256, "text": "ignore_unavailable − No error will occur or no operation will be stopped, if the one or more index(es) present in the URL does not exist. For example, schools index exists, but book_shops does not exist." }, { "code": null, "e": 4494, "s": 4460, "text": "POST /school*,book_shops/_search\n" }, { "code": null, "e": 4572, "s": 4494, "text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n" }, { "code": null, "e": 4975, "s": 4572, "text": "{\n \"error\":{\n \"root_cause\":[{\n \"type\":\"index_not_found_exception\", \"reason\":\"no such index\",\n \"resource.type\":\"index_or_alias\", \"resource.id\":\"book_shops\",\n \"index\":\"book_shops\"\n }],\n \"type\":\"index_not_found_exception\", \"reason\":\"no such index\",\n \"resource.type\":\"index_or_alias\", \"resource.id\":\"book_shops\",\n \"index\":\"book_shops\"\n },\"status\":404\n}\n" }, { "code": null, "e": 5005, "s": 4975, "text": "Consider the following code −" }, { "code": null, "e": 5065, "s": 5005, "text": "POST /school*,book_shops/_search?ignore_unavailable = true\n" }, { "code": null, "e": 5143, "s": 5065, "text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n" }, { "code": null, "e": 5216, "s": 5143, "text": "JSON objects from all indices which start with school having CBSE in it." }, { "code": null, "e": 5373, "s": 5216, "text": "true value of this parameter will prevent error, if a URL with wildcard results in no indices. For example, there is no index that starts with schools_pri −" }, { "code": null, "e": 5425, "s": 5373, "text": "POST /schools_pri*/_search?allow_no_indices = true\n" }, { "code": null, "e": 5469, "s": 5425, "text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n" }, { "code": null, "e": 5607, "s": 5469, "text": "{\n \"took\":1,\"timed_out\": false, \"_shards\":{\"total\":0, \"successful\":0, \"failed\":0},\n \"hits\":{\"total\":0, \"max_score\":0.0, \"hits\":[]}\n}\n" }, { "code": null, "e": 5791, "s": 5607, "text": "This parameter decides whether the wildcards need to be expanded to open indices or closed indices or perform both. The value of this parameter can be open and closed or none and all." }, { "code": null, "e": 5826, "s": 5791, "text": "For example, close index schools −" }, { "code": null, "e": 5848, "s": 5826, "text": "POST /schools/_close\n" }, { "code": null, "e": 5871, "s": 5848, "text": "{\"acknowledged\":true}\n" }, { "code": null, "e": 5901, "s": 5871, "text": "Consider the following code −" }, { "code": null, "e": 5950, "s": 5901, "text": "POST /school*/_search?expand_wildcards = closed\n" }, { "code": null, "e": 5994, "s": 5950, "text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n" }, { "code": null, "e": 6218, "s": 5994, "text": "{\n \"error\":{\n \"root_cause\":[{\n \"type\":\"index_closed_exception\", \"reason\":\"closed\", \"index\":\"schools\"\n }],\n \"type\":\"index_closed_exception\", \"reason\":\"closed\", \"index\":\"schools\"\n }, \"status\":403\n}\n" }, { "code": null, "e": 6567, "s": 6218, "text": "Elasticsearch offers a functionality to search indices according to date and time. We need to specify date and time in a specific format. For example, accountdetail-2015.12.30, index will store the bank account details of 30th December 2015. Mathematical operations can be performed to get details for a particular date or a range of date and time." }, { "code": null, "e": 6601, "s": 6567, "text": "Format for date math index name −" }, { "code": null, "e": 6705, "s": 6601, "text": "<static_name{date_math_expr{date_format|time_zone}}>\n/<accountdetail-{now-2d{YYYY.MM.dd|utc}}>/_search\n" }, { "code": null, "e": 7127, "s": 6705, "text": "static_name is a part of expression which remains the same in every date math index like account detail. date_math_expr contains the mathematical expression that determines the date and time dynamically like now-2d. date_format contains the format in which the date is written in index like YYYY.MM.dd. If today’s date is 30th December 2015, then <accountdetail-{now-2d{YYYY.MM.dd}}> will return accountdetail-2015.12.28." }, { "code": null, "e": 7257, "s": 7127, "text": "We will now see some of the common options available in Elasticsearch that can be used to get the response in a specified format." }, { "code": null, "e": 7371, "s": 7257, "text": "We can get response in a well-formatted JSON object by just appending a URL query parameter, i.e., pretty = true." }, { "code": null, "e": 7408, "s": 7371, "text": "POST /schools/_search?pretty = true\n" }, { "code": null, "e": 7452, "s": 7408, "text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n" }, { "code": null, "e": 7865, "s": 7452, "text": "..........................\n{\n \"_index\" : \"schools\", \"_type\" : \"school\", \"_id\" : \"1\", \"_score\" : 1.0,\n \"_source\":{\n \"name\":\"Central School\", \"description\":\"CBSE Affiliation\",\n \"street\":\"Nagan\", \"city\":\"paprola\", \"state\":\"HP\", \"zip\":\"176115\",\n \"location\": [31.8955385, 76.8380405], \"fees\":2000,\n \"tags\":[\"Senior Secondary\", \"beautiful campus\"], \"rating\":\"3.5\"\n }\n}\n......................\n" }, { "code": null, "e": 8180, "s": 7865, "text": "This option can change the statistical responses either into human readable form (If human = true) or computer readable form (if human = false). For example, if human = true then distance_kilometer = 20KM and if human = false then distance_meter = 20000, when response needs to be used by another computer program." }, { "code": null, "e": 8279, "s": 8180, "text": "We can filter the response to less fields by adding them in the field_path parameter. For example," }, { "code": null, "e": 8327, "s": 8279, "text": "POST /schools/_search?filter_path = hits.total\n" }, { "code": null, "e": 8371, "s": 8327, "text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n" }, { "code": null, "e": 8393, "s": 8371, "text": "{\"hits\":{\"total\":3}}\n" }, { "code": null, "e": 8426, "s": 8393, "text": "\n 14 Lectures \n 5 hours \n" }, { "code": null, "e": 8442, "s": 8426, "text": " Manuj Aggarwal" }, { "code": null, "e": 8475, "s": 8442, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 8490, "s": 8475, "text": " Faizan Tayyab" }, { "code": null, "e": 8497, "s": 8490, "text": " Print" }, { "code": null, "e": 8508, "s": 8497, "text": " Add Notes" } ]
Kali Linux - Forensics Tools
In this chapter, we will learn about the forensics tools available in Kali Linux. p0f is a tool that can identify the operating system of a target host simply by examining captured packets even when the device in question is behind a packet firewall. P0f does not generate any additional network traffic, direct or indirect; no name lookups; no mysterious probes; no ARIN queries; nothing. In the hands of advanced users, P0f can detect firewall presence, NAT use, and existence of load balancers. Type “p0f – h” in the terminal to see how to use it and you will get the following results. It will list even the available interfaces. Then, type the following command: “p0f –i eth0 –p -o filename”. Where the parameter "-i" is the interface name as shown above. "-p" means it is in promiscuous mode. "-o" means the output will be saved in a file. Open a webpage with the address 192.168.1.2 From the results, you can observe that the Webserver is using apache 2.x and the OS is Debian. pdf-parser is a tool that parses a PDF document to identify the fundamental elements used in the analyzed pdf file. It will not render a PDF document. It is not recommended for text book case for PDF parsers, however it gets the job done. Generally, this is used for pdf files that you suspect has a script embedded in it. The command is − pdf-parser -o 10 filepath where "-o" is the number of objects. As you can see in the following screenshot, the pdf file opens a CMD command. Dumpzilla application is developed in Python 3.x and has as a purpose to extract all forensic interesting information of Firefox, Iceweasel, and Seamonkey browsers to be analyzed. It copies data from one file or block device (hard disc, cdrom, etc.) to another, trying to rescue the good parts first in case of read errors. The basic operation of ddrescue is fully automatic. That is, you don't have to wait for an error, stop the program, restart it from a new position, etc. If you use the mapfile feature of ddrescue, the data is rescued very efficiently (only the needed blocks are read). Also, you can interrupt the rescue at any time and resume it later at the same point. The mapfile is an essential part of ddrescue's effectiveness. Use it unless you know what you are doing. The command line is − dd_rescue infilepath outfilepath Parameter "–v" means verbose. "/dev/sdb" is the folder to be rescued. The img file is the recovered image. It is another forensic tool used to recover the files. It has a GUI too. To open it, type “dff-gui” in the terminal and the following web GUI will open. Click File → “Open Evidence”. The following table will open. Check “Raw format” and click “+” to select the folder that you want to recover. Then, you can browse the files on the left of the pane to see what has been recovered. 84 Lectures 6.5 hours Mohamad Mahjoub 8 Lectures 1 hours Corey Charles 21 Lectures 4 hours Atul Tiwari 55 Lectures 3 hours Musab Zayadneh 29 Lectures 2 hours Musab Zayadneh 32 Lectures 4 hours Adnaan Arbaaz Ahmed Print Add Notes Bookmark this page
[ { "code": null, "e": 2111, "s": 2029, "text": "In this chapter, we will learn about the forensics tools available in Kali Linux." }, { "code": null, "e": 2527, "s": 2111, "text": "p0f is a tool that can identify the operating system of a target host simply by examining captured packets even when the device in question is behind a packet firewall. P0f does not generate any additional network traffic, direct or indirect; no name lookups; no mysterious probes; no ARIN queries; nothing. In the hands of advanced users, P0f can detect firewall presence, NAT use, and existence of load balancers." }, { "code": null, "e": 2619, "s": 2527, "text": "Type “p0f – h” in the terminal to see how to use it and you will get the following results." }, { "code": null, "e": 2663, "s": 2619, "text": "It will list even the available interfaces." }, { "code": null, "e": 2727, "s": 2663, "text": "Then, type the following command: “p0f –i eth0 –p -o filename”." }, { "code": null, "e": 2875, "s": 2727, "text": "Where the parameter \"-i\" is the interface name as shown above. \"-p\" means it is in promiscuous mode. \"-o\" means the output will be saved in a file." }, { "code": null, "e": 2919, "s": 2875, "text": "Open a webpage with the address 192.168.1.2" }, { "code": null, "e": 3014, "s": 2919, "text": "From the results, you can observe that the Webserver is using apache 2.x and the OS is Debian." }, { "code": null, "e": 3337, "s": 3014, "text": "pdf-parser is a tool that parses a PDF document to identify the fundamental elements used in the analyzed pdf file. It will not render a PDF document. It is not recommended for text book case for PDF parsers, however it gets the job done. Generally, this is used for pdf files that you suspect has a script embedded in it." }, { "code": null, "e": 3354, "s": 3337, "text": "The command is −" }, { "code": null, "e": 3382, "s": 3354, "text": "pdf-parser -o 10 filepath\n" }, { "code": null, "e": 3419, "s": 3382, "text": "where \"-o\" is the number of objects." }, { "code": null, "e": 3497, "s": 3419, "text": "As you can see in the following screenshot, the pdf file opens a CMD command." }, { "code": null, "e": 3677, "s": 3497, "text": "Dumpzilla application is developed in Python 3.x and has as a purpose to extract all forensic interesting information of Firefox, Iceweasel, and Seamonkey browsers to be analyzed." }, { "code": null, "e": 3821, "s": 3677, "text": "It copies data from one file or block device (hard disc, cdrom, etc.) to another, trying to rescue the good parts first in case of read errors." }, { "code": null, "e": 3974, "s": 3821, "text": "The basic operation of ddrescue is fully automatic. That is, you don't have to wait for an error, stop the program, restart it from a new position, etc." }, { "code": null, "e": 4281, "s": 3974, "text": "If you use the mapfile feature of ddrescue, the data is rescued very efficiently (only the needed blocks are read). Also, you can interrupt the rescue at any time and resume it later at the same point. The mapfile is an essential part of ddrescue's effectiveness. Use it unless you know what you are doing." }, { "code": null, "e": 4303, "s": 4281, "text": "The command line is −" }, { "code": null, "e": 4338, "s": 4303, "text": "dd_rescue infilepath outfilepath\n" }, { "code": null, "e": 4445, "s": 4338, "text": "Parameter \"–v\" means verbose. \"/dev/sdb\" is the folder to be rescued. The img file is the recovered image." }, { "code": null, "e": 4598, "s": 4445, "text": "It is another forensic tool used to recover the files. It has a GUI too. To open it, type “dff-gui” in the terminal and the following web GUI will open." }, { "code": null, "e": 4628, "s": 4598, "text": "Click File → “Open Evidence”." }, { "code": null, "e": 4739, "s": 4628, "text": "The following table will open. Check “Raw format” and click “+” to select the folder that you want to recover." }, { "code": null, "e": 4826, "s": 4739, "text": "Then, you can browse the files on the left of the pane to see what has been recovered." }, { "code": null, "e": 4861, "s": 4826, "text": "\n 84 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4878, "s": 4861, "text": " Mohamad Mahjoub" }, { "code": null, "e": 4910, "s": 4878, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 4925, "s": 4910, "text": " Corey Charles" }, { "code": null, "e": 4958, "s": 4925, "text": "\n 21 Lectures \n 4 hours \n" }, { "code": null, "e": 4971, "s": 4958, "text": " Atul Tiwari" }, { "code": null, "e": 5004, "s": 4971, "text": "\n 55 Lectures \n 3 hours \n" }, { "code": null, "e": 5020, "s": 5004, "text": " Musab Zayadneh" }, { "code": null, "e": 5053, "s": 5020, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 5069, "s": 5053, "text": " Musab Zayadneh" }, { "code": null, "e": 5102, "s": 5069, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 5123, "s": 5102, "text": " Adnaan Arbaaz Ahmed" }, { "code": null, "e": 5130, "s": 5123, "text": " Print" }, { "code": null, "e": 5141, "s": 5130, "text": " Add Notes" } ]
PyQt - QGridLayout Class
A GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell. Optionally, a spanning factor for row as well as column, if specified makes the widget wider or taller than one cell. Two overloads of addWidget() method are as follows − addWidget(QWidget, int r, int c) Adds a widget at specified row and column addWidget(QWidget, int r, int c, int rowspan, int columnspan) Adds a widget at specified row and column and having specified width and/or height A child layout object can also be added at any cell in the grid. addLayout(QLayout, int r, int c) Adds a layout object at specified row and column The following code creates a grid layout of 16 push buttons arranged in a grid layout of 4 rows and 4 columns. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * def window(): app = QApplication(sys.argv) win = QWidget() grid = QGridLayout() for i in range(1,5): for j in range(1,5): grid.addWidget(QPushButton("B"+str(i)+str(j)),i,j) win.setLayout(grid) win.setGeometry(100,100,200,100) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) if __name__ == '__main__': window() The code uses two nested for loops for row and column numbers, denoted by variables i and j. They are converted to string to concatenate the caption of each push button to be added at ith row and jth column. The above code produces the following output − 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2304, "s": 1926, "text": "A GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell. Optionally, a spanning factor for row as well as column, if specified makes the widget wider or taller than one cell. Two overloads of addWidget() method are as follows −" }, { "code": null, "e": 2337, "s": 2304, "text": "addWidget(QWidget, int r, int c)" }, { "code": null, "e": 2379, "s": 2337, "text": "Adds a widget at specified row and column" }, { "code": null, "e": 2441, "s": 2379, "text": "addWidget(QWidget, int r, int c, int rowspan, int columnspan)" }, { "code": null, "e": 2524, "s": 2441, "text": "Adds a widget at specified row and column and having specified width and/or height" }, { "code": null, "e": 2589, "s": 2524, "text": "A child layout object can also be added at any cell in the grid." }, { "code": null, "e": 2622, "s": 2589, "text": "addLayout(QLayout, int r, int c)" }, { "code": null, "e": 2671, "s": 2622, "text": "Adds a layout object at specified row and column" }, { "code": null, "e": 2782, "s": 2671, "text": "The following code creates a grid layout of 16 push buttons arranged in a grid layout of 4 rows and 4 columns." }, { "code": null, "e": 3221, "s": 2782, "text": "import sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\ndef window():\n app = QApplication(sys.argv)\n win = QWidget()\n grid = QGridLayout()\n\t\n for i in range(1,5):\n for j in range(1,5):\n grid.addWidget(QPushButton(\"B\"+str(i)+str(j)),i,j)\n\t\t\t\n win.setLayout(grid)\n win.setGeometry(100,100,200,100)\n win.setWindowTitle(\"PyQt\")\n win.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 3429, "s": 3221, "text": "The code uses two nested for loops for row and column numbers, denoted by variables i and j. They are converted to string to concatenate the caption of each push button to be added at ith row and jth column." }, { "code": null, "e": 3476, "s": 3429, "text": "The above code produces the following output −" }, { "code": null, "e": 3513, "s": 3476, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 3523, "s": 3513, "text": " ALAA EID" }, { "code": null, "e": 3530, "s": 3523, "text": " Print" }, { "code": null, "e": 3541, "s": 3530, "text": " Add Notes" } ]
Comparing Machine Learning Models: Statistical vs. Practical Significance | by Dina Jankovic | Towards Data Science
A lot of work has been done on building and tuning ML models, but a natural question that eventually comes up after all that hard work is — how do we actually compare the models we’ve built? If we’re facing a choice between models A and B, which one is the winner and why? Could the models be combined together so that optimal performance is achieved? A very shallow approach would be to compare the overall accuracy on the test set, say, model A’s accuracy is 94% vs. model B’s accuracy is 95%, and blindly conclude that B won the race. In fact, there is so much more than the overall accuracy to investigate and more facts to consider. In this blog post, I’d love to share my recent findings on model comparison. I like using simple language when explaining statistics, so this post is a good read for those who are not so strong in statistics, but would love to learn a little more. If possible, it’s a really good idea to come up with some plots that can tell you right away what’s actually going on. It seems odd to do any plotting at this point, but plots can provide you with some insights that numbers just can’t. In one of my projects, my goal was to compare the accuracy of 2 ML models on the same test set when predicting user’s tax on their documents, so I thought it’d be a good idea to aggregate the data by user’s id and compute the proportion of correctly predicted taxes for each model. The data set I had was big (100K+ instances), so I broke down the analysis by region and focused on smaller subsets of data — the accuracy may differ from subset to subset. This is generally a good idea when dealing with ridiculously large data sets, simply because it is impossible to digest a huge amount of data at once, let alone come up with reliable conclusions (more about the sample size issue later). A huge advantage of a Big Data set is that not only you have an insane amount of information available, but you can also zoom in the data and explore what’s going on on a certain subset of pixels. At this point, I was suspicious that one of the models is doing better on some subsets, while they’re doing pretty much the same job on other subsets of data. This is a huge step forward from just comparing the overall accuracy. But this suspicion could be further investigated with hypothesis testing. Hypothesis tests can spot differences better than human eye — we have a limited amount of data in the test set, and we may be wondering how is the accuracy going to change if we compare the models on a different test set. Sadly, it’s not always possible to come up with a different test set, so knowing some statistics may be helpful to investigate the nature of model accuracies. It seems trivial at the first sight, and you’ve probably seen this before: Set up H0 and H1Come up with a test-statistic, and assume Normal distribution out of the blueSomehow calculate the p-valueIf p < alpha = 0.05 reject H0, and ta-dam you’re all done! Set up H0 and H1 Come up with a test-statistic, and assume Normal distribution out of the blue Somehow calculate the p-value If p < alpha = 0.05 reject H0, and ta-dam you’re all done! In practice, hypothesis testing is a little more complicated and sensitive. Sadly, people use it without much caution and misinterpret the results. Let’s do it together step by step! Step 1. We set up H0: the null hypothesis = no statistically significant difference between the 2 models and H1: the alternative hypothesis = there is a statistically significant difference between the accuracy of the 2 models — up to you: model A != B (two-tailed) or model A < or > model B (one-tailed) Step 2. We come up with a test-statistic in such a way as to quantify, within the observed data, behaviours that would distinguish the null from the alternative hypothesis. There are many options, and even the best statisticians could be clueless about an X number of statistical tests — and that’s totally fine! There are way too many assumptions and facts to consider, so once you know your data, you can pick the right one. The point is to understand how hypothesis testing works, and the actual test-statistic is just a tool that is easy to calculate with a software. Beware that there is a bunch of assumptions that need to be met before applying any statistical test. For each test, you can look up the required assumptions; however, the vast majority of real life data is not going to strictly meet all conditions, so feel free to relax them a little bit! But what if your data, for example, seriously deviates from Normal distribution? There are 2 big families of statistical tests: parametric and non-parametric tests, and I highly recommend reading a little more about them here. I’ll keep it short: the major difference between the two is the fact that parametric tests require certain assumptions about the population distribution, while non-parametric tests are a bit more robust (no parameters, please!). In my analysis, I initially wanted to use the paired samples t-test, but my data was clearly not normally distributed, so I went for the Wilcoxon signed rank test (non-parametric equivalent of the paired samples t-test). It’s up to you to decide which test-statistic you’re going to use in your analysis, but always make sure the assumptions are met. Step 3. Now the p-value. The concept of p-value is sort of abstract, and I bet many of you have used p-values before, but let’s clarify what a p-value actually is: a p-value is just a number that measures the evidence against H0: the stronger the evidence against H0, the smaller the p-value is. If your p-value is small enough, you have enough credit to reject H0. Luckily, the p-value can be easily found in R/Python so you don’t need to torture yourself and do it manually, and although I’ve been mostly using Python, I prefer doing hypothesis testing in R since there are more options available. Below is a code snippet. We see that on subset 2, we indeed obtained a small p-value, but the confidence interval is useless. > wilcox.test(data1, data2, conf.int = TRUE, alternative="greater", paired=TRUE, conf.level = .95, exact = FALSE)V = 1061.5, p-value = 0.008576alternative hypothesis: true location shift is less than 095 percent confidence interval:-Inf -0.008297017sample estimates:(pseudo)median-0.02717335 Step 4. Very straightforward: if p-value < pre-specified alpha (0.05, traditionally), you can reject H0 in favour of H1. Otherwise, there is not enough evidence to reject H0, which does not mean that H0 is true! In fact, it may still be false, but there was simply not enough evidence to reject it, based on the data. If alpha is 0.05 = 5%, that means there is only a 5% risk of concluding a difference exists when it actually doesn’t (aka type 1 error). You may be asking yourself: so why can’t we go for alpha = 1% instead of 5%? It’s because the analysis is going to be more conservative, so it is going to be harder to reject H0 (and we’re aiming to reject it). The most commonly used alphas are 5%, 10% and 1%, but you can pick any alpha you’d like! It really depends on how much risk you’re willing to take. Can alpha be 0% (i.e. no chance of type 1 error)? Nope :) In reality, there’s always a chance you’ll commit an error, so it doesn’t really make sense to pick 0%. It’s always good to leave some room for errors. If you wanna play around and p-hack, you may increase your alpha and reject H0, but then you have to settle for a lower level of confidence (as alpha increases, confidence level goes down — you can’t have it all :) ). If you get a ridiculously small p-value, that certainly means that there is a statistically significant difference between the accuracy of the 2 models. Previously, I indeed got a small p-value, so mathematically speaking, the models differ for sure, but being “significant” does not imply being important. Does that difference actually mean anything? Is that small difference relevant to the business problem? Statistical significance refers to the unlikelihood that mean differences observed in the sample have occurred due to sampling error. Given a large enough sample, despite seemingly insignificant population differences, one might still find statistical significance. On the other side, practical significance looks at whether the difference is large enough to be of value in a practical sense. While statistical significance is strictly defined, practical significance is more intuitive and subjective. At this point, you may have realized that p-values are not super powerful as you may think. There’s more to investigate. It’d be great to consider the effect size as well. The effect size measures the magnitude of the difference — if there is a statistically significant difference, we may be interested in its magnitude. Effect size emphasizes the size of the difference rather than confounding it with sample size. > abs(qnorm(p-value))/sqrt(n)0.14# the effect size is small What is considered a small, medium, large effect size? The traditional cut-offs are 0.1, 0.3, 0.5 respectively, but again, this really depends on your business problem. And what’s the issue with the sample size? Well, if your sample is too small, then your results are not going to be reliable, but that’s trivial. What if your sample size is too large? This seems awesome — but in that case even the ridiculously small differences could be detected with a hypothesis test. There’s so much data that even the tiny deviations could be perceived as significant. That’s why the effect size becomes useful . There’s more to do — we could try to find the power or the test and the optimal sample size. But we’re good for now. Hypothesis testing could be really useful in model comparison if it’s done right. Setting up H0 & H1, calculating the test-statistic and finding the p-value is routine work, but interpreting the results require some intuition, creativity and deeper understanding of the business problem. Remember that if the testing is based on a very large test set, relationships found to be statistically significant may not have much practical significance. Don’t just blindly trust those magical p-values: zooming in the data and conducting a post-hoc analysis is always a good idea! :) Feel free to reach out to me via email or LinkedIn, I’m always up for a chat about Data Science!
[ { "code": null, "e": 523, "s": 171, "text": "A lot of work has been done on building and tuning ML models, but a natural question that eventually comes up after all that hard work is — how do we actually compare the models we’ve built? If we’re facing a choice between models A and B, which one is the winner and why? Could the models be combined together so that optimal performance is achieved?" }, { "code": null, "e": 809, "s": 523, "text": "A very shallow approach would be to compare the overall accuracy on the test set, say, model A’s accuracy is 94% vs. model B’s accuracy is 95%, and blindly conclude that B won the race. In fact, there is so much more than the overall accuracy to investigate and more facts to consider." }, { "code": null, "e": 1057, "s": 809, "text": "In this blog post, I’d love to share my recent findings on model comparison. I like using simple language when explaining statistics, so this post is a good read for those who are not so strong in statistics, but would love to learn a little more." }, { "code": null, "e": 1293, "s": 1057, "text": "If possible, it’s a really good idea to come up with some plots that can tell you right away what’s actually going on. It seems odd to do any plotting at this point, but plots can provide you with some insights that numbers just can’t." }, { "code": null, "e": 1575, "s": 1293, "text": "In one of my projects, my goal was to compare the accuracy of 2 ML models on the same test set when predicting user’s tax on their documents, so I thought it’d be a good idea to aggregate the data by user’s id and compute the proportion of correctly predicted taxes for each model." }, { "code": null, "e": 2182, "s": 1575, "text": "The data set I had was big (100K+ instances), so I broke down the analysis by region and focused on smaller subsets of data — the accuracy may differ from subset to subset. This is generally a good idea when dealing with ridiculously large data sets, simply because it is impossible to digest a huge amount of data at once, let alone come up with reliable conclusions (more about the sample size issue later). A huge advantage of a Big Data set is that not only you have an insane amount of information available, but you can also zoom in the data and explore what’s going on on a certain subset of pixels." }, { "code": null, "e": 2866, "s": 2182, "text": "At this point, I was suspicious that one of the models is doing better on some subsets, while they’re doing pretty much the same job on other subsets of data. This is a huge step forward from just comparing the overall accuracy. But this suspicion could be further investigated with hypothesis testing. Hypothesis tests can spot differences better than human eye — we have a limited amount of data in the test set, and we may be wondering how is the accuracy going to change if we compare the models on a different test set. Sadly, it’s not always possible to come up with a different test set, so knowing some statistics may be helpful to investigate the nature of model accuracies." }, { "code": null, "e": 2941, "s": 2866, "text": "It seems trivial at the first sight, and you’ve probably seen this before:" }, { "code": null, "e": 3122, "s": 2941, "text": "Set up H0 and H1Come up with a test-statistic, and assume Normal distribution out of the blueSomehow calculate the p-valueIf p < alpha = 0.05 reject H0, and ta-dam you’re all done!" }, { "code": null, "e": 3139, "s": 3122, "text": "Set up H0 and H1" }, { "code": null, "e": 3217, "s": 3139, "text": "Come up with a test-statistic, and assume Normal distribution out of the blue" }, { "code": null, "e": 3247, "s": 3217, "text": "Somehow calculate the p-value" }, { "code": null, "e": 3306, "s": 3247, "text": "If p < alpha = 0.05 reject H0, and ta-dam you’re all done!" }, { "code": null, "e": 3489, "s": 3306, "text": "In practice, hypothesis testing is a little more complicated and sensitive. Sadly, people use it without much caution and misinterpret the results. Let’s do it together step by step!" }, { "code": null, "e": 3794, "s": 3489, "text": "Step 1. We set up H0: the null hypothesis = no statistically significant difference between the 2 models and H1: the alternative hypothesis = there is a statistically significant difference between the accuracy of the 2 models — up to you: model A != B (two-tailed) or model A < or > model B (one-tailed)" }, { "code": null, "e": 4366, "s": 3794, "text": "Step 2. We come up with a test-statistic in such a way as to quantify, within the observed data, behaviours that would distinguish the null from the alternative hypothesis. There are many options, and even the best statisticians could be clueless about an X number of statistical tests — and that’s totally fine! There are way too many assumptions and facts to consider, so once you know your data, you can pick the right one. The point is to understand how hypothesis testing works, and the actual test-statistic is just a tool that is easy to calculate with a software." }, { "code": null, "e": 4738, "s": 4366, "text": "Beware that there is a bunch of assumptions that need to be met before applying any statistical test. For each test, you can look up the required assumptions; however, the vast majority of real life data is not going to strictly meet all conditions, so feel free to relax them a little bit! But what if your data, for example, seriously deviates from Normal distribution?" }, { "code": null, "e": 5113, "s": 4738, "text": "There are 2 big families of statistical tests: parametric and non-parametric tests, and I highly recommend reading a little more about them here. I’ll keep it short: the major difference between the two is the fact that parametric tests require certain assumptions about the population distribution, while non-parametric tests are a bit more robust (no parameters, please!)." }, { "code": null, "e": 5464, "s": 5113, "text": "In my analysis, I initially wanted to use the paired samples t-test, but my data was clearly not normally distributed, so I went for the Wilcoxon signed rank test (non-parametric equivalent of the paired samples t-test). It’s up to you to decide which test-statistic you’re going to use in your analysis, but always make sure the assumptions are met." }, { "code": null, "e": 5830, "s": 5464, "text": "Step 3. Now the p-value. The concept of p-value is sort of abstract, and I bet many of you have used p-values before, but let’s clarify what a p-value actually is: a p-value is just a number that measures the evidence against H0: the stronger the evidence against H0, the smaller the p-value is. If your p-value is small enough, you have enough credit to reject H0." }, { "code": null, "e": 6190, "s": 5830, "text": "Luckily, the p-value can be easily found in R/Python so you don’t need to torture yourself and do it manually, and although I’ve been mostly using Python, I prefer doing hypothesis testing in R since there are more options available. Below is a code snippet. We see that on subset 2, we indeed obtained a small p-value, but the confidence interval is useless." }, { "code": null, "e": 6482, "s": 6190, "text": "> wilcox.test(data1, data2, conf.int = TRUE, alternative=\"greater\", paired=TRUE, conf.level = .95, exact = FALSE)V = 1061.5, p-value = 0.008576alternative hypothesis: true location shift is less than 095 percent confidence interval:-Inf -0.008297017sample estimates:(pseudo)median-0.02717335" }, { "code": null, "e": 7148, "s": 6482, "text": "Step 4. Very straightforward: if p-value < pre-specified alpha (0.05, traditionally), you can reject H0 in favour of H1. Otherwise, there is not enough evidence to reject H0, which does not mean that H0 is true! In fact, it may still be false, but there was simply not enough evidence to reject it, based on the data. If alpha is 0.05 = 5%, that means there is only a 5% risk of concluding a difference exists when it actually doesn’t (aka type 1 error). You may be asking yourself: so why can’t we go for alpha = 1% instead of 5%? It’s because the analysis is going to be more conservative, so it is going to be harder to reject H0 (and we’re aiming to reject it)." }, { "code": null, "e": 7296, "s": 7148, "text": "The most commonly used alphas are 5%, 10% and 1%, but you can pick any alpha you’d like! It really depends on how much risk you’re willing to take." }, { "code": null, "e": 7506, "s": 7296, "text": "Can alpha be 0% (i.e. no chance of type 1 error)? Nope :) In reality, there’s always a chance you’ll commit an error, so it doesn’t really make sense to pick 0%. It’s always good to leave some room for errors." }, { "code": null, "e": 7724, "s": 7506, "text": "If you wanna play around and p-hack, you may increase your alpha and reject H0, but then you have to settle for a lower level of confidence (as alpha increases, confidence level goes down — you can’t have it all :) )." }, { "code": null, "e": 8135, "s": 7724, "text": "If you get a ridiculously small p-value, that certainly means that there is a statistically significant difference between the accuracy of the 2 models. Previously, I indeed got a small p-value, so mathematically speaking, the models differ for sure, but being “significant” does not imply being important. Does that difference actually mean anything? Is that small difference relevant to the business problem?" }, { "code": null, "e": 8637, "s": 8135, "text": "Statistical significance refers to the unlikelihood that mean differences observed in the sample have occurred due to sampling error. Given a large enough sample, despite seemingly insignificant population differences, one might still find statistical significance. On the other side, practical significance looks at whether the difference is large enough to be of value in a practical sense. While statistical significance is strictly defined, practical significance is more intuitive and subjective." }, { "code": null, "e": 9054, "s": 8637, "text": "At this point, you may have realized that p-values are not super powerful as you may think. There’s more to investigate. It’d be great to consider the effect size as well. The effect size measures the magnitude of the difference — if there is a statistically significant difference, we may be interested in its magnitude. Effect size emphasizes the size of the difference rather than confounding it with sample size." }, { "code": null, "e": 9114, "s": 9054, "text": "> abs(qnorm(p-value))/sqrt(n)0.14# the effect size is small" }, { "code": null, "e": 9283, "s": 9114, "text": "What is considered a small, medium, large effect size? The traditional cut-offs are 0.1, 0.3, 0.5 respectively, but again, this really depends on your business problem." }, { "code": null, "e": 9718, "s": 9283, "text": "And what’s the issue with the sample size? Well, if your sample is too small, then your results are not going to be reliable, but that’s trivial. What if your sample size is too large? This seems awesome — but in that case even the ridiculously small differences could be detected with a hypothesis test. There’s so much data that even the tiny deviations could be perceived as significant. That’s why the effect size becomes useful ." }, { "code": null, "e": 9835, "s": 9718, "text": "There’s more to do — we could try to find the power or the test and the optimal sample size. But we’re good for now." }, { "code": null, "e": 10411, "s": 9835, "text": "Hypothesis testing could be really useful in model comparison if it’s done right. Setting up H0 & H1, calculating the test-statistic and finding the p-value is routine work, but interpreting the results require some intuition, creativity and deeper understanding of the business problem. Remember that if the testing is based on a very large test set, relationships found to be statistically significant may not have much practical significance. Don’t just blindly trust those magical p-values: zooming in the data and conducting a post-hoc analysis is always a good idea! :)" } ]
Add elements to a Vector in Java
A dynamic array is implemented by a Vector. This means an array that can grow or reduce in size as required. Elements can be added at the end of the Vector using the java.util.Vector.add() method. This method has a single parameter i.e. the element to be added. It returns true if the element is added to the Vector as required and false otherwise. A program that demonstrates this is given as follows − Live Demo import java.util.Vector; public class Demo { public static void main(String args[]) { Vector vec = new Vector(5); vec.add(4); vec.add(1); vec.add(7); vec.add(3); vec.add(5); vec.add(9); vec.add(2); vec.add(8); vec.add(6); System.out.println("The Vector elements are: " + vec); } } The output of the above program is as follows − The Vector elements are: [4, 1, 7, 3, 5, 9, 2, 8, 6] Now let us understand the above program. The Vector is created. Then Vector.add() is used to add the elements to the Vector. Finally, the Vector elements are displayed. A code snippet which demonstrates this is as follows − Vector vec = new Vector(5); vec.add(4); vec.add(1); vec.add(7); vec.add(3); vec.add(5); vec.add(9); vec.add(2); vec.add(8); vec.add(6); System.out.println("The Vector elements are: " + vec);
[ { "code": null, "e": 1171, "s": 1062, "text": "A dynamic array is implemented by a Vector. This means an array that can grow or reduce in size as required." }, { "code": null, "e": 1411, "s": 1171, "text": "Elements can be added at the end of the Vector using the java.util.Vector.add() method. This method has a single parameter i.e. the element to be added. It returns true if the element is added to the Vector as required and false otherwise." }, { "code": null, "e": 1466, "s": 1411, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1477, "s": 1466, "text": " Live Demo" }, { "code": null, "e": 1830, "s": 1477, "text": "import java.util.Vector;\npublic class Demo {\n public static void main(String args[]) {\n Vector vec = new Vector(5);\n vec.add(4);\n vec.add(1);\n vec.add(7);\n vec.add(3);\n vec.add(5);\n vec.add(9);\n vec.add(2);\n vec.add(8);\n vec.add(6);\n System.out.println(\"The Vector elements are: \" + vec);\n }\n}" }, { "code": null, "e": 1878, "s": 1830, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1931, "s": 1878, "text": "The Vector elements are: [4, 1, 7, 3, 5, 9, 2, 8, 6]" }, { "code": null, "e": 1972, "s": 1931, "text": "Now let us understand the above program." }, { "code": null, "e": 2155, "s": 1972, "text": "The Vector is created. Then Vector.add() is used to add the elements to the Vector. Finally, the Vector elements are displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2346, "s": 2155, "text": "Vector vec = new Vector(5);\nvec.add(4);\nvec.add(1);\nvec.add(7);\nvec.add(3);\nvec.add(5);\nvec.add(9);\nvec.add(2);\nvec.add(8);\nvec.add(6);\nSystem.out.println(\"The Vector elements are: \" + vec);" } ]
State ProgressBar in Android
23 Feb, 2021 State Progress Bar is one of the main features that we see in many applications. We can get to see this feature in ticket booking apps, educational apps. This progress bar helps to tell the user the steps to be carried out for performing a task. In this article, we are going to see how to implement State Progress Bar in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Used in most of the service providing applications such as ticket booking, exam form filling, and many more. This State Progress Bar helps the user’s steps to be carried out for performing the task. Use in various exam form-filling applications. Attributes Description Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency of State Progress Bar library in build.gradle file Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section. implementation ‘com.kofigyan.stateprogressbar:stateprogressbar:1.0.0’ Now click on Sync now it will sync your all files in build.gradle(). Step 3: Create a new State Progress Bar in your activity_main.xml file Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns: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"> <!--Progress Bar created--> <com.kofigyan.stateprogressbar.StateProgressBar android:id="@+id/your_state_progress_bar_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" app:spb_animateToCurrentProgressState="true" app:spb_checkStateCompleted="true" app:spb_currentStateDescriptionColor="#0F9D58" app:spb_currentStateNumber="one" app:spb_maxStateNumber="four" app:spb_stateBackgroundColor="#BDBDBD" app:spb_stateDescriptionColor="#808080" app:spb_stateForegroundColor="#0F9D58" app:spb_stateNumberBackgroundColor="#808080" app:spb_stateNumberForegroundColor="#eeeeee" /> <!--Button to go on next step--> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="NEXT" /> </RelativeLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.kofigyan.stateprogressbar.StateProgressBar; public class MainActivity extends AppCompatActivity { // steps on state progress bar String[] descriptionData = {"Step One", "Step Two", "Step Three", "Step Four"}; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StateProgressBar stateProgressBar = (StateProgressBar) findViewById(R.id.your_state_progress_bar_id); stateProgressBar.setStateDescriptionData(descriptionData); // button given along with id button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (stateProgressBar.getCurrentStateNumber()) { case 1: stateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO); break; case 2: stateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE); break; case 3: stateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR); break; case 4: stateProgressBar.setAllStatesCompleted(true); break; } } }); }} Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below. Android-Bars Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Feb, 2021" }, { "code": null, "e": 524, "s": 28, "text": "State Progress Bar is one of the main features that we see in many applications. We can get to see this feature in ticket booking apps, educational apps. This progress bar helps to tell the user the steps to be carried out for performing a task. In this article, we are going to see how to implement State Progress Bar in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 633, "s": 524, "text": "Used in most of the service providing applications such as ticket booking, exam form filling, and many more." }, { "code": null, "e": 723, "s": 633, "text": "This State Progress Bar helps the user’s steps to be carried out for performing the task." }, { "code": null, "e": 770, "s": 723, "text": "Use in various exam form-filling applications." }, { "code": null, "e": 781, "s": 770, "text": "Attributes" }, { "code": null, "e": 793, "s": 781, "text": "Description" }, { "code": null, "e": 822, "s": 793, "text": "Step 1: Create a New Project" }, { "code": null, "e": 984, "s": 822, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1058, "s": 984, "text": "Step 2: Add dependency of State Progress Bar library in build.gradle file" }, { "code": null, "e": 1195, "s": 1058, "text": "Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section." }, { "code": null, "e": 1265, "s": 1195, "text": "implementation ‘com.kofigyan.stateprogressbar:stateprogressbar:1.0.0’" }, { "code": null, "e": 1334, "s": 1265, "text": "Now click on Sync now it will sync your all files in build.gradle()." }, { "code": null, "e": 1405, "s": 1334, "text": "Step 3: Create a new State Progress Bar in your activity_main.xml file" }, { "code": null, "e": 1526, "s": 1405, "text": "Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file." }, { "code": null, "e": 1530, "s": 1526, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Progress Bar created--> <com.kofigyan.stateprogressbar.StateProgressBar android:id=\"@+id/your_state_progress_bar_id\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" app:spb_animateToCurrentProgressState=\"true\" app:spb_checkStateCompleted=\"true\" app:spb_currentStateDescriptionColor=\"#0F9D58\" app:spb_currentStateNumber=\"one\" app:spb_maxStateNumber=\"four\" app:spb_stateBackgroundColor=\"#BDBDBD\" app:spb_stateDescriptionColor=\"#808080\" app:spb_stateForegroundColor=\"#0F9D58\" app:spb_stateNumberBackgroundColor=\"#808080\" app:spb_stateNumberForegroundColor=\"#eeeeee\" /> <!--Button to go on next step--> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:layout_centerHorizontal=\"true\" android:text=\"NEXT\" /> </RelativeLayout>", "e": 2921, "s": 1530, "text": null }, { "code": null, "e": 2969, "s": 2921, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 3159, "s": 2969, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3164, "s": 3159, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.kofigyan.stateprogressbar.StateProgressBar; public class MainActivity extends AppCompatActivity { // steps on state progress bar String[] descriptionData = {\"Step One\", \"Step Two\", \"Step Three\", \"Step Four\"}; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StateProgressBar stateProgressBar = (StateProgressBar) findViewById(R.id.your_state_progress_bar_id); stateProgressBar.setStateDescriptionData(descriptionData); // button given along with id button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (stateProgressBar.getCurrentStateNumber()) { case 1: stateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO); break; case 2: stateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE); break; case 3: stateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR); break; case 4: stateProgressBar.setAllStatesCompleted(true); break; } } }); }}", "e": 4807, "s": 3164, "text": null }, { "code": null, "e": 4938, "s": 4807, "text": "Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below." }, { "code": null, "e": 4951, "s": 4938, "text": "Android-Bars" }, { "code": null, "e": 4975, "s": 4951, "text": "Technical Scripter 2020" }, { "code": null, "e": 4983, "s": 4975, "text": "Android" }, { "code": null, "e": 4988, "s": 4983, "text": "Java" }, { "code": null, "e": 5007, "s": 4988, "text": "Technical Scripter" }, { "code": null, "e": 5012, "s": 5007, "text": "Java" }, { "code": null, "e": 5020, "s": 5012, "text": "Android" }, { "code": null, "e": 5118, "s": 5020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5150, "s": 5118, "text": "Android SDK and it's Components" }, { "code": null, "e": 5189, "s": 5150, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5231, "s": 5189, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 5282, "s": 5231, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 5305, "s": 5282, "text": "Flutter - Stack Widget" }, { "code": null, "e": 5320, "s": 5305, "text": "Arrays in Java" }, { "code": null, "e": 5364, "s": 5320, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5400, "s": 5364, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5451, "s": 5400, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Python | Numpy matrix.mean()
15 Apr, 2019 With the help of Numpy matrix.mean() method, we can get the mean value from given matrix. Syntax : matrix.mean() Return : Return mean value from given matrix Example #1 :In this example we can see that we are able to get the mean value from a given matrix with the help of method matrix.mean(). # import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.mean() methodgeeks = gfg.mean() print(geeks) 20.0 Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.mean() methodgeeks = gfg.mean() print(geeks) 5.0 Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2019" }, { "code": null, "e": 118, "s": 28, "text": "With the help of Numpy matrix.mean() method, we can get the mean value from given matrix." }, { "code": null, "e": 141, "s": 118, "text": "Syntax : matrix.mean()" }, { "code": null, "e": 186, "s": 141, "text": "Return : Return mean value from given matrix" }, { "code": null, "e": 323, "s": 186, "text": "Example #1 :In this example we can see that we are able to get the mean value from a given matrix with the help of method matrix.mean()." }, { "code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.mean() methodgeeks = gfg.mean() print(geeks)", "e": 523, "s": 323, "text": null }, { "code": null, "e": 529, "s": 523, "text": "20.0\n" }, { "code": null, "e": 542, "s": 529, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.mean() methodgeeks = gfg.mean() print(geeks)", "e": 757, "s": 542, "text": null }, { "code": null, "e": 762, "s": 757, "text": "5.0\n" }, { "code": null, "e": 791, "s": 762, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 804, "s": 791, "text": "Python-numpy" }, { "code": null, "e": 811, "s": 804, "text": "Python" } ]
Javascript Tutorial
JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform. Javascript is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning Javascript: Javascript is the most popular programming language in the world and that makes it a programmer’s great choice. Once you learnt Javascript, it helps you developing great front-end as well as back-end softwares using different Javascript based frameworks like jQuery, Node.JS etc. Javascript is the most popular programming language in the world and that makes it a programmer’s great choice. Once you learnt Javascript, it helps you developing great front-end as well as back-end softwares using different Javascript based frameworks like jQuery, Node.JS etc. Javascript is everywhere, it comes installed on every modern web browser and so to learn Javascript you really do not need any special environment setup. For example Chrome, Mozilla Firefox , Safari and every browser you know as of today, supports Javascript. Javascript is everywhere, it comes installed on every modern web browser and so to learn Javascript you really do not need any special environment setup. For example Chrome, Mozilla Firefox , Safari and every browser you know as of today, supports Javascript. Javascript helps you create really beautiful and crazy fast websites. You can develop your website with a console like look and feel and give your users the best Graphical User Experience. Javascript helps you create really beautiful and crazy fast websites. You can develop your website with a console like look and feel and give your users the best Graphical User Experience. JavaScript usage has now extended to mobile app development, desktop app development, and game development. This opens many opportunities for you as Javascript Programmer. JavaScript usage has now extended to mobile app development, desktop app development, and game development. This opens many opportunities for you as Javascript Programmer. Due to high demand, there is tons of job growth and high pay for those who know JavaScript. You can navigate over to different job sites to see what having JavaScript skills looks like in the job market. Due to high demand, there is tons of job growth and high pay for those who know JavaScript. You can navigate over to different job sites to see what having JavaScript skills looks like in the job market. Great thing about Javascript is that you will find tons of frameworks and Libraries already developed which can be used directly in your software development to reduce your time to market. Great thing about Javascript is that you will find tons of frameworks and Libraries already developed which can be used directly in your software development to reduce your time to market. There could be 1000s of good reasons to learn Javascript Programming. But one thing for sure, to learn any programming language, not only Javascript, you just need to code, and code and finally code until you become expert. Just to give you a little excitement about Javascript programming, I'm going to give you a small conventional Javascript Hello World program, You can try it using Demo link <html> <body> <script language = "javascript" type = "text/javascript"> <!-- document.write("Hello World!") //--> </script> </body> </html> There are many useful Javascript frameworks and libraries available: Angular Angular React React jQuery jQuery Vue.js Vue.js Ext.js Ext.js Ember.js Ember.js Meteor Meteor Mithril Mithril Node.js Node.js Polymer Polymer Aurelia Aurelia Backbone.js Backbone.js It is really impossible to give a complete list of all the available Javascript frameworks and libraries. The Javascript world is just too large and too much new is happening. As mentioned before, Javascript is one of the most widely used programming languages (Front-end as well as Back-end). It has it's presence in almost every area of software development. I'm going to list few of them here: Client side validation - This is really important to verify any user input before submitting it to the server and Javascript plays an important role in validting those inputs at front-end itself. Client side validation - This is really important to verify any user input before submitting it to the server and Javascript plays an important role in validting those inputs at front-end itself. Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps in adding and deleting any HTML tag very easily using javascript and modify your HTML to change its look and feel based on different devices and requirements. Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps in adding and deleting any HTML tag very easily using javascript and modify your HTML to change its look and feel based on different devices and requirements. User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give different types of notifications to your website visitors. User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give different types of notifications to your website visitors. Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data while you are doing some other processing. This really gives an amazing experience to your website visitors. Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data while you are doing some other processing. This really gives an amazing experience to your website visitors. Presentations - JavaScript also provides the facility of creating presentations which gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide presentations. Presentations - JavaScript also provides the facility of creating presentations which gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide presentations. Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and scalable network applications. This is an event based library which helps in developing very sophisticated server applications including Web Servers. Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and scalable network applications. This is an event based library which helps in developing very sophisticated server applications including Web Servers. This list goes on, there are various areas where millions of software developers are happily using Javascript to develop great websites and others softwares. This tutorial has been prepared for JavaScript beginners to help them understand the basic functionality of JavaScript to build dynamic web pages and web applications. For this Javascript tutorial, it is assumed that the reader have a prior knowledge of HTML coding. It would help if the reader had some prior exposure to object-oriented programming concepts and a general idea on creating online applications. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2740, "s": 2466, "text": "JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform." }, { "code": null, "e": 2963, "s": 2740, "text": "Javascript is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning Javascript:" }, { "code": null, "e": 3243, "s": 2963, "text": "Javascript is the most popular programming language in the world and that makes it a programmer’s great choice. Once you learnt Javascript, it helps you developing great front-end as well as back-end softwares using different Javascript based frameworks like jQuery, Node.JS etc." }, { "code": null, "e": 3523, "s": 3243, "text": "Javascript is the most popular programming language in the world and that makes it a programmer’s great choice. Once you learnt Javascript, it helps you developing great front-end as well as back-end softwares using different Javascript based frameworks like jQuery, Node.JS etc." }, { "code": null, "e": 3783, "s": 3523, "text": "Javascript is everywhere, it comes installed on every modern web browser and so to learn Javascript you really do not need any special environment setup. For example Chrome, Mozilla Firefox , Safari and every browser you know as of today, supports Javascript." }, { "code": null, "e": 4043, "s": 3783, "text": "Javascript is everywhere, it comes installed on every modern web browser and so to learn Javascript you really do not need any special environment setup. For example Chrome, Mozilla Firefox , Safari and every browser you know as of today, supports Javascript." }, { "code": null, "e": 4232, "s": 4043, "text": "Javascript helps you create really beautiful and crazy fast websites. You can develop your website with a console like look and feel and give your users the best Graphical User Experience." }, { "code": null, "e": 4421, "s": 4232, "text": "Javascript helps you create really beautiful and crazy fast websites. You can develop your website with a console like look and feel and give your users the best Graphical User Experience." }, { "code": null, "e": 4593, "s": 4421, "text": "JavaScript usage has now extended to mobile app development, desktop app development, and game development. This opens many opportunities for you as Javascript Programmer." }, { "code": null, "e": 4765, "s": 4593, "text": "JavaScript usage has now extended to mobile app development, desktop app development, and game development. This opens many opportunities for you as Javascript Programmer." }, { "code": null, "e": 4969, "s": 4765, "text": "Due to high demand, there is tons of job growth and high pay for those who know JavaScript. You can navigate over to different job sites to see what having JavaScript skills looks like in the job market." }, { "code": null, "e": 5173, "s": 4969, "text": "Due to high demand, there is tons of job growth and high pay for those who know JavaScript. You can navigate over to different job sites to see what having JavaScript skills looks like in the job market." }, { "code": null, "e": 5362, "s": 5173, "text": "Great thing about Javascript is that you will find tons of frameworks and Libraries already developed which can be used directly in your software development to reduce your time to market." }, { "code": null, "e": 5551, "s": 5362, "text": "Great thing about Javascript is that you will find tons of frameworks and Libraries already developed which can be used directly in your software development to reduce your time to market." }, { "code": null, "e": 5775, "s": 5551, "text": "There could be 1000s of good reasons to learn Javascript Programming. But one thing for sure, to learn any programming language, not only Javascript, you just need to code, and code and finally code until you become expert." }, { "code": null, "e": 5948, "s": 5775, "text": "Just to give you a little excitement about Javascript programming, I'm going to give you a small conventional Javascript Hello World program, You can try it using Demo link" }, { "code": null, "e": 6145, "s": 5948, "text": "<html>\n <body> \n <script language = \"javascript\" type = \"text/javascript\">\n <!--\n document.write(\"Hello World!\")\n //-->\n </script> \n </body>\n</html>" }, { "code": null, "e": 6214, "s": 6145, "text": "There are many useful Javascript frameworks and libraries available:" }, { "code": null, "e": 6222, "s": 6214, "text": "Angular" }, { "code": null, "e": 6230, "s": 6222, "text": "Angular" }, { "code": null, "e": 6236, "s": 6230, "text": "React" }, { "code": null, "e": 6242, "s": 6236, "text": "React" }, { "code": null, "e": 6249, "s": 6242, "text": "jQuery" }, { "code": null, "e": 6256, "s": 6249, "text": "jQuery" }, { "code": null, "e": 6263, "s": 6256, "text": "Vue.js" }, { "code": null, "e": 6270, "s": 6263, "text": "Vue.js" }, { "code": null, "e": 6277, "s": 6270, "text": "Ext.js" }, { "code": null, "e": 6284, "s": 6277, "text": "Ext.js" }, { "code": null, "e": 6293, "s": 6284, "text": "Ember.js" }, { "code": null, "e": 6302, "s": 6293, "text": "Ember.js" }, { "code": null, "e": 6309, "s": 6302, "text": "Meteor" }, { "code": null, "e": 6316, "s": 6309, "text": "Meteor" }, { "code": null, "e": 6324, "s": 6316, "text": "Mithril" }, { "code": null, "e": 6332, "s": 6324, "text": "Mithril" }, { "code": null, "e": 6340, "s": 6332, "text": "Node.js" }, { "code": null, "e": 6348, "s": 6340, "text": "Node.js" }, { "code": null, "e": 6356, "s": 6348, "text": "Polymer" }, { "code": null, "e": 6364, "s": 6356, "text": "Polymer" }, { "code": null, "e": 6372, "s": 6364, "text": "Aurelia" }, { "code": null, "e": 6380, "s": 6372, "text": "Aurelia" }, { "code": null, "e": 6392, "s": 6380, "text": "Backbone.js" }, { "code": null, "e": 6404, "s": 6392, "text": "Backbone.js" }, { "code": null, "e": 6580, "s": 6404, "text": "It is really impossible to give a complete list of all the available Javascript frameworks and libraries. The Javascript world is just too large and too much new is happening." }, { "code": null, "e": 6801, "s": 6580, "text": "As mentioned before, Javascript is one of the most widely used programming languages (Front-end as well as Back-end). It has it's presence in almost every area of software development. I'm going to list few of them here:" }, { "code": null, "e": 6997, "s": 6801, "text": "Client side validation - This is really important to verify any user input before submitting it to the server and Javascript plays an important role in validting those inputs at front-end itself." }, { "code": null, "e": 7193, "s": 6997, "text": "Client side validation - This is really important to verify any user input before submitting it to the server and Javascript plays an important role in validting those inputs at front-end itself." }, { "code": null, "e": 7444, "s": 7193, "text": "Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps in adding and deleting any HTML tag very easily using javascript and modify your HTML to change its look and feel based on different devices and requirements." }, { "code": null, "e": 7695, "s": 7444, "text": "Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps in adding and deleting any HTML tag very easily using javascript and modify your HTML to change its look and feel based on different devices and requirements." }, { "code": null, "e": 7847, "s": 7695, "text": "User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give different types of notifications to your website visitors." }, { "code": null, "e": 7999, "s": 7847, "text": "User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give different types of notifications to your website visitors." }, { "code": null, "e": 8202, "s": 7999, "text": "Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data while you are doing some other processing. This really gives an amazing experience to your website visitors." }, { "code": null, "e": 8405, "s": 8202, "text": "Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data while you are doing some other processing. This really gives an amazing experience to your website visitors." }, { "code": null, "e": 8615, "s": 8405, "text": "Presentations - JavaScript also provides the facility of creating presentations which gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide presentations." }, { "code": null, "e": 8825, "s": 8615, "text": "Presentations - JavaScript also provides the facility of creating presentations which gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide presentations." }, { "code": null, "e": 9067, "s": 8825, "text": "Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and scalable network applications. This is an event based library which helps in developing very sophisticated server applications including Web Servers." }, { "code": null, "e": 9309, "s": 9067, "text": "Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and scalable network applications. This is an event based library which helps in developing very sophisticated server applications including Web Servers." }, { "code": null, "e": 9467, "s": 9309, "text": "This list goes on, there are various areas where millions of software developers are happily using Javascript to develop great websites and others softwares." }, { "code": null, "e": 9635, "s": 9467, "text": "This tutorial has been prepared for JavaScript beginners to help them understand the basic functionality of JavaScript to build dynamic web pages and web applications." }, { "code": null, "e": 9878, "s": 9635, "text": "For this Javascript tutorial, it is assumed that the reader have a prior knowledge of HTML coding. It would help if the reader had some prior exposure to object-oriented programming concepts and a general idea on creating online applications." }, { "code": null, "e": 9913, "s": 9878, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9927, "s": 9913, "text": " Anadi Sharma" }, { "code": null, "e": 9961, "s": 9927, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 9975, "s": 9961, "text": " Lets Kode It" }, { "code": null, "e": 10010, "s": 9975, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10027, "s": 10010, "text": " Frahaan Hussain" }, { "code": null, "e": 10062, "s": 10027, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10079, "s": 10062, "text": " Frahaan Hussain" }, { "code": null, "e": 10112, "s": 10079, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 10140, "s": 10112, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10174, "s": 10140, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 10202, "s": 10174, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10209, "s": 10202, "text": " Print" }, { "code": null, "e": 10220, "s": 10209, "text": " Add Notes" } ]
MomentJS - Is Daylight Saving Time
This method returns true or false if the current moment falls in daylight saving time. moment().isDST(); var isdylight = moment().isDST(); If date is not given it will check for the current time. var isdylight = moment([2017, 2, 14]).isDST(); Print Add Notes Bookmark this page
[ { "code": null, "e": 2047, "s": 1960, "text": "This method returns true or false if the current moment falls in daylight saving time." }, { "code": null, "e": 2066, "s": 2047, "text": "moment().isDST();\n" }, { "code": null, "e": 2100, "s": 2066, "text": "var isdylight = moment().isDST();" }, { "code": null, "e": 2157, "s": 2100, "text": "If date is not given it will check for the current time." }, { "code": null, "e": 2204, "s": 2157, "text": "var isdylight = moment([2017, 2, 14]).isDST();" }, { "code": null, "e": 2211, "s": 2204, "text": " Print" }, { "code": null, "e": 2222, "s": 2211, "text": " Add Notes" } ]
Perl | Pass By Reference - GeeksforGeeks
12 Feb, 2019 When a variable is passed by reference function operates on original data in the function. Passing by reference allows the function to change the original value of a variable. When the values of the elements in the argument arrays @_ are changed, the values of the corresponding arguments will also change. This is what passing parameters by reference does. In the example given below, when we update the elements of an array @a in subroutine sample, it also changes the value of the parameters which will be reflected in the whole program. Hence when parameters are called by reference, changing their value in the function also changes their value in the main program. Example 1: #!/usr/bin/perl # Initialising an array 'a' @a = (0..10); # Array before subroutine callprint("Values of an array before function call: = @a\n"); # calling subroutine 'sample'sample(@a); # Array after subroutine callprint("Values of an array after function call: = @a"); # Subroutine to represent # Passing by Referencesub sample{ $_[0] = "A"; $_[1] = "B";} Output: Values of an array before function call: = 0 1 2 3 4 5 6 7 8 9 10 Values of an array after function call: = A B 2 3 4 5 6 7 8 9 10 Here is how the program works:- An array consisting of values from 0 to 10 is defined.Further, this array is passed to the ‘sample’ subroutine.A subroutine ‘sample’ is already defined. Inside this, the values of the first and second parameters are changed through the argument array @_.Values of the array @a are displayed after calling the subroutine. Now the first two values of the scalar are updated to A and B respectively. An array consisting of values from 0 to 10 is defined. Further, this array is passed to the ‘sample’ subroutine. A subroutine ‘sample’ is already defined. Inside this, the values of the first and second parameters are changed through the argument array @_. Values of the array @a are displayed after calling the subroutine. Now the first two values of the scalar are updated to A and B respectively. Example 2: #!/usr/bin/perl # Initializing values to scalar# variables x and ymy $x = 10;my $y = 20; # Values before subroutine callprint "Before calling subroutine x = $x, y = $y \n"; # Subroutine callsample($x, $y); # Values after subroutine callprint "After calling subroutine x = $x, y = $y "; # Subroutine sample sub sample{ $_[0] = 1; $_[1] = 2;} Output: Before calling subroutine x = 10, y = 20 After calling subroutine x = 1, y = 2 Perl-function Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | Polymorphism in OOPs Perl | Arrays Perl | Arrays (push, pop, shift, unshift) Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | Boolean Values Perl | length() Function Introduction to Perl Perl | sleep() Function Perl | join() Function
[ { "code": null, "e": 23921, "s": 23893, "text": "\n12 Feb, 2019" }, { "code": null, "e": 24097, "s": 23921, "text": "When a variable is passed by reference function operates on original data in the function. Passing by reference allows the function to change the original value of a variable." }, { "code": null, "e": 24279, "s": 24097, "text": "When the values of the elements in the argument arrays @_ are changed, the values of the corresponding arguments will also change. This is what passing parameters by reference does." }, { "code": null, "e": 24592, "s": 24279, "text": "In the example given below, when we update the elements of an array @a in subroutine sample, it also changes the value of the parameters which will be reflected in the whole program. Hence when parameters are called by reference, changing their value in the function also changes their value in the main program." }, { "code": null, "e": 24603, "s": 24592, "text": "Example 1:" }, { "code": "#!/usr/bin/perl # Initialising an array 'a' @a = (0..10); # Array before subroutine callprint(\"Values of an array before function call: = @a\\n\"); # calling subroutine 'sample'sample(@a); # Array after subroutine callprint(\"Values of an array after function call: = @a\"); # Subroutine to represent # Passing by Referencesub sample{ $_[0] = \"A\"; $_[1] = \"B\";}", "e": 24976, "s": 24603, "text": null }, { "code": null, "e": 24984, "s": 24976, "text": "Output:" }, { "code": null, "e": 25117, "s": 24984, "text": "Values of an array before function call: = 0 1 2 3 4 5 6 7 8 9 10\nValues of an array after function call: = A B 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 25149, "s": 25117, "text": "Here is how the program works:-" }, { "code": null, "e": 25546, "s": 25149, "text": "An array consisting of values from 0 to 10 is defined.Further, this array is passed to the ‘sample’ subroutine.A subroutine ‘sample’ is already defined. Inside this, the values of the first and second parameters are changed through the argument array @_.Values of the array @a are displayed after calling the subroutine. Now the first two values of the scalar are updated to A and B respectively." }, { "code": null, "e": 25601, "s": 25546, "text": "An array consisting of values from 0 to 10 is defined." }, { "code": null, "e": 25659, "s": 25601, "text": "Further, this array is passed to the ‘sample’ subroutine." }, { "code": null, "e": 25803, "s": 25659, "text": "A subroutine ‘sample’ is already defined. Inside this, the values of the first and second parameters are changed through the argument array @_." }, { "code": null, "e": 25946, "s": 25803, "text": "Values of the array @a are displayed after calling the subroutine. Now the first two values of the scalar are updated to A and B respectively." }, { "code": null, "e": 25957, "s": 25946, "text": "Example 2:" }, { "code": "#!/usr/bin/perl # Initializing values to scalar# variables x and ymy $x = 10;my $y = 20; # Values before subroutine callprint \"Before calling subroutine x = $x, y = $y \\n\"; # Subroutine callsample($x, $y); # Values after subroutine callprint \"After calling subroutine x = $x, y = $y \"; # Subroutine sample sub sample{ $_[0] = 1; $_[1] = 2;}", "e": 26310, "s": 25957, "text": null }, { "code": null, "e": 26318, "s": 26310, "text": "Output:" }, { "code": null, "e": 26400, "s": 26318, "text": "Before calling subroutine x = 10, y = 20 \nAfter calling subroutine x = 1, y = 2 \n" }, { "code": null, "e": 26414, "s": 26400, "text": "Perl-function" }, { "code": null, "e": 26421, "s": 26414, "text": "Picked" }, { "code": null, "e": 26426, "s": 26421, "text": "Perl" }, { "code": null, "e": 26431, "s": 26426, "text": "Perl" }, { "code": null, "e": 26529, "s": 26431, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26538, "s": 26529, "text": "Comments" }, { "code": null, "e": 26551, "s": 26538, "text": "Old Comments" }, { "code": null, "e": 26579, "s": 26551, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 26593, "s": 26579, "text": "Perl | Arrays" }, { "code": null, "e": 26635, "s": 26593, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 26676, "s": 26635, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 26709, "s": 26676, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 26731, "s": 26709, "text": "Perl | Boolean Values" }, { "code": null, "e": 26756, "s": 26731, "text": "Perl | length() Function" }, { "code": null, "e": 26777, "s": 26756, "text": "Introduction to Perl" }, { "code": null, "e": 26801, "s": 26777, "text": "Perl | sleep() Function" } ]
How to pass individual elements in an array as argument to function in C language?
If individual elements are to be passed as arguments, then array elements along with their subscripts must be given in function call. To receive the elements, simple variables are used in function definition. #include<stdio.h> main (){ void display (int, int); int a[5], i; clrscr(); printf (“enter 5 elements”); for (i=0; i<5; i++) scanf("%d", &a[i]); display (a [0], a[4]); //calling function with individual arguments getch( ); } void display (int a, int b){ //called function with individual arguments print f ("first element = %d",a); printf ("last element = %d",b); } Enter 5 elements 10 20 30 40 50 First element = 10 Last element = 50 Consider another example for passing individual elements as argument to a function. #include<stdio.h> main (){ void arguments(int,int); int a[10], i; printf ("enter 6 elements:\n"); for (i=0; i<6; i++) scanf("%d", &a[i]); arguments(a[0],a[5]); //calling function with individual arguments getch( ); } void arguments(int a, int b){ //called function with individual arguments printf ("first element = %d\n",a); printf ("last element = %d\n",b); } enter 6 elements: 1 2 3 4 5 6 first element = 1 last element = 6
[ { "code": null, "e": 1196, "s": 1062, "text": "If individual elements are to be passed as arguments, then array elements along with their subscripts must be given in function call." }, { "code": null, "e": 1271, "s": 1196, "text": "To receive the elements, simple variables are used in function definition." }, { "code": null, "e": 1669, "s": 1271, "text": "#include<stdio.h>\nmain (){\n void display (int, int);\n int a[5], i;\n clrscr();\n printf (“enter 5 elements”);\n for (i=0; i<5; i++)\n scanf(\"%d\", &a[i]);\n display (a [0], a[4]); //calling function with individual arguments\n getch( );\n}\nvoid display (int a, int b){ //called function with individual arguments\n print f (\"first element = %d\",a);\n printf (\"last element = %d\",b);\n}" }, { "code": null, "e": 1753, "s": 1669, "text": "Enter 5 elements\n 10 20 30 40 50\nFirst element = 10\nLast element = 50" }, { "code": null, "e": 1837, "s": 1753, "text": "Consider another example for passing individual elements as argument to a function." }, { "code": null, "e": 2229, "s": 1837, "text": "#include<stdio.h>\nmain (){\n void arguments(int,int);\n int a[10], i;\n printf (\"enter 6 elements:\\n\");\n for (i=0; i<6; i++)\n scanf(\"%d\", &a[i]);\n arguments(a[0],a[5]); //calling function with individual arguments\n getch( );\n}\nvoid arguments(int a, int b){ //called function with individual arguments\n printf (\"first element = %d\\n\",a);\n printf (\"last element = %d\\n\",b);\n}" }, { "code": null, "e": 2294, "s": 2229, "text": "enter 6 elements:\n1\n2\n3\n4\n5\n6\nfirst element = 1\nlast element = 6" } ]
Transformations of Stack, Melt, Pivot Table in pandas | by Han Qi | Towards Data Science
Full notebook at https://gist.github.com/gitgithan/0ba595e3ef9cf8fab7deeb7b8b533ba3Alternatively, click “view raw” at the bottom right of this scrollable frame and save the json as an .ipynb file from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" import pandas as pd #----------------Transformation pipelines-------------------- #1. df-->stack-->reset_index-->pivot-->df #2. df-->stack-->convert to dataframe-->pivot-->df #3. df-->melt-->add index-->pivot-->df df= pd.DataFrame([[0, 1], [2, 3]],index=['cat', 'dog'],columns=['weight', 'height']) print('{:*^80}'.format('dataframe')) df print('{:*^80}'.format('stacked dataframe')) df.stack() print('{:*^80}'.format('stacked dataframe with index in column')) df.stack().reset_index(level = 1) #AttributeError: 'Series' object has no attribute 'pivot_table' , so must convert to dataframe before pivot_table stacked = df.stack().reset_index(level = 1) print('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)')) recovered_df1 = df.stack().reset_index(level = 1).pivot_table(index = stacked.index, columns = 'level_1',values = 0) #pivot_table orders columns alphabetically,specifying values parameter prevents creation of useless multiindex column recovered_df1.columns.name = None #remove 'level_1' column.name recovered_df1 ***********************************dataframe************************************ *******************************stacked dataframe******************************** cat weight 0 height 1 dog weight 2 height 3 dtype: int64 *********************stacked dataframe with index in column********************* *****pivot_table recovered original dataframe (with extra name for columns)***** type(stacked_df.index.get_level_values(0)) pandas.core.indexes.base.Index print('{:*^80}'.format('dataframe')) df print('{:*^80}'.format('stack and convert to dataframe to expose pivot_table')) stacked_df = pd.DataFrame(df.stack()) stacked_df print('{:*^80}'.format('rather than unstack, pivot_table achieves the same')) idx_lvl0, idx_lvl1 = stacked_df.index.get_level_values(0), stacked_df.index.get_level_values(1) recovered_df2 = stacked_df.pivot_table(index=idx_lvl0,columns = idx_lvl1,values = 0) recovered_df2 ***********************************dataframe************************************ **************stack and convert to dataframe to expose pivot_table************** ***************rather than unstack, pivot_table achieves the same*************** print('{:*^80}'.format('dataframe')) df print('{:*^80}'.format('melting loses index information')) melted = df.melt() #melt appends columns into new "variable" column, while stack adds columns to new inner index layer (same information end up different places) melted print('{:*^80}'.format('manually enrich index')) # until this is solved: https://github.com/pandas-dev/pandas/issues/17440 melted.index = ['cat','dog']*2 #list(df.index)*len(df.columns) for more generalizable index generation melted print('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)')) recovered_df3 = melted.pivot_table(index = melted.index, columns = 'variable',values = 'value') recovered_df3.columns.name=None #remove 'variable' column.name recovered_df3 #melting loses index while pivot_table requires index parameter ***********************************dataframe************************************ ************************melting loses index information************************* *****************************manually enrich index****************************** *****pivot_table recovered original dataframe (with extra name for columns)***** In this article i will explore how dataframe.stack(), dataframe.melt(), dataframe.pivot_table from pandas data manipulation library of python interact with each other in a transformation pipeline to reshape dataframes and recover the original dataframe, along with numerous caveats along the way by following along the code. from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = “all”import pandas as pd By default, jupyter notebooks only display the last line of every cell. The first two lines make jupyter display the outputs of all variables as a convenience to avoid wrapping print() around every single variable I wish to see. Next, we import the pandas library where we call the dataframe reshaping functions from. df= pd.DataFrame([[0, 1], [2, 3]],index=['cat', 'dog'],columns=['weight', 'height'])print('{:*^80}'.format('dataframe'))dfprint('{:*^80}'.format('stacked dataframe'))df.stack() Here, we create the dataframe. Then df.stack() turns our single-level column df into a dataseries with a multi-index index by fitting the columns into a new inner index (index level 1) for each value in the old outer index (index level 0). The outer level looks like it has only 2 values [cat,dog], but it is only for neat display and is really 4 values [cat,cat,dog,dog]. Something useful to note from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.htmlif the columns have multiple levels, the new index level(s) is (are) taken from the prescribed level(s) and the output is a DataFrame. So it’s good to keep in mind whether the transformation output is a dataseries or dataframe. print('{:*^80}'.format('stacked dataframe with index in column'))df.stack().reset_index(level = 1) #AttributeError: 'Series' object has no attribute 'pivot_table' , so must convert to dataframe before pivot_tablestacked = df.stack().reset_index(level = 1) The values are aligned accordingly to the indexes, turning the dataframe from a wide format to a long format dataseries. Because pivot_table is a dataframe method and does not apply to dataseries, we can extract level 1 of the multi-index using reset_index(level = 1) to prepare for pivoting back. Specifying level = 0 would have extracted the outer index into a column. Note that ‘level_1’ is automatically added as a column name after reset_index(). This will be extra information that can be used or cleaned and ignored later. The 0 column above values is added automatically too. It does not matter if you extracted level 0 or level 1 at this stage. You can simply switch the inputs to index and columns parameters of pivot_table later to achieve the same output (barring the tiny df.columns.name difference) and recover the original dataframe. print('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)'))recovered_df1 = df.stack().reset_index(level = 1).pivot_table(index = stacked.index, columns = 'level_1',values = 0) #pivot_table orders columns alphabetically,specifying values parameter prevents creation of useless multiindex column recovered_df1.columns.name = None #remove 'level_1' column.namerecovered_df1 Finally, we specify index and columns parameters in pivot_table by selecting from the current column names to describe how the final pivoted dataframe should look like. The values parameter is optional, but not specifying it will add column names not yet specified in index or columns parameters to the outerlevel of current columns to create multi-indexed columns that look ugly and make data access unnecessarily difficult. print('{:*^80}'.format('dataframe'))dfprint('{:*^80}'.format('stack and convert to dataframe to expose pivot_table'))stacked_df = pd.DataFrame(df.stack())stacked_df Remember that pivot_table is a dataframe method and does not apply to dataseries, so rather than reset_index as in part1, we can directly construct a dataframe from the series using pd.DataFrame(df.stack()) to create a multi-indexed dataframe to make the pivot_table method available and work harder in specifying its parameters correctly. print('{:*^80}'.format('rather than unstack, pivot_table achieves the same'))idx_lvl0, idx_lvl1 = stacked_df.index.get_level_values(0), stacked_df.index.get_level_values(1)recovered_df2 = stacked_df.pivot_table(index=idx_lvl0,columns = idx_lvl1,values = 0)recovered_df2 index.get_level_values(0) is a way to get the index values of the specified muti-index level (in this case, 0) as a pandas.core.indexes.base.Index object which can be conveniently used by functions accepting sequences/lists. In part 2, we match the correct index information from each level into the index and columns parameters of pivot table to recover the original dataframe. Part 2 is cleaner than part 1 because there was no reset_index to create an extra ‘level_0’ or ‘level_1’ in df.columns.name that we set to None in part 1. print('{:*^80}'.format('dataframe'))dfprint('{:*^80}'.format('melting loses index information'))melted = df.melt() #melt appends columns into new "variable" column, while stack adds columns to new inner index layer (same information end up different places)melted Similar to stacking, melt turns wide format data to long format data by putting compressing columns into a single list. The difference is that stack inserted this list into the inner index, while melt inserts this list as a new column called ‘variable’ (can be renamed). print('{:*^80}'.format('manually enrich index')) # until this is solved: https://github.com/pandas-dev/pandas/issues/17440melted.index = ['cat','dog']*2 #list(df.index)*len(df.columns) for more generalizable index generationmelted Note that melt has made the cat dog information in the index disappear. This makes it impossible to recover the original dataframe. Until this issue (https://github.com/pandas-dev/pandas/issues/17440) is fixed, we have to manually add back the index. print('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)'))recovered_df3 = melted.pivot_table(index = melted.index, columns = 'variable',values = 'value')recovered_df3.columns.name=None #remove 'variable' column.namerecovered_df3 Finally, pivot_table with the right parameters will recover our original dataframe. Like in part 1, ‘variable’ is removed from df.columns.name for exact recovery. I hope these transformations have given beginners to these functions a better understanding of how flexible pandas is. The same information can be placed in Index or Columns using set_index and reset_index depending on where they serve the greatest purpose. For example, instead of df.loc[df.col == value] to filter when the information is in a column, setting col to the index, and doing df.loc[value] is much simpler. Whether information is in the index or column will also greatly affect how pd.merge, pd.concat, dataframe.join work on such dataseries/dataframes, but that would be another whole article by itself. Stack allows information from columns to swing to indexes and vice versa (with unstack()). Melt combines columns to a standard 3-column format of id_vars, variable, value to allow columnar processing of variable before pivoting back with edited column values. Pivot_table is the most powerful among the 3 with other parameters such as aggfunc (aggregation) that allows custom functions so possibilities there are limitless. Finally, here is a practical example that helped me a lot: http://pbpython.com/pandas-pivot-table-explained.html
[ { "code": null, "e": 368, "s": 172, "text": "Full notebook at https://gist.github.com/gitgithan/0ba595e3ef9cf8fab7deeb7b8b533ba3Alternatively, click “view raw” at the bottom right of this scrollable frame and save the json as an .ipynb file" }, { "code": null, "e": 692, "s": 368, "text": "from IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\nimport pandas as pd\n\n#----------------Transformation pipelines--------------------\n#1. df-->stack-->reset_index-->pivot-->df\n#2. df-->stack-->convert to dataframe-->pivot-->df\n#3. df-->melt-->add index-->pivot-->df\n" }, { "code": null, "e": 1553, "s": 692, "text": "df= pd.DataFrame([[0, 1], [2, 3]],index=['cat', 'dog'],columns=['weight', 'height'])\n\nprint('{:*^80}'.format('dataframe'))\ndf\n\nprint('{:*^80}'.format('stacked dataframe'))\ndf.stack()\n\nprint('{:*^80}'.format('stacked dataframe with index in column'))\ndf.stack().reset_index(level = 1) #AttributeError: 'Series' object has no attribute 'pivot_table' , so must convert to dataframe before pivot_table\nstacked = df.stack().reset_index(level = 1) \n\nprint('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)'))\nrecovered_df1 = df.stack().reset_index(level = 1).pivot_table(index = stacked.index, columns = 'level_1',values = 0) #pivot_table orders columns alphabetically,specifying values parameter prevents creation of useless multiindex column \nrecovered_df1.columns.name = None #remove 'level_1' column.name\nrecovered_df1\n" }, { "code": null, "e": 1635, "s": 1553, "text": "***********************************dataframe************************************\n" }, { "code": null, "e": 1717, "s": 1635, "text": "*******************************stacked dataframe********************************\n" }, { "code": null, "e": 1798, "s": 1717, "text": "cat weight 0\n height 1\ndog weight 2\n height 3\ndtype: int64" }, { "code": null, "e": 1880, "s": 1798, "text": "*********************stacked dataframe with index in column*********************\n" }, { "code": null, "e": 1962, "s": 1880, "text": "*****pivot_table recovered original dataframe (with extra name for columns)*****\n" }, { "code": null, "e": 2006, "s": 1962, "text": "type(stacked_df.index.get_level_values(0))\n" }, { "code": null, "e": 2037, "s": 2006, "text": "pandas.core.indexes.base.Index" }, { "code": null, "e": 2481, "s": 2037, "text": "print('{:*^80}'.format('dataframe'))\ndf\nprint('{:*^80}'.format('stack and convert to dataframe to expose pivot_table'))\nstacked_df = pd.DataFrame(df.stack())\nstacked_df\n\nprint('{:*^80}'.format('rather than unstack, pivot_table achieves the same'))\nidx_lvl0, idx_lvl1 = stacked_df.index.get_level_values(0), stacked_df.index.get_level_values(1)\nrecovered_df2 = stacked_df.pivot_table(index=idx_lvl0,columns = idx_lvl1,values = 0)\nrecovered_df2\n" }, { "code": null, "e": 2563, "s": 2481, "text": "***********************************dataframe************************************\n" }, { "code": null, "e": 2645, "s": 2563, "text": "**************stack and convert to dataframe to expose pivot_table**************\n" }, { "code": null, "e": 2727, "s": 2645, "text": "***************rather than unstack, pivot_table achieves the same***************\n" }, { "code": null, "e": 3599, "s": 2727, "text": "print('{:*^80}'.format('dataframe'))\ndf\nprint('{:*^80}'.format('melting loses index information'))\nmelted = df.melt() #melt appends columns into new \"variable\" column, while stack adds columns to new inner index layer (same information end up different places)\nmelted\n\nprint('{:*^80}'.format('manually enrich index')) # until this is solved: https://github.com/pandas-dev/pandas/issues/17440\nmelted.index = ['cat','dog']*2 #list(df.index)*len(df.columns) for more generalizable index generation\nmelted \n\nprint('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)'))\nrecovered_df3 = melted.pivot_table(index = melted.index, columns = 'variable',values = 'value')\nrecovered_df3.columns.name=None #remove 'variable' column.name\nrecovered_df3\n\n#melting loses index while pivot_table requires index parameter\n" }, { "code": null, "e": 3681, "s": 3599, "text": "***********************************dataframe************************************\n" }, { "code": null, "e": 3763, "s": 3681, "text": "************************melting loses index information*************************\n" }, { "code": null, "e": 3845, "s": 3763, "text": "*****************************manually enrich index******************************\n" }, { "code": null, "e": 3927, "s": 3845, "text": "*****pivot_table recovered original dataframe (with extra name for columns)*****\n" }, { "code": null, "e": 4258, "s": 3933, "text": "In this article i will explore how dataframe.stack(), dataframe.melt(), dataframe.pivot_table from pandas data manipulation library of python interact with each other in a transformation pipeline to reshape dataframes and recover the original dataframe, along with numerous caveats along the way by following along the code." }, { "code": null, "e": 4383, "s": 4258, "text": "from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = “all”import pandas as pd" }, { "code": null, "e": 4701, "s": 4383, "text": "By default, jupyter notebooks only display the last line of every cell. The first two lines make jupyter display the outputs of all variables as a convenience to avoid wrapping print() around every single variable I wish to see. Next, we import the pandas library where we call the dataframe reshaping functions from." }, { "code": null, "e": 4878, "s": 4701, "text": "df= pd.DataFrame([[0, 1], [2, 3]],index=['cat', 'dog'],columns=['weight', 'height'])print('{:*^80}'.format('dataframe'))dfprint('{:*^80}'.format('stacked dataframe'))df.stack()" }, { "code": null, "e": 5592, "s": 4878, "text": "Here, we create the dataframe. Then df.stack() turns our single-level column df into a dataseries with a multi-index index by fitting the columns into a new inner index (index level 1) for each value in the old outer index (index level 0). The outer level looks like it has only 2 values [cat,dog], but it is only for neat display and is really 4 values [cat,cat,dog,dog]. Something useful to note from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.htmlif the columns have multiple levels, the new index level(s) is (are) taken from the prescribed level(s) and the output is a DataFrame. So it’s good to keep in mind whether the transformation output is a dataseries or dataframe." }, { "code": null, "e": 5850, "s": 5592, "text": "print('{:*^80}'.format('stacked dataframe with index in column'))df.stack().reset_index(level = 1) #AttributeError: 'Series' object has no attribute 'pivot_table' , so must convert to dataframe before pivot_tablestacked = df.stack().reset_index(level = 1)" }, { "code": null, "e": 6434, "s": 5850, "text": "The values are aligned accordingly to the indexes, turning the dataframe from a wide format to a long format dataseries. Because pivot_table is a dataframe method and does not apply to dataseries, we can extract level 1 of the multi-index using reset_index(level = 1) to prepare for pivoting back. Specifying level = 0 would have extracted the outer index into a column. Note that ‘level_1’ is automatically added as a column name after reset_index(). This will be extra information that can be used or cleaned and ignored later. The 0 column above values is added automatically too." }, { "code": null, "e": 6699, "s": 6434, "text": "It does not matter if you extracted level 0 or level 1 at this stage. You can simply switch the inputs to index and columns parameters of pivot_table later to achieve the same output (barring the tiny df.columns.name difference) and recover the original dataframe." }, { "code": null, "e": 7109, "s": 6699, "text": "print('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)'))recovered_df1 = df.stack().reset_index(level = 1).pivot_table(index = stacked.index, columns = 'level_1',values = 0) #pivot_table orders columns alphabetically,specifying values parameter prevents creation of useless multiindex column recovered_df1.columns.name = None #remove 'level_1' column.namerecovered_df1" }, { "code": null, "e": 7535, "s": 7109, "text": "Finally, we specify index and columns parameters in pivot_table by selecting from the current column names to describe how the final pivoted dataframe should look like. The values parameter is optional, but not specifying it will add column names not yet specified in index or columns parameters to the outerlevel of current columns to create multi-indexed columns that look ugly and make data access unnecessarily difficult." }, { "code": null, "e": 7700, "s": 7535, "text": "print('{:*^80}'.format('dataframe'))dfprint('{:*^80}'.format('stack and convert to dataframe to expose pivot_table'))stacked_df = pd.DataFrame(df.stack())stacked_df" }, { "code": null, "e": 8040, "s": 7700, "text": "Remember that pivot_table is a dataframe method and does not apply to dataseries, so rather than reset_index as in part1, we can directly construct a dataframe from the series using pd.DataFrame(df.stack()) to create a multi-indexed dataframe to make the pivot_table method available and work harder in specifying its parameters correctly." }, { "code": null, "e": 8310, "s": 8040, "text": "print('{:*^80}'.format('rather than unstack, pivot_table achieves the same'))idx_lvl0, idx_lvl1 = stacked_df.index.get_level_values(0), stacked_df.index.get_level_values(1)recovered_df2 = stacked_df.pivot_table(index=idx_lvl0,columns = idx_lvl1,values = 0)recovered_df2" }, { "code": null, "e": 8844, "s": 8310, "text": "index.get_level_values(0) is a way to get the index values of the specified muti-index level (in this case, 0) as a pandas.core.indexes.base.Index object which can be conveniently used by functions accepting sequences/lists. In part 2, we match the correct index information from each level into the index and columns parameters of pivot table to recover the original dataframe. Part 2 is cleaner than part 1 because there was no reset_index to create an extra ‘level_0’ or ‘level_1’ in df.columns.name that we set to None in part 1." }, { "code": null, "e": 9110, "s": 8844, "text": "print('{:*^80}'.format('dataframe'))dfprint('{:*^80}'.format('melting loses index information'))melted = df.melt() #melt appends columns into new \"variable\" column, while stack adds columns to new inner index layer (same information end up different places)melted" }, { "code": null, "e": 9381, "s": 9110, "text": "Similar to stacking, melt turns wide format data to long format data by putting compressing columns into a single list. The difference is that stack inserted this list into the inner index, while melt inserts this list as a new column called ‘variable’ (can be renamed)." }, { "code": null, "e": 9614, "s": 9381, "text": "print('{:*^80}'.format('manually enrich index')) # until this is solved: https://github.com/pandas-dev/pandas/issues/17440melted.index = ['cat','dog']*2 #list(df.index)*len(df.columns) for more generalizable index generationmelted" }, { "code": null, "e": 9865, "s": 9614, "text": "Note that melt has made the cat dog information in the index disappear. This makes it impossible to recover the original dataframe. Until this issue (https://github.com/pandas-dev/pandas/issues/17440) is fixed, we have to manually add back the index." }, { "code": null, "e": 10134, "s": 9865, "text": "print('{:*^80}'.format('pivot_table recovered original dataframe (with extra name for columns)'))recovered_df3 = melted.pivot_table(index = melted.index, columns = 'variable',values = 'value')recovered_df3.columns.name=None #remove 'variable' column.namerecovered_df3" }, { "code": null, "e": 10297, "s": 10134, "text": "Finally, pivot_table with the right parameters will recover our original dataframe. Like in part 1, ‘variable’ is removed from df.columns.name for exact recovery." }, { "code": null, "e": 10915, "s": 10297, "text": "I hope these transformations have given beginners to these functions a better understanding of how flexible pandas is. The same information can be placed in Index or Columns using set_index and reset_index depending on where they serve the greatest purpose. For example, instead of df.loc[df.col == value] to filter when the information is in a column, setting col to the index, and doing df.loc[value] is much simpler. Whether information is in the index or column will also greatly affect how pd.merge, pd.concat, dataframe.join work on such dataseries/dataframes, but that would be another whole article by itself." } ]
Siamese NN Recipes with Keras. Practical Siamese neural network... | by Duygu ALTINOK | Towards Data Science
I have been enjoying Siamese networks for different NLU tasks at my work for quite some time. In this article, I’ll share quick recipes with Keras, featuring Glove vectors or BERT as the text vectorizer. We’ll focus on semantic similarity calculations. Semantic similarity is basically the task of determining if a group of text is related. Semantic similarity is usually calculated between a pair of text segments. In this article, I’ll give examples of how to compare two texts. A Siamese network is a NN with two or more inputs (typically number of inputs is two, otherwise one has to define 3-way distance functions). We encode the input texts, then feed the encoded vectors to a distance layer. Finally we run a classification layer on top of the distance layer. Distance can be cosine distance, L1 distance, exponential negative Manhattan distance and any other distance function. Here’s a Siamese network as a black box: Encoding the input text can be via LSTM, Universal Encoder or BERT. Depending on the text encoding with word embeddings, the architecture looks like the following figure: Here’s the Keras recipe with LSTM and a pretrained Embedding layer: from keras import backend as Kfirst_sent_in = Input(shape=(MAX_LEN,))second_sent_in = Input(shape=(MAX_LEN,))embedding_layer = Embedding(input_dim=n_words+1, output_dim=embed_size, embeddings_initializer=Constant(embedding_matrix), input_length=MAX_LEN, trainable=True, mask_zero=True)first_sent_embedding = embedding_layer(first_sent_in)second_sent_embedding = embedding_layer(second_sent_in)lstm = Bidirectional(LSTM(units=256, return_sequences=False))first_sent_encoded = lstm(first_sent_embedding)second_sent_encoded = lstm(second_sent_embedding)l1_norm = lambda x: 1 - K.abs(x[0] - x[1])merged = Lambda(function=l1_norm, output_shape=lambda x: x[0], name='L1_distance')([first_sent_encoded, second_sent_encoded])predictions = Dense(1, activation='sigmoid', name='classification_layer')(merged)model = Model([first_sent_in, second_sent_in], predictions)model.compile(loss = 'binary_crossentropy', optimizer = "adam", metrics=["accuracy"])print(model.summary())model.fit([fsents, ssents], labels, validation_split=0.1, epochs = 20,shuffle=True, batch_size = 256) Model summary should look like: Layer (type) Output Shape Param # Connected to ==================================================================================================input_1 (InputLayer) [(None, 200)] 0 __________________________________________________________________________________________________input_2 (InputLayer) [(None, 200)] 0 __________________________________________________________________________________________________embedding (Embedding) (None, 200, 100) 1633800 input_1[0][0] input_2[0][0] __________________________________________________________________________________________________bidirectional (Bidirectional) (None, 512) 731136 embedding[0][0] embedding[1][0] __________________________________________________________________________________________________L1_distance (Lambda) (None, 512) 0 bidirectional[0][0] bidirectional[1][0] __________________________________________________________________________________________________classification_layer (Dense) (None, 1) 1026 L1_distance[0][0] ==================================================================================================Total params: 2,365,962Trainable params: 2,365,962Non-trainable params: 0______________________________ The two input layers inputs the two texts to be compared. Then, we feed the input words to the Embedding layer to get the word embeddings per each input word. After that, we feed the embedding vectors of first sentence to the LSTM layer and embedding vectors of second sentence to the LSTM layer separately and get a dense representation for the first text and the second text (represented with variables first_sent_encoded and second_sent_encoded ). Now comes the tricky part, merge layer. Merge layer inputs the dense representation of the first text and second text and computes the distance between them. If you look at he fourth layer of the model summary, you see L1_distance (Lambda) (this layer is technically a Keras Lambda layer), accepts two inputs, which are both are outputs of the LSTM layer. The result is a 512 dimensional vector and we feed this vector to the classifier. The result is a 1 dimensional vector, which is a 0 or 1 because I’m doing binary classification as similar or not similar. At the classification layer, I squashed the 512-dim distance vector by sigmoid (because I like this activation func a lot :)), also I compiled the model with binary_crossentory because again it’s a binary classification task. In this recipe used l1-distance to calculate the distance between the encoded vectors. You can use cosine distance or any other distance. I particularly like l1 distance because it’s not so smooth as a function. Same applies to the sigmoid function, it provides the nonlinearity that neural networks for language need. Recipe with BERT is just a bit different. We take out the embeddings + LSTM layers and place BERT layer instead (as BERT vectors include more than enough sequentiality!): fsent_inputs = Input(shape=(MAX_L,), dtype="int32") fsent_encoded = bert_model(fsent_inputs) fsent_encoded = fsent_encoded[1] ssent_inputs = Input(shape=(150,), dtype="int32") ssent_encoded = bert_model(ssent_inputs) ssent_encoded = ssent_encoded[1] merged =concatenate([fsent_encoded, ssent_encoded]) predictions = Dense(1, activation='sigmoid', name='classification_layer')(merged) model = Model([fsent_inputs, ssent_inputs], predictions) adam = keras.optimizers.Adam(learning_rate=2e-6,epsilon=1e-08) model.compile(loss="binary_crossentropy", metrics=["accuracy"], optimizer="adam") Here, we again feed a pair of text inputs to BERT layer separately and get their encodings fsent-encoded and ssent_encoded. We use the [CLS] token’s embedding which captures an average representation of the sentence. (BERT layer has 2 outputs, the first one is the vector for CLS token, and the second is a vector of (MAX_LEN, 768). The second output gives an vector for each token of the input sentence. We used the first input by calling fsent_encoded = fsent_encoded[1] and ssent_encoded = ssent_encoded[1]). Optimizer is again Adam, but with a bit different learning rate (we lower down the lr to prevent BERT behaving aggressive and overfit. BERT overfits quickly if we don’t prevent it). Loss is again binary cross entropy because we’re doing a binary classification task. Basically I replaced Embedding layer + LSTM with BERT layer, rest of the architecture is the same. Dear readers, you reached the end of this practical article. I aimed to provide a quick working solution as well as explaining how Siamese networks work. If you wish you can place dropout layers to several places and experiment yourself. It’s exciting to play with Siamese networks, personally they might be my favourite architecture.I hope you liked Siamese NN and use in your work too. Until meeting at new architectures, thanks for your attention and stay tuned!
[ { "code": null, "e": 652, "s": 171, "text": "I have been enjoying Siamese networks for different NLU tasks at my work for quite some time. In this article, I’ll share quick recipes with Keras, featuring Glove vectors or BERT as the text vectorizer. We’ll focus on semantic similarity calculations. Semantic similarity is basically the task of determining if a group of text is related. Semantic similarity is usually calculated between a pair of text segments. In this article, I’ll give examples of how to compare two texts." }, { "code": null, "e": 1099, "s": 652, "text": "A Siamese network is a NN with two or more inputs (typically number of inputs is two, otherwise one has to define 3-way distance functions). We encode the input texts, then feed the encoded vectors to a distance layer. Finally we run a classification layer on top of the distance layer. Distance can be cosine distance, L1 distance, exponential negative Manhattan distance and any other distance function. Here’s a Siamese network as a black box:" }, { "code": null, "e": 1270, "s": 1099, "text": "Encoding the input text can be via LSTM, Universal Encoder or BERT. Depending on the text encoding with word embeddings, the architecture looks like the following figure:" }, { "code": null, "e": 1338, "s": 1270, "text": "Here’s the Keras recipe with LSTM and a pretrained Embedding layer:" }, { "code": null, "e": 2406, "s": 1338, "text": "from keras import backend as Kfirst_sent_in = Input(shape=(MAX_LEN,))second_sent_in = Input(shape=(MAX_LEN,))embedding_layer = Embedding(input_dim=n_words+1, output_dim=embed_size, embeddings_initializer=Constant(embedding_matrix), input_length=MAX_LEN, trainable=True, mask_zero=True)first_sent_embedding = embedding_layer(first_sent_in)second_sent_embedding = embedding_layer(second_sent_in)lstm = Bidirectional(LSTM(units=256, return_sequences=False))first_sent_encoded = lstm(first_sent_embedding)second_sent_encoded = lstm(second_sent_embedding)l1_norm = lambda x: 1 - K.abs(x[0] - x[1])merged = Lambda(function=l1_norm, output_shape=lambda x: x[0], name='L1_distance')([first_sent_encoded, second_sent_encoded])predictions = Dense(1, activation='sigmoid', name='classification_layer')(merged)model = Model([first_sent_in, second_sent_in], predictions)model.compile(loss = 'binary_crossentropy', optimizer = \"adam\", metrics=[\"accuracy\"])print(model.summary())model.fit([fsents, ssents], labels, validation_split=0.1, epochs = 20,shuffle=True, batch_size = 256)" }, { "code": null, "e": 2438, "s": 2406, "text": "Model summary should look like:" }, { "code": null, "e": 4208, "s": 2438, "text": "Layer (type) Output Shape Param # Connected to ==================================================================================================input_1 (InputLayer) [(None, 200)] 0 __________________________________________________________________________________________________input_2 (InputLayer) [(None, 200)] 0 __________________________________________________________________________________________________embedding (Embedding) (None, 200, 100) 1633800 input_1[0][0] input_2[0][0] __________________________________________________________________________________________________bidirectional (Bidirectional) (None, 512) 731136 embedding[0][0] embedding[1][0] __________________________________________________________________________________________________L1_distance (Lambda) (None, 512) 0 bidirectional[0][0] bidirectional[1][0] __________________________________________________________________________________________________classification_layer (Dense) (None, 1) 1026 L1_distance[0][0] ==================================================================================================Total params: 2,365,962Trainable params: 2,365,962Non-trainable params: 0______________________________" }, { "code": null, "e": 5446, "s": 4208, "text": "The two input layers inputs the two texts to be compared. Then, we feed the input words to the Embedding layer to get the word embeddings per each input word. After that, we feed the embedding vectors of first sentence to the LSTM layer and embedding vectors of second sentence to the LSTM layer separately and get a dense representation for the first text and the second text (represented with variables first_sent_encoded and second_sent_encoded ). Now comes the tricky part, merge layer. Merge layer inputs the dense representation of the first text and second text and computes the distance between them. If you look at he fourth layer of the model summary, you see L1_distance (Lambda) (this layer is technically a Keras Lambda layer), accepts two inputs, which are both are outputs of the LSTM layer. The result is a 512 dimensional vector and we feed this vector to the classifier. The result is a 1 dimensional vector, which is a 0 or 1 because I’m doing binary classification as similar or not similar. At the classification layer, I squashed the 512-dim distance vector by sigmoid (because I like this activation func a lot :)), also I compiled the model with binary_crossentory because again it’s a binary classification task." }, { "code": null, "e": 5765, "s": 5446, "text": "In this recipe used l1-distance to calculate the distance between the encoded vectors. You can use cosine distance or any other distance. I particularly like l1 distance because it’s not so smooth as a function. Same applies to the sigmoid function, it provides the nonlinearity that neural networks for language need." }, { "code": null, "e": 5936, "s": 5765, "text": "Recipe with BERT is just a bit different. We take out the embeddings + LSTM layers and place BERT layer instead (as BERT vectors include more than enough sequentiality!):" }, { "code": null, "e": 6882, "s": 5936, "text": "fsent_inputs = Input(shape=(MAX_L,), dtype=\"int32\") fsent_encoded = bert_model(fsent_inputs) fsent_encoded = fsent_encoded[1] ssent_inputs = Input(shape=(150,), dtype=\"int32\") ssent_encoded = bert_model(ssent_inputs) ssent_encoded = ssent_encoded[1] merged =concatenate([fsent_encoded, ssent_encoded]) predictions = Dense(1, activation='sigmoid', name='classification_layer')(merged) model = Model([fsent_inputs, ssent_inputs], predictions) adam = keras.optimizers.Adam(learning_rate=2e-6,epsilon=1e-08) model.compile(loss=\"binary_crossentropy\", metrics=[\"accuracy\"], optimizer=\"adam\")" }, { "code": null, "e": 7760, "s": 6882, "text": "Here, we again feed a pair of text inputs to BERT layer separately and get their encodings fsent-encoded and ssent_encoded. We use the [CLS] token’s embedding which captures an average representation of the sentence. (BERT layer has 2 outputs, the first one is the vector for CLS token, and the second is a vector of (MAX_LEN, 768). The second output gives an vector for each token of the input sentence. We used the first input by calling fsent_encoded = fsent_encoded[1] and ssent_encoded = ssent_encoded[1]). Optimizer is again Adam, but with a bit different learning rate (we lower down the lr to prevent BERT behaving aggressive and overfit. BERT overfits quickly if we don’t prevent it). Loss is again binary cross entropy because we’re doing a binary classification task. Basically I replaced Embedding layer + LSTM with BERT layer, rest of the architecture is the same." } ]
Embedded Systems - Assembly Language
Assembly languages were developed to provide mnemonics or symbols for the machine level code instructions. Assembly language programs consist of mnemonics, thus they should be translated into machine code. A program that is responsible for this conversion is known as assembler. Assembly language is often termed as a low-level language because it directly works with the internal structure of the CPU. To program in assembly language, a programmer must know all the registers of the CPU. Different programming languages such as C, C++, Java and various other languages are called high-level languages because they do not deal with the internal details of a CPU. In contrast, an assembler is used to translate an assembly language program into machine code (sometimes also called object code or opcode). Similarly, a compiler translates a high-level language into machine code. For example, to write a program in C language, one must use a C compiler to translate the program into machine language. An assembly language program is a series of statements, which are either assembly language instructions such as ADD and MOV, or statements called directives. An instruction tells the CPU what to do, while a directive (also called pseudo-instructions) gives instruction to the assembler. For example, ADD and MOV instructions are commands which the CPU runs, while ORG and END are assembler directives. The assembler places the opcode to the memory location 0 when the ORG directive is used, while END indicates to the end of the source code. A program language instruction consists of the following four fields − [ label: ] mnemonics [ operands ] [;comment ] A square bracket ( [ ] ) indicates that the field is optional. The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters. The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters. The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; "A, C" and "C, #68" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute. The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; "A, C" and "C, #68" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute. 1.0000 ORG 0H ;start (origin) at location 0 2 0000 7D25 MOV R5,#25H ;load 25H into R5 3.0002 7F34 MOV R7,#34H ;load 34H into R7 4.0004 7400 MOV A,#0 ;load 0 into A 5.0006 2D ADD A,R5 ;add contents of R5 to A 6.0007 2F ADD A,R7 ;add contents of R7 to A 7.0008 2412 ADD A,#12H ;add to A value 12 H 8.000A 80FE HERE: SJMP HERE ;stay in this loop 9.000C END ;end of asm source file The comment field begins with a semicolon which is a comment indicator. The comment field begins with a semicolon which is a comment indicator. Notice the Label "HERE" in the program. Any label which refers to an instruction should be followed by a colon. Notice the Label "HERE" in the program. Any label which refers to an instruction should be followed by a colon. Here we will discuss about the basic form of an assembly language. The steps to create, assemble, and run an assembly language program are as follows − First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The "asm" extension for the source file is used by an assembler in the next step. First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The "asm" extension for the source file is used by an assembler in the next step. The "asm" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the "src" extensions. The "lst" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected. The "asm" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the "src" extensions. The "lst" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected. Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension "abs". Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension "abs". Next, the "abs" file is fed to a program called "OH" (object to hex converter), which creates a file with the extension "hex" that is ready to burn in to the ROM. Next, the "abs" file is fed to a program called "OH" (object to hex converter), which creates a file with the extension "hex" that is ready to burn in to the ROM. The 8051 microcontroller contains a single data type of 8-bits, and each register is also of 8-bits size. The programmer has to break down data larger than 8-bits (00 to FFH, or to 255 in decimal) so that it can be processed by the CPU. The DB directive is the most widely used data directive in the assembler. It is used to define the 8-bit data. It can also be used to define decimal, binary, hex, or ASCII formats data. For decimal, the "D" after the decimal number is optional, but it is required for "B" (binary) and "Hl" (hexadecimal). To indicate ASCII, simply place the characters in quotation marks ('like this'). The assembler generates ASCII code for the numbers/characters automatically. The DB directive is the only directive that can be used to define ASCII strings larger than two characters; therefore, it should be used for all the ASCII data definitions. Some examples of DB are given below − ORG 500H DATA1: DB 28 ;DECIMAL (1C in hex) DATA2: DB 00110101B ;BINARY (35 in hex) DATA3: DB 39H ;HEX ORG 510H DATA4: DB "2591" ;ASCII NUMBERS ORG 520H DATA6: DA "MY NAME IS Michael" ;ASCII CHARACTERS Either single or double quotes can be used around ASCII strings. DB is also used to allocate memory in byte-sized chunks. Some of the directives of 8051 are as follows − ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa. ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa. EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction "MOV R3, #COUNT", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program. EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction "MOV R3, #COUNT", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program. END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler. END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler. All the labels in assembly language must follow the rules given below − Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($). Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($). The first character should be in alphabetical character; it cannot be a number. The first character should be in alphabetical character; it cannot be a number. Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics. Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics. 65 Lectures 6.5 hours Amit Rana 36 Lectures 4.5 hours Amit Rana 33 Lectures 3 hours Ashraf Said 23 Lectures 2 hours Smart Logic Academy 66 Lectures 5.5 hours NerdyElectronics 49 Lectures 8.5 hours Rahul Shrivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2372, "s": 1883, "text": "Assembly languages were developed to provide mnemonics or symbols for the machine level code instructions. Assembly language programs consist of mnemonics, thus they should be translated into machine code. A program that is responsible for this conversion is known as assembler. Assembly language is often termed as a low-level language because it directly works with the internal structure of the CPU. To program in assembly language, a programmer must know all the registers of the CPU." }, { "code": null, "e": 2882, "s": 2372, "text": "Different programming languages such as C, C++, Java and various other languages are called high-level languages because they do not deal with the internal details of a CPU. In contrast, an assembler is used to translate an assembly language program into machine code (sometimes also called object code or opcode). Similarly, a compiler translates a high-level language into machine code. For example, to write a program in C language, one must use a C compiler to translate the program into machine language." }, { "code": null, "e": 3040, "s": 2882, "text": "An assembly language program is a series of statements, which are either assembly language instructions such as ADD and MOV, or statements called directives." }, { "code": null, "e": 3495, "s": 3040, "text": "An instruction tells the CPU what to do, while a directive (also called pseudo-instructions) gives instruction to the assembler. For example, ADD and MOV instructions are commands which the CPU runs, while ORG and END are assembler directives. The assembler places the opcode to the memory location 0 when the ORG directive is used, while END indicates to the end of the source code. A program language instruction consists of the following four fields −" }, { "code": null, "e": 3548, "s": 3495, "text": "[ label: ] mnemonics [ operands ] [;comment ] \n" }, { "code": null, "e": 3611, "s": 3548, "text": "A square bracket ( [ ] ) indicates that the field is optional." }, { "code": null, "e": 3745, "s": 3611, "text": "The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters." }, { "code": null, "e": 3879, "s": 3745, "text": "The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters." }, { "code": null, "e": 4316, "s": 3879, "text": "The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; \"A, C\" and \"C, #68\" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute." }, { "code": null, "e": 4753, "s": 4316, "text": "The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; \"A, C\" and \"C, #68\" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute." }, { "code": null, "e": 5263, "s": 4753, "text": "1.0000 ORG 0H ;start (origin) at location 0 \n2 0000 7D25 MOV R5,#25H ;load 25H into R5 \n3.0002 7F34 MOV R7,#34H ;load 34H into R7 \n4.0004 7400 MOV A,#0 ;load 0 into A \n5.0006 2D ADD A,R5 ;add contents of R5 to A \n6.0007 2F ADD A,R7 ;add contents of R7 to A\n7.0008 2412 ADD A,#12H ;add to A value 12 H \n8.000A 80FE HERE: SJMP HERE ;stay in this loop \n9.000C END ;end of asm source file\n" }, { "code": null, "e": 5335, "s": 5263, "text": "The comment field begins with a semicolon which is a comment indicator." }, { "code": null, "e": 5407, "s": 5335, "text": "The comment field begins with a semicolon which is a comment indicator." }, { "code": null, "e": 5519, "s": 5407, "text": "Notice the Label \"HERE\" in the program. Any label which refers to an instruction should be followed by a colon." }, { "code": null, "e": 5631, "s": 5519, "text": "Notice the Label \"HERE\" in the program. Any label which refers to an instruction should be followed by a colon." }, { "code": null, "e": 5783, "s": 5631, "text": "Here we will discuss about the basic form of an assembly language. The steps to create, assemble, and run an assembly language program are as follows −" }, { "code": null, "e": 6112, "s": 5783, "text": "First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The \"asm\" extension for the source file is used by an assembler in the next step." }, { "code": null, "e": 6441, "s": 6112, "text": "First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The \"asm\" extension for the source file is used by an assembler in the next step." }, { "code": null, "e": 6972, "s": 6441, "text": "The \"asm\" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the \"src\" extensions. The \"lst\" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected." }, { "code": null, "e": 7503, "s": 6972, "text": "The \"asm\" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the \"src\" extensions. The \"lst\" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected." }, { "code": null, "e": 7662, "s": 7503, "text": "Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension \"abs\"." }, { "code": null, "e": 7821, "s": 7662, "text": "Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension \"abs\"." }, { "code": null, "e": 7984, "s": 7821, "text": "Next, the \"abs\" file is fed to a program called \"OH\" (object to hex converter), which creates a file with the extension \"hex\" that is ready to burn in to the ROM." }, { "code": null, "e": 8147, "s": 7984, "text": "Next, the \"abs\" file is fed to a program called \"OH\" (object to hex converter), which creates a file with the extension \"hex\" that is ready to burn in to the ROM." }, { "code": null, "e": 8384, "s": 8147, "text": "The 8051 microcontroller contains a single data type of 8-bits, and each register is also of 8-bits size. The programmer has to break down data larger than 8-bits (00 to FFH, or to 255 in decimal) so that it can be processed by the CPU." }, { "code": null, "e": 8689, "s": 8384, "text": "The DB directive is the most widely used data directive in the assembler. It is used to define the 8-bit data. It can also be used to define decimal, binary, hex, or ASCII formats data. For decimal, the \"D\" after the decimal number is optional, but it is required for \"B\" (binary) and \"Hl\" (hexadecimal)." }, { "code": null, "e": 9058, "s": 8689, "text": "To indicate ASCII, simply place the characters in quotation marks ('like this'). The assembler generates ASCII code for the numbers/characters automatically. The DB directive is the only directive that can be used to define ASCII strings larger than two characters; therefore, it should be used for all the ASCII data definitions. Some examples of DB are given below −" }, { "code": null, "e": 9406, "s": 9058, "text": " ORG 500H \nDATA1: DB 28 ;DECIMAL (1C in hex) \nDATA2: DB 00110101B ;BINARY (35 in hex) \nDATA3: DB 39H ;HEX \n ORG 510H \nDATA4: DB \"2591\" ;ASCII NUMBERS \n ORG 520H \nDATA6: DA \"MY NAME IS Michael\" ;ASCII CHARACTERS \n" }, { "code": null, "e": 9528, "s": 9406, "text": "Either single or double quotes can be used around ASCII strings. DB is also used to allocate memory in byte-sized chunks." }, { "code": null, "e": 9576, "s": 9528, "text": "Some of the directives of 8051 are as follows −" }, { "code": null, "e": 9846, "s": 9576, "text": "ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa." }, { "code": null, "e": 10116, "s": 9846, "text": "ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa." }, { "code": null, "e": 10648, "s": 10116, "text": "EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction \"MOV R3, #COUNT\", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program." }, { "code": null, "e": 11180, "s": 10648, "text": "EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction \"MOV R3, #COUNT\", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program." }, { "code": null, "e": 11356, "s": 11180, "text": "END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler." }, { "code": null, "e": 11532, "s": 11356, "text": "END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler." }, { "code": null, "e": 11604, "s": 11532, "text": "All the labels in assembly language must follow the rules given below −" }, { "code": null, "e": 11886, "s": 11604, "text": "Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($)." }, { "code": null, "e": 12168, "s": 11886, "text": "Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($)." }, { "code": null, "e": 12248, "s": 12168, "text": "The first character should be in alphabetical character; it cannot be a number." }, { "code": null, "e": 12328, "s": 12248, "text": "The first character should be in alphabetical character; it cannot be a number." }, { "code": null, "e": 12478, "s": 12328, "text": "Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics." }, { "code": null, "e": 12628, "s": 12478, "text": "Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics." }, { "code": null, "e": 12663, "s": 12628, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 12674, "s": 12663, "text": " Amit Rana" }, { "code": null, "e": 12709, "s": 12674, "text": "\n 36 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12720, "s": 12709, "text": " Amit Rana" }, { "code": null, "e": 12753, "s": 12720, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 12766, "s": 12753, "text": " Ashraf Said" }, { "code": null, "e": 12799, "s": 12766, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 12820, "s": 12799, "text": " Smart Logic Academy" }, { "code": null, "e": 12855, "s": 12820, "text": "\n 66 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12873, "s": 12855, "text": " NerdyElectronics" }, { "code": null, "e": 12908, "s": 12873, "text": "\n 49 Lectures \n 8.5 hours \n" }, { "code": null, "e": 12927, "s": 12908, "text": " Rahul Shrivastava" }, { "code": null, "e": 12934, "s": 12927, "text": " Print" }, { "code": null, "e": 12945, "s": 12934, "text": " Add Notes" } ]
Writer append(char) method in Java with Examples - GeeksforGeeks
29 Jan, 2019 The append(char) method of Writer Class in Java is used to append the specified char value on the writer. This char value is taken as a parameter. Syntax: public void append(char charValue) Parameters: This method accepts a mandatory parameter charValue which is the char value to be appended on the writer. Return Value: This method do not returns any value. Below methods illustrates the working of append(char) method: Program 1: // Java program to demonstrate// Writer append(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Append the char value 'A' // to this writer using append() method // This will put the charValue in the // writer till it is appended on the console writer.append('A'); writer.flush(); } catch (Exception e) { System.out.println(e); } }} A Program 2: // Java program to demonstrate// Writer append(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Append the char value 'G' // to this writer using append() method // This will put the charValue in the // writer till it is appended on the console writer.append('G'); writer.flush(); } catch (Exception e) { System.out.println(e); } }} G Java-Functions Java-IO package Java-Writer Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Collections in Java Set in Java Overriding in Java
[ { "code": null, "e": 24123, "s": 24095, "text": "\n29 Jan, 2019" }, { "code": null, "e": 24270, "s": 24123, "text": "The append(char) method of Writer Class in Java is used to append the specified char value on the writer. This char value is taken as a parameter." }, { "code": null, "e": 24278, "s": 24270, "text": "Syntax:" }, { "code": null, "e": 24313, "s": 24278, "text": "public void append(char charValue)" }, { "code": null, "e": 24431, "s": 24313, "text": "Parameters: This method accepts a mandatory parameter charValue which is the char value to be appended on the writer." }, { "code": null, "e": 24483, "s": 24431, "text": "Return Value: This method do not returns any value." }, { "code": null, "e": 24545, "s": 24483, "text": "Below methods illustrates the working of append(char) method:" }, { "code": null, "e": 24556, "s": 24545, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Writer append(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Append the char value 'A' // to this writer using append() method // This will put the charValue in the // writer till it is appended on the console writer.append('A'); writer.flush(); } catch (Exception e) { System.out.println(e); } }}", "e": 25167, "s": 24556, "text": null }, { "code": null, "e": 25170, "s": 25167, "text": "A\n" }, { "code": null, "e": 25181, "s": 25170, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Writer append(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Append the char value 'G' // to this writer using append() method // This will put the charValue in the // writer till it is appended on the console writer.append('G'); writer.flush(); } catch (Exception e) { System.out.println(e); } }}", "e": 25792, "s": 25181, "text": null }, { "code": null, "e": 25795, "s": 25792, "text": "G\n" }, { "code": null, "e": 25810, "s": 25795, "text": "Java-Functions" }, { "code": null, "e": 25826, "s": 25810, "text": "Java-IO package" }, { "code": null, "e": 25838, "s": 25826, "text": "Java-Writer" }, { "code": null, "e": 25843, "s": 25838, "text": "Java" }, { "code": null, "e": 25848, "s": 25843, "text": "Java" }, { "code": null, "e": 25946, "s": 25848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25955, "s": 25946, "text": "Comments" }, { "code": null, "e": 25968, "s": 25955, "text": "Old Comments" }, { "code": null, "e": 25998, "s": 25968, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26029, "s": 25998, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26048, "s": 26029, "text": "Interfaces in Java" }, { "code": null, "e": 26080, "s": 26048, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26100, "s": 26080, "text": "Stack Class in Java" }, { "code": null, "e": 26132, "s": 26100, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26156, "s": 26132, "text": "Singleton Class in Java" }, { "code": null, "e": 26176, "s": 26156, "text": "Collections in Java" }, { "code": null, "e": 26188, "s": 26176, "text": "Set in Java" } ]
Custom metrics in tensorflow2.2 | Towards Data Science
Keras has simplified DNN based machine learning a lot and it keeps getting better. Here we show how to implement metric based on the confusion matrix (recall, precision and f1) and show how using them is very simple in tensorflow 2.2. You can directly run the notebook in Google Colab. When considering a multi-class problem it is often said that accuracy is not a good metric if the classes are imbalanced. While that is certainly true, accuracy is also a bad metric when all classes do not train equally well even if the datasets are balanced. In this article, I will use Fashion MNIST to highlight this aspect. This is however not the only goal of this article as this can be done by simply plotting the confusion matrix on the validation set at the end of training. What we discuss here is the ability to easily extend keras.metrics.Metric class to make a metric that tracks the confusion matrix during training and can be used to follow the class specific recall, precision and f1 and plot them in the usual way with keras. Getting class specific recall, precision and f1 during training is useful for at least two things: We can see if training is stable — plots do not jump around too much — on a per class basisWe can implement more customized training based on class statistic — early stopping or even dynamically changing class weights. We can see if training is stable — plots do not jump around too much — on a per class basis We can implement more customized training based on class statistic — early stopping or even dynamically changing class weights. Furthermore, since tensorflow 2.2, integrating such custom metrics into training and validation has become very easy thanks to the new model methods train_step and test_step. There is also an associate predict_step that we do not use here but works in the same spirit. So lets get down to it. We first make a custom metric class. While there are more steps to this and they are show in the referenced jupyter notebook, the important thing is to implement the API that integrates with the rest of Keras training and testing workflow. That is as simple as implementing and update_state that takes in the true labels and predictions, a reset_states that re-initializes the metric. class ConfusionMatrixMetric(tf.keras.metrics.Metric): def update_state(self, y_true, y_pred,sample_weight=None): self.total_cm.assign_add(self.confusion_matrix(y_true,y_pred)) return self.total_cm def result(self): return self.process_confusion_matrix() def confusion_matrix(self,y_true, y_pred): """ Make a confusion matrix """ y_pred=tf.argmax(y_pred,1) cm=tf.math.confusion_matrix(y_true,y_pred,dtype=tf.float32,num_classes=self.num_classes) return cm def process_confusion_matrix(self): "returns precision, recall and f1 along with overall accuracy" cm=self.total_cm diag_part=tf.linalg.diag_part(cm) precision=diag_part/(tf.reduce_sum(cm,0)+tf.constant(1e-15)) recall=diag_part/(tf.reduce_sum(cm,1)+tf.constant(1e-15)) f1=2*precision*recall/(precision+recall+tf.constant(1e-15)) return precision,recall,f1 In the normal Keras workflow, the method result will be called and it will return a number and nothing else needs to be done. However, in our case we have three tensors for precision, recall and f1 being returned and Keras does not know how to handle this out of the box. This is where the new features of tensorflow 2.2 come in. Since tensorflow 2.2 it is possible to modify what happens in each train step (i.e. training on a mini-batch) transparently (whereas earlier one had to write an unbounded function that was called in a custom training loop and one had to take care of decorating it with tf.function to enable autographing). Again, details are in the referenced jupyter notebook but the crux is the following class MySequential(keras.Sequential): def train_step(self, data): # Unpack the data. Its structure depends on your model and # on what you pass to `fit()`. x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass # Compute the loss value. # The loss function is configured in `compile()`. loss = self.compiled_loss( y, y_pred, regularization_losses=self.losses, ) # Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(loss, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.compiled_metrics.update_state(y, y_pred) output={m.name: m.result() for m in self.metrics[:-1]} if 'confusion_matrix_metric' in self.metrics_names: self.metrics[-1].fill_output(output) return output That’s it. Now you can create (using the above class not keras.Sequential), compile and fit a sequential model (the procedure to do with with Functional and Subclassing API is straightfoward and one just implements the above function). The resulting history now has elements like val_F1_1 etc. The advantage of this is that we can see how individual classes train We see that class 6 trains pretty bad with an F1 of around .6 on the validation set but the training itself is stable (the plot doesn’t jump around too much). As mentioned in the beginning, getting the per-class metrics during training is useful for at least two things: We can see if training is stable — plots do not jump around too much — on a per class basisWe can implement more customized training based on class statistic based early stopping or even dynamically changing class weights. We can see if training is stable — plots do not jump around too much — on a per class basis We can implement more customized training based on class statistic based early stopping or even dynamically changing class weights. Finally, let's look at the confusion matrix to see what is happening with class 6 In the confusion matrix, true classes are on the y-axis and predicted ones on the x-axis. We see that shirts (6), are being incorrectly labeled mostly as t-shirts (0), pullovers(2) and coats (4). Conversely, the mislabelling as shirts happens mostly for t-shirts. These kinds of mistakes are reasonable and I will discuss in a separate article what can be done to improve training in such cases. Ref: Code on githubGoogle Colab notebook Code on github Google Colab notebook
[ { "code": null, "e": 457, "s": 171, "text": "Keras has simplified DNN based machine learning a lot and it keeps getting better. Here we show how to implement metric based on the confusion matrix (recall, precision and f1) and show how using them is very simple in tensorflow 2.2. You can directly run the notebook in Google Colab." }, { "code": null, "e": 717, "s": 457, "text": "When considering a multi-class problem it is often said that accuracy is not a good metric if the classes are imbalanced. While that is certainly true, accuracy is also a bad metric when all classes do not train equally well even if the datasets are balanced." }, { "code": null, "e": 1200, "s": 717, "text": "In this article, I will use Fashion MNIST to highlight this aspect. This is however not the only goal of this article as this can be done by simply plotting the confusion matrix on the validation set at the end of training. What we discuss here is the ability to easily extend keras.metrics.Metric class to make a metric that tracks the confusion matrix during training and can be used to follow the class specific recall, precision and f1 and plot them in the usual way with keras." }, { "code": null, "e": 1299, "s": 1200, "text": "Getting class specific recall, precision and f1 during training is useful for at least two things:" }, { "code": null, "e": 1518, "s": 1299, "text": "We can see if training is stable — plots do not jump around too much — on a per class basisWe can implement more customized training based on class statistic — early stopping or even dynamically changing class weights." }, { "code": null, "e": 1610, "s": 1518, "text": "We can see if training is stable — plots do not jump around too much — on a per class basis" }, { "code": null, "e": 1738, "s": 1610, "text": "We can implement more customized training based on class statistic — early stopping or even dynamically changing class weights." }, { "code": null, "e": 2007, "s": 1738, "text": "Furthermore, since tensorflow 2.2, integrating such custom metrics into training and validation has become very easy thanks to the new model methods train_step and test_step. There is also an associate predict_step that we do not use here but works in the same spirit." }, { "code": null, "e": 2416, "s": 2007, "text": "So lets get down to it. We first make a custom metric class. While there are more steps to this and they are show in the referenced jupyter notebook, the important thing is to implement the API that integrates with the rest of Keras training and testing workflow. That is as simple as implementing and update_state that takes in the true labels and predictions, a reset_states that re-initializes the metric." }, { "code": null, "e": 3385, "s": 2416, "text": "class ConfusionMatrixMetric(tf.keras.metrics.Metric): def update_state(self, y_true, y_pred,sample_weight=None): self.total_cm.assign_add(self.confusion_matrix(y_true,y_pred)) return self.total_cm def result(self): return self.process_confusion_matrix() def confusion_matrix(self,y_true, y_pred): \"\"\" Make a confusion matrix \"\"\" y_pred=tf.argmax(y_pred,1) cm=tf.math.confusion_matrix(y_true,y_pred,dtype=tf.float32,num_classes=self.num_classes) return cm def process_confusion_matrix(self): \"returns precision, recall and f1 along with overall accuracy\" cm=self.total_cm diag_part=tf.linalg.diag_part(cm) precision=diag_part/(tf.reduce_sum(cm,0)+tf.constant(1e-15)) recall=diag_part/(tf.reduce_sum(cm,1)+tf.constant(1e-15)) f1=2*precision*recall/(precision+recall+tf.constant(1e-15)) return precision,recall,f1 " }, { "code": null, "e": 3715, "s": 3385, "text": "In the normal Keras workflow, the method result will be called and it will return a number and nothing else needs to be done. However, in our case we have three tensors for precision, recall and f1 being returned and Keras does not know how to handle this out of the box. This is where the new features of tensorflow 2.2 come in." }, { "code": null, "e": 4021, "s": 3715, "text": "Since tensorflow 2.2 it is possible to modify what happens in each train step (i.e. training on a mini-batch) transparently (whereas earlier one had to write an unbounded function that was called in a custom training loop and one had to take care of decorating it with tf.function to enable autographing)." }, { "code": null, "e": 4105, "s": 4021, "text": "Again, details are in the referenced jupyter notebook but the crux is the following" }, { "code": null, "e": 5107, "s": 4105, "text": "class MySequential(keras.Sequential): def train_step(self, data): # Unpack the data. Its structure depends on your model and # on what you pass to `fit()`. x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass # Compute the loss value. # The loss function is configured in `compile()`. loss = self.compiled_loss( y, y_pred, regularization_losses=self.losses, ) # Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(loss, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.compiled_metrics.update_state(y, y_pred) output={m.name: m.result() for m in self.metrics[:-1]} if 'confusion_matrix_metric' in self.metrics_names: self.metrics[-1].fill_output(output) return output" }, { "code": null, "e": 5401, "s": 5107, "text": "That’s it. Now you can create (using the above class not keras.Sequential), compile and fit a sequential model (the procedure to do with with Functional and Subclassing API is straightfoward and one just implements the above function). The resulting history now has elements like val_F1_1 etc." }, { "code": null, "e": 5471, "s": 5401, "text": "The advantage of this is that we can see how individual classes train" }, { "code": null, "e": 5630, "s": 5471, "text": "We see that class 6 trains pretty bad with an F1 of around .6 on the validation set but the training itself is stable (the plot doesn’t jump around too much)." }, { "code": null, "e": 5742, "s": 5630, "text": "As mentioned in the beginning, getting the per-class metrics during training is useful for at least two things:" }, { "code": null, "e": 5965, "s": 5742, "text": "We can see if training is stable — plots do not jump around too much — on a per class basisWe can implement more customized training based on class statistic based early stopping or even dynamically changing class weights." }, { "code": null, "e": 6057, "s": 5965, "text": "We can see if training is stable — plots do not jump around too much — on a per class basis" }, { "code": null, "e": 6189, "s": 6057, "text": "We can implement more customized training based on class statistic based early stopping or even dynamically changing class weights." }, { "code": null, "e": 6271, "s": 6189, "text": "Finally, let's look at the confusion matrix to see what is happening with class 6" }, { "code": null, "e": 6667, "s": 6271, "text": "In the confusion matrix, true classes are on the y-axis and predicted ones on the x-axis. We see that shirts (6), are being incorrectly labeled mostly as t-shirts (0), pullovers(2) and coats (4). Conversely, the mislabelling as shirts happens mostly for t-shirts. These kinds of mistakes are reasonable and I will discuss in a separate article what can be done to improve training in such cases." }, { "code": null, "e": 6672, "s": 6667, "text": "Ref:" }, { "code": null, "e": 6708, "s": 6672, "text": "Code on githubGoogle Colab notebook" }, { "code": null, "e": 6723, "s": 6708, "text": "Code on github" } ]
Check if the given permutation is a valid BFS of a given Tree - GeeksforGeeks
22 Jun, 2021 Given a tree with N nodes numbered from 1 to N and a permutation array of numbers from 1 to N. Check if it is possible to obtain the given permutation array by applying BFS (Breadth First Traversal) on the given tree.Note: Traversal will always start from 1.Example: Input: arr[] = { 1 5 2 3 4 6 } Edges of the given tree: 1 – 2 1 – 5 2 – 3 2 – 4 5 – 6 Output: No Explanation: There is no such traversal which is same as the given permutation. The valid traversals are: 1 2 5 3 4 6 1 2 5 4 3 6 1 5 2 6 3 4 1 5 2 6 4 3Input: arr[] = { 1 2 3 } Edges of the given tree: 1 – 2 2 – 3 Output: Yes Explanation: The given permutation is a valid one. Approach: To solve the problem mentioned above we have to follow the steps given below: In BFS we visit all the neighbors of the current node and push their children in the queue in order and repeat this process until the queue is not empty. Suppose there are two children of root: A and B. We are free to choose which of them to visit first. Let’s say we visit A first, but now we will have to push children of A in the queue, and we cannot visit children of B before A. So basically we can visit the children of a particular node in any order but the order in which the children of 2 different nodes should be visited is fixed i.e. if A if visited before B, then all the children of A should be visited before all the children of B. We will do the same. We will make a queue of sets and in each set, we will push the children of a particular node and traverse the permutation alongside. If the current element of permutation is found in the set at the top of the queue, then we will proceed otherwise, we will return false. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to check if the// given permutation is a valid// BFS of a given tree#include <bits/stdc++.h>using namespace std; // map for storing the treemap<int, vector<int> > tree; // map for marking// the nodes visitedmap<int, int> vis; // Function to check if// permutation is validbool valid_bfs(vector<int>& v){ int n = (int)v.size(); queue<set<int> > q; set<int> s; s.insert(1); /*inserting the root in the front of queue.*/ q.push(s); int i = 0; while (!q.empty() && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.count(v[i])) { return 0; } vis[v[i]] = 1; // if all the children of previous // nodes are visited then pop the // front element of queue. if (q.front().size() == 0) { q.pop(); } // if the current element of the // permutation is not found // in the set at the top of queue // then return false if (q.front().find(v[i]) == q.front().end()) { return 0; } s.clear(); // push all the children of current // node in a set and then push // the set in the queue. for (auto j : tree[v[i]]) { if (vis.count(j)) { continue; } s.insert(j); } if (s.size() > 0) { set<int> temp = s; q.push(temp); } s.clear(); // erase the current node from // the set at the top of queue q.front().erase(v[i]); // increment the index // of permutation i++; } return 1;} // Driver codeint main(){ tree[1].push_back(2); tree[2].push_back(1); tree[1].push_back(5); tree[5].push_back(1); tree[2].push_back(3); tree[3].push_back(2); tree[2].push_back(4); tree[4].push_back(2); tree[5].push_back(6); tree[6].push_back(5); vector<int> arr = { 1, 5, 2, 3, 4, 6 }; if (valid_bfs(arr)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // This code is contributed by rutvik_56 // Java implementation to check if the// given permutation is a valid// BFS of a given treeimport java.util.*;class GFG{ // Map for storing the treestatic HashMap<Integer, Vector<Integer> > tree = new HashMap<>(); // Map for marking// the nodes visitedstatic HashMap<Integer, Integer> vis = new HashMap<>(); // Function to check if// permutation is validstatic boolean valid_bfs(List<Integer> v){ int n = (int)v.size(); Queue<HashSet<Integer> > q = new LinkedList<>(); HashSet<Integer> s = new HashSet<>(); s.add(1); // Inserting the root in // the front of queue. q.add(s); int i = 0; while (!q.isEmpty() && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.containsKey(v.get(i))) { return false; } vis.put(v.get(i), 1); // If all the children of previous // nodes are visited then pop the // front element of queue. if (q.peek().size() == 0) { q.remove(); } // If the current element of the // permutation is not found // in the set at the top of queue // then return false if (!q.peek().contains(v.get(i))) { return false; } s.clear(); // Push all the children of current // node in a set and then push // the set in the queue. for (int j : tree.get(v.get(i))) { if (vis.containsKey(j)) { continue; } s.add(j); } if (s.size() > 0) { HashSet<Integer> temp = s; q.add(temp); } s.clear(); // Erase the current node from // the set at the top of queue q.peek().remove(v.get(i)); // Increment the index // of permutation i++; } return true;} // Driver codepublic static void main(String[] args){ for (int i = 1; i <= 6; i++) { tree.put(i, new Vector<Integer>()); } tree.get(1).add(2); tree.get(2).add(1); tree.get(1).add(5); tree.get(5).add(1); tree.get(2).add(3); tree.get(3).add(2); tree.get(2).add(4); tree.get(4).add(2); tree.get(5).add(6); tree.get(6).add(5); Integer []arr1 = {1, 5, 2, 3, 4, 6}; List<Integer> arr = Arrays.asList(arr1); if (valid_bfs(arr)) System.out.print("Yes" + "\n"); else System.out.print("No" + "\n");}} // This code is contributed by Princi Singh # Python3 implementation to check if the# given permutation is a valid# BFS of a given tree # map for storing the treetree=dict() # map for marking# the nodes visitedvis=dict() # Function to check if# permutation is validdef valid_bfs( v): n = len(v) q=[] s=set() s.add(1); '''inserting the root in the front of queue.''' q.append(s); i = 0; while (len(q)!=0 and i < n): # If the current node # in a permutation # is already visited # then return false if (v[i] in vis): return 0; vis[v[i]] = 1; # if all the children of previous # nodes are visited then pop the # front element of queue. if (len(q[0])== 0): q.pop(0); # if the current element of the # permutation is not found # in the set at the top of queue # then return false if (v[i] not in q[0]): return 0; s.clear(); # append all the children of current # node in a set and then append # the set in the queue. for j in tree[v[i]]: if (j in vis): continue; s.add(j); if (len(s) > 0): temp = s; q.append(temp); s.clear(); # erase the current node from # the set at the top of queue q[0].discard(v[i]); # increment the index # of permutation i+=1 return 1; # Driver codeif __name__=="__main__": tree[1]=[] tree[2]=[] tree[5]=[] tree[3]=[] tree[2]=[] tree[4]=[] tree[6]=[] tree[1].append(2); tree[2].append(1); tree[1].append(5); tree[5].append(1); tree[2].append(3); tree[3].append(2); tree[2].append(4); tree[4].append(2); tree[5].append(6); tree[6].append(5); arr = [ 1, 5, 2, 3, 4, 6 ] if (valid_bfs(arr)): print("Yes") else: print("No") // C# implementation to check// if the given permutation// is a valid BFS of a given treeusing System;using System.Collections.Generic;class GFG{ // Map for storing the treestatic Dictionary<int, List<int>> tree = new Dictionary<int, List<int>>(); // Map for marking// the nodes visitedstatic Dictionary<int, int> vis = new Dictionary<int, int>(); // Function to check if// permutation is validstatic bool valid_bfs(List<int> v){ int n = (int)v.Count; Queue<HashSet<int>> q = new Queue<HashSet<int>>(); HashSet<int> s = new HashSet<int>(); s.Add(1); // Inserting the root in // the front of queue. q.Enqueue(s); int i = 0; while (q.Count != 0 && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.ContainsKey(v[i])) { return false; } vis.Add(v[i], 1); // If all the children of previous // nodes are visited then pop the // front element of queue. if (q.Peek().Count == 0) { q.Dequeue(); } // If the current element of the // permutation is not found // in the set at the top of queue // then return false if (!q.Peek().Contains(v[i])) { return false; } s.Clear(); // Push all the children of current // node in a set and then push // the set in the queue. foreach (int j in tree[v[i]]) { if (vis.ContainsKey(j)) { continue; } s.Add(j); } if (s.Count > 0) { HashSet<int> temp = s; q.Enqueue(temp); } s.Clear(); // Erase the current node from // the set at the top of queue q.Peek().Remove(v[i]); // Increment the index // of permutation i++; } return true;} // Driver codepublic static void Main(String[] args){ for (int i = 1; i <= 6; i++) { tree.Add(i, new List<int>()); } tree[1].Add(2); tree[2].Add(1); tree[1].Add(5); tree[5].Add(1); tree[2].Add(3); tree[3].Add(2); tree[2].Add(4); tree[4].Add(2); tree[5].Add(6); tree[6].Add(5); int []arr1 = {1, 5, 2, 3, 4, 6}; List<int> arr = new List<int>(); arr.AddRange(arr1); if (valid_bfs(arr)) Console.Write("Yes" + "\n"); else Console.Write("No" + "\n");}} // This code is contributed by Princi Singh <script> // Javascript implementation to check if the // given permutation is a valid // BFS of a given tree // Map for storing the tree let tree = new Map(); // Map for marking // the nodes visited let vis = new Map(); // Function to check if // permutation is valid function valid_bfs(v) { let n = v.length; let q = []; let s = new Set(); s.add(1); // Inserting the root in // the front of queue. q.push(s); let i = 0; while (q.length > 0 && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.has(v[i])) { return false; } vis.set(v[i], 1); // If all the children of previous // nodes are visited then pop the // front element of queue. if (q[0].length == 0) { q.shift(); } // If the current element of the // permutation is not found // in the set at the top of queue // then return false if (!q[0].has(v[i])) { return false; } s.clear(); // Push all the children of current // node in a set and then push // the set in the queue. for (let j = 0; j < (tree.get(v[i])).length; j++) { if (vis.has((tree.get(v[i]))[j])) { continue; } s.add((tree.get(v[i]))[j]); } if (s.size > 0) { let temp = s; q.push(temp); } s.clear(); // Erase the current node from // the set at the top of queue q[0].delete(v[i]); // Increment the index // of permutation i++; } return true; } for (let i = 1; i <= 6; i++) { tree.set(i, []); } tree.get(1).push(2); tree.get(2).push(1); tree.get(1).push(5); tree.get(5).push(1); tree.get(2).push(3); tree.get(3).push(2); tree.get(2).push(4); tree.get(4).push(2); tree.get(5).push(6); tree.get(6).push(5); let arr1 = [1, 5, 2, 3, 4, 6]; let arr = arr1; if (valid_bfs(arr)) document.write("Yes"); else document.write("No"); // This code is contributed by divyeshrabadiya07.</script> No Time complexity: O(N * log N)Similar articles: Check if the given permutation is a valid DFS of graph princi singh rutvik_56 divyeshrabadiya07 BFS cpp-map permutation tree-traversal Algorithms Arrays Queue Tree Arrays permutation Queue Tree BFS Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar K means Clustering - Introduction SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing Difference between Informed and Uninformed Search in AI Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24610, "s": 24582, "text": "\n22 Jun, 2021" }, { "code": null, "e": 24878, "s": 24610, "text": "Given a tree with N nodes numbered from 1 to N and a permutation array of numbers from 1 to N. Check if it is possible to obtain the given permutation array by applying BFS (Breadth First Traversal) on the given tree.Note: Traversal will always start from 1.Example: " }, { "code": null, "e": 25255, "s": 24878, "text": "Input: arr[] = { 1 5 2 3 4 6 } Edges of the given tree: 1 – 2 1 – 5 2 – 3 2 – 4 5 – 6 Output: No Explanation: There is no such traversal which is same as the given permutation. The valid traversals are: 1 2 5 3 4 6 1 2 5 4 3 6 1 5 2 6 3 4 1 5 2 6 4 3Input: arr[] = { 1 2 3 } Edges of the given tree: 1 – 2 2 – 3 Output: Yes Explanation: The given permutation is a valid one. " }, { "code": null, "e": 25344, "s": 25255, "text": "Approach: To solve the problem mentioned above we have to follow the steps given below: " }, { "code": null, "e": 25498, "s": 25344, "text": "In BFS we visit all the neighbors of the current node and push their children in the queue in order and repeat this process until the queue is not empty." }, { "code": null, "e": 25728, "s": 25498, "text": "Suppose there are two children of root: A and B. We are free to choose which of them to visit first. Let’s say we visit A first, but now we will have to push children of A in the queue, and we cannot visit children of B before A." }, { "code": null, "e": 25991, "s": 25728, "text": "So basically we can visit the children of a particular node in any order but the order in which the children of 2 different nodes should be visited is fixed i.e. if A if visited before B, then all the children of A should be visited before all the children of B." }, { "code": null, "e": 26282, "s": 25991, "text": "We will do the same. We will make a queue of sets and in each set, we will push the children of a particular node and traverse the permutation alongside. If the current element of permutation is found in the set at the top of the queue, then we will proceed otherwise, we will return false." }, { "code": null, "e": 26334, "s": 26282, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26338, "s": 26334, "text": "C++" }, { "code": null, "e": 26343, "s": 26338, "text": "Java" }, { "code": null, "e": 26351, "s": 26343, "text": "Python3" }, { "code": null, "e": 26354, "s": 26351, "text": "C#" }, { "code": null, "e": 26365, "s": 26354, "text": "Javascript" }, { "code": "// C++ implementation to check if the// given permutation is a valid// BFS of a given tree#include <bits/stdc++.h>using namespace std; // map for storing the treemap<int, vector<int> > tree; // map for marking// the nodes visitedmap<int, int> vis; // Function to check if// permutation is validbool valid_bfs(vector<int>& v){ int n = (int)v.size(); queue<set<int> > q; set<int> s; s.insert(1); /*inserting the root in the front of queue.*/ q.push(s); int i = 0; while (!q.empty() && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.count(v[i])) { return 0; } vis[v[i]] = 1; // if all the children of previous // nodes are visited then pop the // front element of queue. if (q.front().size() == 0) { q.pop(); } // if the current element of the // permutation is not found // in the set at the top of queue // then return false if (q.front().find(v[i]) == q.front().end()) { return 0; } s.clear(); // push all the children of current // node in a set and then push // the set in the queue. for (auto j : tree[v[i]]) { if (vis.count(j)) { continue; } s.insert(j); } if (s.size() > 0) { set<int> temp = s; q.push(temp); } s.clear(); // erase the current node from // the set at the top of queue q.front().erase(v[i]); // increment the index // of permutation i++; } return 1;} // Driver codeint main(){ tree[1].push_back(2); tree[2].push_back(1); tree[1].push_back(5); tree[5].push_back(1); tree[2].push_back(3); tree[3].push_back(2); tree[2].push_back(4); tree[4].push_back(2); tree[5].push_back(6); tree[6].push_back(5); vector<int> arr = { 1, 5, 2, 3, 4, 6 }; if (valid_bfs(arr)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;} // This code is contributed by rutvik_56", "e": 28572, "s": 26365, "text": null }, { "code": "// Java implementation to check if the// given permutation is a valid// BFS of a given treeimport java.util.*;class GFG{ // Map for storing the treestatic HashMap<Integer, Vector<Integer> > tree = new HashMap<>(); // Map for marking// the nodes visitedstatic HashMap<Integer, Integer> vis = new HashMap<>(); // Function to check if// permutation is validstatic boolean valid_bfs(List<Integer> v){ int n = (int)v.size(); Queue<HashSet<Integer> > q = new LinkedList<>(); HashSet<Integer> s = new HashSet<>(); s.add(1); // Inserting the root in // the front of queue. q.add(s); int i = 0; while (!q.isEmpty() && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.containsKey(v.get(i))) { return false; } vis.put(v.get(i), 1); // If all the children of previous // nodes are visited then pop the // front element of queue. if (q.peek().size() == 0) { q.remove(); } // If the current element of the // permutation is not found // in the set at the top of queue // then return false if (!q.peek().contains(v.get(i))) { return false; } s.clear(); // Push all the children of current // node in a set and then push // the set in the queue. for (int j : tree.get(v.get(i))) { if (vis.containsKey(j)) { continue; } s.add(j); } if (s.size() > 0) { HashSet<Integer> temp = s; q.add(temp); } s.clear(); // Erase the current node from // the set at the top of queue q.peek().remove(v.get(i)); // Increment the index // of permutation i++; } return true;} // Driver codepublic static void main(String[] args){ for (int i = 1; i <= 6; i++) { tree.put(i, new Vector<Integer>()); } tree.get(1).add(2); tree.get(2).add(1); tree.get(1).add(5); tree.get(5).add(1); tree.get(2).add(3); tree.get(3).add(2); tree.get(2).add(4); tree.get(4).add(2); tree.get(5).add(6); tree.get(6).add(5); Integer []arr1 = {1, 5, 2, 3, 4, 6}; List<Integer> arr = Arrays.asList(arr1); if (valid_bfs(arr)) System.out.print(\"Yes\" + \"\\n\"); else System.out.print(\"No\" + \"\\n\");}} // This code is contributed by Princi Singh", "e": 30899, "s": 28572, "text": null }, { "code": "# Python3 implementation to check if the# given permutation is a valid# BFS of a given tree # map for storing the treetree=dict() # map for marking# the nodes visitedvis=dict() # Function to check if# permutation is validdef valid_bfs( v): n = len(v) q=[] s=set() s.add(1); '''inserting the root in the front of queue.''' q.append(s); i = 0; while (len(q)!=0 and i < n): # If the current node # in a permutation # is already visited # then return false if (v[i] in vis): return 0; vis[v[i]] = 1; # if all the children of previous # nodes are visited then pop the # front element of queue. if (len(q[0])== 0): q.pop(0); # if the current element of the # permutation is not found # in the set at the top of queue # then return false if (v[i] not in q[0]): return 0; s.clear(); # append all the children of current # node in a set and then append # the set in the queue. for j in tree[v[i]]: if (j in vis): continue; s.add(j); if (len(s) > 0): temp = s; q.append(temp); s.clear(); # erase the current node from # the set at the top of queue q[0].discard(v[i]); # increment the index # of permutation i+=1 return 1; # Driver codeif __name__==\"__main__\": tree[1]=[] tree[2]=[] tree[5]=[] tree[3]=[] tree[2]=[] tree[4]=[] tree[6]=[] tree[1].append(2); tree[2].append(1); tree[1].append(5); tree[5].append(1); tree[2].append(3); tree[3].append(2); tree[2].append(4); tree[4].append(2); tree[5].append(6); tree[6].append(5); arr = [ 1, 5, 2, 3, 4, 6 ] if (valid_bfs(arr)): print(\"Yes\") else: print(\"No\")", "e": 32893, "s": 30899, "text": null }, { "code": "// C# implementation to check// if the given permutation// is a valid BFS of a given treeusing System;using System.Collections.Generic;class GFG{ // Map for storing the treestatic Dictionary<int, List<int>> tree = new Dictionary<int, List<int>>(); // Map for marking// the nodes visitedstatic Dictionary<int, int> vis = new Dictionary<int, int>(); // Function to check if// permutation is validstatic bool valid_bfs(List<int> v){ int n = (int)v.Count; Queue<HashSet<int>> q = new Queue<HashSet<int>>(); HashSet<int> s = new HashSet<int>(); s.Add(1); // Inserting the root in // the front of queue. q.Enqueue(s); int i = 0; while (q.Count != 0 && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.ContainsKey(v[i])) { return false; } vis.Add(v[i], 1); // If all the children of previous // nodes are visited then pop the // front element of queue. if (q.Peek().Count == 0) { q.Dequeue(); } // If the current element of the // permutation is not found // in the set at the top of queue // then return false if (!q.Peek().Contains(v[i])) { return false; } s.Clear(); // Push all the children of current // node in a set and then push // the set in the queue. foreach (int j in tree[v[i]]) { if (vis.ContainsKey(j)) { continue; } s.Add(j); } if (s.Count > 0) { HashSet<int> temp = s; q.Enqueue(temp); } s.Clear(); // Erase the current node from // the set at the top of queue q.Peek().Remove(v[i]); // Increment the index // of permutation i++; } return true;} // Driver codepublic static void Main(String[] args){ for (int i = 1; i <= 6; i++) { tree.Add(i, new List<int>()); } tree[1].Add(2); tree[2].Add(1); tree[1].Add(5); tree[5].Add(1); tree[2].Add(3); tree[3].Add(2); tree[2].Add(4); tree[4].Add(2); tree[5].Add(6); tree[6].Add(5); int []arr1 = {1, 5, 2, 3, 4, 6}; List<int> arr = new List<int>(); arr.AddRange(arr1); if (valid_bfs(arr)) Console.Write(\"Yes\" + \"\\n\"); else Console.Write(\"No\" + \"\\n\");}} // This code is contributed by Princi Singh", "e": 35217, "s": 32893, "text": null }, { "code": "<script> // Javascript implementation to check if the // given permutation is a valid // BFS of a given tree // Map for storing the tree let tree = new Map(); // Map for marking // the nodes visited let vis = new Map(); // Function to check if // permutation is valid function valid_bfs(v) { let n = v.length; let q = []; let s = new Set(); s.add(1); // Inserting the root in // the front of queue. q.push(s); let i = 0; while (q.length > 0 && i < n) { // If the current node // in a permutation // is already visited // then return false if (vis.has(v[i])) { return false; } vis.set(v[i], 1); // If all the children of previous // nodes are visited then pop the // front element of queue. if (q[0].length == 0) { q.shift(); } // If the current element of the // permutation is not found // in the set at the top of queue // then return false if (!q[0].has(v[i])) { return false; } s.clear(); // Push all the children of current // node in a set and then push // the set in the queue. for (let j = 0; j < (tree.get(v[i])).length; j++) { if (vis.has((tree.get(v[i]))[j])) { continue; } s.add((tree.get(v[i]))[j]); } if (s.size > 0) { let temp = s; q.push(temp); } s.clear(); // Erase the current node from // the set at the top of queue q[0].delete(v[i]); // Increment the index // of permutation i++; } return true; } for (let i = 1; i <= 6; i++) { tree.set(i, []); } tree.get(1).push(2); tree.get(2).push(1); tree.get(1).push(5); tree.get(5).push(1); tree.get(2).push(3); tree.get(3).push(2); tree.get(2).push(4); tree.get(4).push(2); tree.get(5).push(6); tree.get(6).push(5); let arr1 = [1, 5, 2, 3, 4, 6]; let arr = arr1; if (valid_bfs(arr)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by divyeshrabadiya07.</script>", "e": 37521, "s": 35217, "text": null }, { "code": null, "e": 37524, "s": 37521, "text": "No" }, { "code": null, "e": 37628, "s": 37526, "text": "Time complexity: O(N * log N)Similar articles: Check if the given permutation is a valid DFS of graph" }, { "code": null, "e": 37641, "s": 37628, "text": "princi singh" }, { "code": null, "e": 37651, "s": 37641, "text": "rutvik_56" }, { "code": null, "e": 37669, "s": 37651, "text": "divyeshrabadiya07" }, { "code": null, "e": 37673, "s": 37669, "text": "BFS" }, { "code": null, "e": 37681, "s": 37673, "text": "cpp-map" }, { "code": null, "e": 37693, "s": 37681, "text": "permutation" }, { "code": null, "e": 37708, "s": 37693, "text": "tree-traversal" }, { "code": null, "e": 37719, "s": 37708, "text": "Algorithms" }, { "code": null, "e": 37726, "s": 37719, "text": "Arrays" }, { "code": null, "e": 37732, "s": 37726, "text": "Queue" }, { "code": null, "e": 37737, "s": 37732, "text": "Tree" }, { "code": null, "e": 37744, "s": 37737, "text": "Arrays" }, { "code": null, "e": 37756, "s": 37744, "text": "permutation" }, { "code": null, "e": 37762, "s": 37756, "text": "Queue" }, { "code": null, "e": 37767, "s": 37762, "text": "Tree" }, { "code": null, "e": 37771, "s": 37767, "text": "BFS" }, { "code": null, "e": 37782, "s": 37771, "text": "Algorithms" }, { "code": null, "e": 37880, "s": 37782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37889, "s": 37880, "text": "Comments" }, { "code": null, "e": 37902, "s": 37889, "text": "Old Comments" }, { "code": null, "e": 37927, "s": 37902, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37961, "s": 37927, "text": "K means Clustering - Introduction" }, { "code": null, "e": 38004, "s": 37961, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 38033, "s": 38004, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 38089, "s": 38033, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 38104, "s": 38089, "text": "Arrays in Java" }, { "code": null, "e": 38120, "s": 38104, "text": "Arrays in C/C++" }, { "code": null, "e": 38147, "s": 38120, "text": "Program for array rotation" }, { "code": null, "e": 38195, "s": 38147, "text": "Stack Data Structure (Introduction and Program)" } ]
JSF - Environment Setup
This chapter will guide you on how to prepare a development environment to start your work with JSF Framework. You will learn how to setup JDK, Eclipse, Maven, and Tomcat on your machine before you set up JSF Framework. JSF requires JDK 1.5 or higher so the very first requirement is to have JDK installed on your machine. Follow the given steps to setup your environment to start with JSF application development. Open console and execute the following Java command. Let's verify the output for all the operating systems − java version "1.6.0_21" Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) java version "1.6.0_21" Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) java version "1.6.0_21" Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing) If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example − Append Java compiler location to System Path. Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. Otherwise, carry out a proper setup according to the given document of the IDE. All the examples in this tutorial have been written using Eclipse IDE. Hence, we suggest you should have the latest version of Eclipse installed on your machine based on your operating system. To install Eclipse IDE, download the latest Eclipse binaries with WTP support from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it will display the following result. *Note − Install m2eclipse plugin to eclipse using the following eclipse software update site m2eclipse Plugin - https://m2eclipse.sonatype.org/update/. This plugin enables the developers to run maven commands within eclipse with embedded/external maven installation. Download Maven 2.2.1 from https://maven.apache.org/download.html Extract the archive to the directory you wish to install Maven 2.2.1. The subdirectory apache-maven-2.2.1 will be created from the archive. Add M2_HOME, M2, MAVEN_OPTS to environment variables. Set the environment variables using system properties. M2_HOME=C:\Program Files\Apache Software Foundation\apachemaven-2.2.1 M2=%M2_HOME%\bin MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1 export M2=%M2_HOME%\bin export MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1 export M2=%M2_HOME%\bin export MAVEN_OPTS=-Xms256m -Xmx512m Now append M2 variable to System Path. Open console, execute the following mvn command. Finally, verify the output of the above commands, which should be as shown in the following table. Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Java version: 1.6.0_21 Java home: C:\Program Files\Java\jdk1.6.0_21\jre Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Java version: 1.6.0_21 Java home: C:\Program Files\Java\jdk1.6.0_21\jre Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Java version: 1.6.0_21 Java home: C:\Program Files\Java\jdk1.6.0_21\jre You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-6.0.33 on Windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations. Tomcat can be started by executing the following commands on Windows machine, or you can simply double-click on startup.bat %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-6.0.33\bin\startup.bat Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine. $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-6.0.33/bin/startup.sh After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it will display the following result. Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org Tomcat can be stopped by executing the following commands on Windows machine. %CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-5.5.29\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine. $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2172, "s": 1952, "text": "This chapter will guide you on how to prepare a development environment to start your work with JSF Framework. You will learn how to setup JDK, Eclipse, Maven, and Tomcat on your machine before you set up JSF Framework." }, { "code": null, "e": 2275, "s": 2172, "text": "JSF requires JDK 1.5 or higher so the very first requirement is to have JDK installed on your machine." }, { "code": null, "e": 2367, "s": 2275, "text": "Follow the given steps to setup your environment to start with JSF application development." }, { "code": null, "e": 2420, "s": 2367, "text": "Open console and execute the following Java command." }, { "code": null, "e": 2476, "s": 2420, "text": "Let's verify the output for all the operating systems −" }, { "code": null, "e": 2500, "s": 2476, "text": "java version \"1.6.0_21\"" }, { "code": null, "e": 2553, "s": 2500, "text": "Java(TM) SE Runtime Environment (build 1.6.0_21-b07)" }, { "code": null, "e": 2618, "s": 2553, "text": "Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)" }, { "code": null, "e": 2642, "s": 2618, "text": "java version \"1.6.0_21\"" }, { "code": null, "e": 2695, "s": 2642, "text": "Java(TM) SE Runtime Environment (build 1.6.0_21-b07)" }, { "code": null, "e": 2760, "s": 2695, "text": "Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)" }, { "code": null, "e": 2784, "s": 2760, "text": "java version \"1.6.0_21\"" }, { "code": null, "e": 2837, "s": 2784, "text": "Java(TM) SE Runtime Environment (build 1.6.0_21-b07)" }, { "code": null, "e": 2908, "s": 2837, "text": "Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)" }, { "code": null, "e": 3357, "s": 2908, "text": "If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 3477, "s": 3357, "text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine." }, { "code": null, "e": 3491, "s": 3477, "text": "For example −" }, { "code": null, "e": 3537, "s": 3491, "text": "Append Java compiler location to System Path." }, { "code": null, "e": 3842, "s": 3537, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. Otherwise, carry out a proper setup according to the given document of the IDE." }, { "code": null, "e": 4035, "s": 3842, "text": "All the examples in this tutorial have been written using Eclipse IDE. Hence, we suggest you should have the latest version of Eclipse installed on your machine based on your operating system." }, { "code": null, "e": 4369, "s": 4035, "text": "To install Eclipse IDE, download the latest Eclipse binaries with WTP support from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately." }, { "code": null, "e": 4494, "s": 4369, "text": "Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe" }, { "code": null, "e": 4519, "s": 4494, "text": "%C:\\eclipse\\eclipse.exe\n" }, { "code": null, "e": 4619, "s": 4519, "text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 4648, "s": 4619, "text": "$/usr/local/eclipse/eclipse\n" }, { "code": null, "e": 4741, "s": 4648, "text": "After a successful startup, if everything is fine then it will display the following result." }, { "code": null, "e": 4834, "s": 4741, "text": "*Note − Install m2eclipse plugin to eclipse using the following eclipse software update site" }, { "code": null, "e": 4893, "s": 4834, "text": "m2eclipse Plugin - https://m2eclipse.sonatype.org/update/." }, { "code": null, "e": 5008, "s": 4893, "text": "This plugin enables the developers to run maven commands within eclipse with embedded/external maven installation." }, { "code": null, "e": 5073, "s": 5008, "text": "Download Maven 2.2.1 from https://maven.apache.org/download.html" }, { "code": null, "e": 5213, "s": 5073, "text": "Extract the archive to the directory you wish to install Maven 2.2.1. The subdirectory apache-maven-2.2.1 will be created from the archive." }, { "code": null, "e": 5267, "s": 5213, "text": "Add M2_HOME, M2, MAVEN_OPTS to environment variables." }, { "code": null, "e": 5322, "s": 5267, "text": "Set the environment variables using system properties." }, { "code": null, "e": 5392, "s": 5322, "text": "M2_HOME=C:\\Program Files\\Apache Software Foundation\\apachemaven-2.2.1" }, { "code": null, "e": 5409, "s": 5392, "text": "M2=%M2_HOME%\\bin" }, { "code": null, "e": 5438, "s": 5409, "text": "MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 5491, "s": 5438, "text": "Open command terminal and set environment variables." }, { "code": null, "e": 5549, "s": 5491, "text": "export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1" }, { "code": null, "e": 5573, "s": 5549, "text": "export M2=%M2_HOME%\\bin" }, { "code": null, "e": 5609, "s": 5573, "text": "export MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 5662, "s": 5609, "text": "Open command terminal and set environment variables." }, { "code": null, "e": 5720, "s": 5662, "text": "export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1" }, { "code": null, "e": 5744, "s": 5720, "text": "export M2=%M2_HOME%\\bin" }, { "code": null, "e": 5780, "s": 5744, "text": "export MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 5819, "s": 5780, "text": "Now append M2 variable to System Path." }, { "code": null, "e": 5868, "s": 5819, "text": "Open console, execute the following mvn command." }, { "code": null, "e": 5967, "s": 5868, "text": "Finally, verify the output of the above commands, which should be as shown in the following table." }, { "code": null, "e": 6022, "s": 5967, "text": "Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)" }, { "code": null, "e": 6045, "s": 6022, "text": "Java version: 1.6.0_21" }, { "code": null, "e": 6095, "s": 6045, "text": "Java home: C:\\Program Files\\Java\\jdk1.6.0_21\\jre " }, { "code": null, "e": 6150, "s": 6095, "text": "Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)" }, { "code": null, "e": 6173, "s": 6150, "text": "Java version: 1.6.0_21" }, { "code": null, "e": 6223, "s": 6173, "text": "Java home: C:\\Program Files\\Java\\jdk1.6.0_21\\jre " }, { "code": null, "e": 6278, "s": 6223, "text": "Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)" }, { "code": null, "e": 6301, "s": 6278, "text": "Java version: 1.6.0_21" }, { "code": null, "e": 6350, "s": 6301, "text": "Java home: C:\\Program Files\\Java\\jdk1.6.0_21\\jre" }, { "code": null, "e": 6708, "s": 6350, "text": "You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\apache-tomcat-6.0.33 on Windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations." }, { "code": null, "e": 6832, "s": 6708, "text": "Tomcat can be started by executing the following commands on Windows machine, or you can simply double-click on startup.bat" }, { "code": null, "e": 6910, "s": 6832, "text": "%CATALINA_HOME%\\bin\\startup.bat \nor \nC:\\apache-tomcat-6.0.33\\bin\\startup.bat\n" }, { "code": null, "e": 7008, "s": 6910, "text": "Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine." }, { "code": null, "e": 7091, "s": 7008, "text": "$CATALINA_HOME/bin/startup.sh \nor \n/usr/local/apache-tomcat-6.0.33/bin/startup.sh\n" }, { "code": null, "e": 7289, "s": 7091, "text": "After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it will display the following result." }, { "code": null, "e": 7456, "s": 7289, "text": "Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org" }, { "code": null, "e": 7534, "s": 7456, "text": "Tomcat can be stopped by executing the following commands on Windows machine." }, { "code": null, "e": 7607, "s": 7534, "text": "%CATALINA_HOME%\\bin\\shutdown \nor \nC:\\apache-tomcat-5.5.29\\bin\\shutdown \n" }, { "code": null, "e": 7705, "s": 7607, "text": "Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine." }, { "code": null, "e": 7790, "s": 7705, "text": "$CATALINA_HOME/bin/shutdown.sh \nor \n/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh\n" }, { "code": null, "e": 7825, "s": 7790, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7840, "s": 7825, "text": " Chaand Sheikh" }, { "code": null, "e": 7847, "s": 7840, "text": " Print" }, { "code": null, "e": 7858, "s": 7847, "text": " Add Notes" } ]
PyQt5 QListWidget – Getting Spacing Between the Items - GeeksforGeeks
06 Aug, 2020 In this article we will see how we can get the space between the item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Spacing property holds the space around the items in the layout. This property is the size of the empty space that is padded around an item in the layout. Setting this property when the view is visible will cause the items to be laid out again. By default, this property contains a value of 0 although it can be changed with the help of setSpacing method. In order to do this we will use spacing method with the list widget object. Syntax : list_widget.spacing() Argument : It takes no argument Return : It returns integer Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting spacing property list_widget.setSpacing(5) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting spacing between the items value = list_widget.spacing() # setting text to the label label.setText("Spacing : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt 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() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24057, "s": 24029, "text": "\n06 Aug, 2020" }, { "code": null, "e": 24710, "s": 24057, "text": "In this article we will see how we can get the space between the item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Spacing property holds the space around the items in the layout. This property is the size of the empty space that is padded around an item in the layout. Setting this property when the view is visible will cause the items to be laid out again. By default, this property contains a value of 0 although it can be changed with the help of setSpacing method." }, { "code": null, "e": 24786, "s": 24710, "text": "In order to do this we will use spacing method with the list widget object." }, { "code": null, "e": 24817, "s": 24786, "text": "Syntax : list_widget.spacing()" }, { "code": null, "e": 24849, "s": 24817, "text": "Argument : It takes no argument" }, { "code": null, "e": 24877, "s": 24849, "text": "Return : It returns integer" }, { "code": null, "e": 24905, "s": 24877, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting spacing property list_widget.setSpacing(5) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting spacing between the items value = list_widget.spacing() # setting text to the label label.setText(\"Spacing : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26478, "s": 24905, "text": null }, { "code": null, "e": 26487, "s": 26478, "text": "Output :" }, { "code": null, "e": 26511, "s": 26487, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 26522, "s": 26511, "text": "Python-gui" }, { "code": null, "e": 26534, "s": 26522, "text": "Python-PyQt" }, { "code": null, "e": 26541, "s": 26534, "text": "Python" }, { "code": null, "e": 26639, "s": 26541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26648, "s": 26639, "text": "Comments" }, { "code": null, "e": 26661, "s": 26648, "text": "Old Comments" }, { "code": null, "e": 26679, "s": 26661, "text": "Python Dictionary" }, { "code": null, "e": 26714, "s": 26679, "text": "Read a file line by line in Python" }, { "code": null, "e": 26736, "s": 26714, "text": "Enumerate() in Python" }, { "code": null, "e": 26768, "s": 26736, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26798, "s": 26768, "text": "Iterate over a list in Python" }, { "code": null, "e": 26840, "s": 26798, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26866, "s": 26840, "text": "Python String | replace()" }, { "code": null, "e": 26909, "s": 26866, "text": "Python program to convert a list to string" }, { "code": null, "e": 26953, "s": 26909, "text": "Reading and Writing to text files in Python" } ]
How to detect user inactivity for 5 seconds in Android?
This example demonstrates how to detect user inactivity for 5 seconds 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"?> <androidx.constraintlayout.widget.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:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Handler handler; Runnable r; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Override public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; startHandler(); } @Override public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler(); startHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void startHandler() { handler.postDelayed(r, 5*1000); } } Step 4 − 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.app.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 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": 1144, "s": 1062, "text": "This example demonstrates how to detect user inactivity for 5 seconds 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": 2097, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\nxmlns: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:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\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</androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 2154, "s": 2097, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3187, "s": 2154, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Handler handler;\n Runnable r;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n handler = new Handler();\n r = new Runnable() {\n @Override\n public void run() {\n // TODO Auto-generated method stub\n Toast.makeText(MainActivity.this, \"user is inactive from last 5 minutes\",Toast.LENGTH_SHORT).show();\n }\n };\n startHandler();\n }\n @Override\n public void onUserInteraction() {\n // TODO Auto-generated method stub\n super.onUserInteraction();\n stopHandler();\n startHandler();\n }\n public void stopHandler() {\n handler.removeCallbacks(r);\n }\n public void startHandler() {\n handler.postDelayed(r, 5*1000);\n }\n}" }, { "code": null, "e": 3252, "s": 3187, "text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3940, "s": 3252, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.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": 4291, "s": 3940, "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": 4332, "s": 4291, "text": "Click here to download the project code." } ]
How to process Arrays in Java?
To process array elements, we often use either for loop or for each loop because all of the elements in an array are of the same type and the size of the array is known. Suppose we have an array of 5 elements we can print all the elements of this array as: Live Demo public class ProcessingArrays { public static void main(String args[]) { int myArray[] = {22, 23, 25, 27, 30}; for(int i = 0; i<myArray.length; i++) { System.out.println(myArray[i]); } } } 22 23 25 27 30
[ { "code": null, "e": 1319, "s": 1062, "text": "To process array elements, we often use either for loop or for each loop because all of the elements in an array are of the same type and the size of the array is known. Suppose we have an array of 5 elements we can print all the elements of this array as:" }, { "code": null, "e": 1329, "s": 1319, "text": "Live Demo" }, { "code": null, "e": 1552, "s": 1329, "text": "public class ProcessingArrays {\n public static void main(String args[]) {\n int myArray[] = {22, 23, 25, 27, 30};\n\n for(int i = 0; i<myArray.length; i++) {\n System.out.println(myArray[i]);\n }\n }\n}" }, { "code": null, "e": 1567, "s": 1552, "text": "22\n23\n25\n27\n30" } ]
Keras - Layers
As learned earlier, Keras layers are the primary building block of Keras models. Each layer receives input information, do some computation and finally output the transformed information. The output of one layer will flow into the next layer as its input. Let us learn complete details about layers in this chapter. A Keras layer requires shape of the input (input_shape) to understand the structure of the input data, initializer to set the weight for each input and finally activators to transform the output to make it non-linear. In between, constraints restricts and specify the range in which the weight of input data to be generated and regularizer will try to optimize the layer (and the model) by dynamically applying the penalties on the weights during optimization process. To summarise, Keras layer requires below minimum details to create a complete layer. Shape of the input data Number of neurons / units in the layer Initializers Regularizers Constraints Activations Let us understand the basic concept in the next chapter. Before understanding the basic concept, let us create a simple Keras layer using Sequential model API to get the idea of how Keras model and layer works. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers from keras import regularizers from keras import constraints model = Sequential() model.add(Dense(32, input_shape=(16,), kernel_initializer = 'he_uniform', kernel_regularizer = None, kernel_constraint = 'MaxNorm', activation = 'relu')) model.add(Dense(16, activation = 'relu')) model.add(Dense(8)) where, Line 1-5 imports the necessary modules. Line 1-5 imports the necessary modules. Line 7 creates a new model using Sequential API. Line 7 creates a new model using Sequential API. Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional. First parameter represents the number of units (neurons). input_shape represent the shape of input data. kernel_initializer represent initializer to be used. he_uniform function is set as value. kernel_regularizer represent regularizer to be used. None is set as value. kernel_constraint represent constraint to be used. MaxNorm function is set as value. activation represent activation to be used. relu function is set as value. Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional. First parameter represents the number of units (neurons). First parameter represents the number of units (neurons). input_shape represent the shape of input data. input_shape represent the shape of input data. kernel_initializer represent initializer to be used. he_uniform function is set as value. kernel_initializer represent initializer to be used. he_uniform function is set as value. kernel_regularizer represent regularizer to be used. None is set as value. kernel_regularizer represent regularizer to be used. None is set as value. kernel_constraint represent constraint to be used. MaxNorm function is set as value. kernel_constraint represent constraint to be used. MaxNorm function is set as value. activation represent activation to be used. relu function is set as value. activation represent activation to be used. relu function is set as value. Line 10 creates second Dense layer with 16 units and set relu as the activation function. Line 10 creates second Dense layer with 16 units and set relu as the activation function. Line 11 creates final Dense layer with 8 units. Line 11 creates final Dense layer with 8 units. Let us understand the basic concept of layer as well as how Keras supports each concept. In machine learning, all type of input data like text, images or videos will be first converted into array of numbers and then feed into the algorithm. Input numbers may be single dimensional array, two dimensional array (matrix) or multi-dimensional array. We can specify the dimensional information using shape, a tuple of integers. For example, (4,2) represent matrix with four rows and two columns. >>> import numpy as np >>> shape = (4, 2) >>> input = np.zeros(shape) >>> print(input) [ [0. 0.] [0. 0.] [0. 0.] [0. 0.] ] >>> Similarly, (3,4,2) three dimensional matrix having three collections of 4x2 matrix (two rows and four columns). >>> import numpy as np >>> shape = (3, 4, 2) >>> input = np.zeros(shape) >>> print(input) [ [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] ] >>> To create the first layer of the model (or input layer of the model), shape of the input data should be specified. In Machine Learning, weight will be assigned to all input data. Initializers module provides different functions to set these initial weight. Some of the Keras Initializer function are as follows − Generates 0 for all input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Zeros() model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) Where, kernel_initializer represent the initializer for kernel of the model. Generates 1 for all input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Ones() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) Generates a constant value (say, 5) specified by the user for all input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Constant(value = 0) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) where, value represent the constant value Generates value using normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.RandomNormal(mean=0.0, stddev = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) where, mean represent the mean of the random values to generate mean represent the mean of the random values to generate stddev represent the standard deviation of the random values to generate stddev represent the standard deviation of the random values to generate seed represent the values to generate random number seed represent the values to generate random number Generates value using uniform distribution of input data. from keras import initializers my_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) where, minval represent the lower bound of the random values to generate minval represent the lower bound of the random values to generate maxval represent the upper bound of the random values to generate maxval represent the upper bound of the random values to generate Generates value using truncated normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.TruncatedNormal(mean = 0.0, stddev = 0.05, seed = None model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) Generates value based on the input shape and output shape of the layer along with the specified scale. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.VarianceScaling( scale = 1.0, mode = 'fan_in', distribution = 'normal', seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), skernel_initializer = my_init)) where, scale represent the scaling factor scale represent the scaling factor mode represent any one of fan_in, fan_out and fan_avg values mode represent any one of fan_in, fan_out and fan_avg values distribution represent either of normal or uniform distribution represent either of normal or uniform It finds the stddev value for normal distribution using below formula and then find the weights using normal distribution, stddev = sqrt(scale / n) where n represent, number of input units for mode = fan_in number of input units for mode = fan_in number of out units for mode = fan_out number of out units for mode = fan_out average number of input and output units for mode = fan_avg average number of input and output units for mode = fan_avg Similarly, it finds the limit for uniform distribution using below formula and then find the weights using uniform distribution, limit = sqrt(3 * scale / n) Generates value using lecun normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the stddev using the below formula and then apply normal distribution stddev = sqrt(1 / fan_in) where, fan_in represent the number of input units. Generates value using lecun uniform distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.lecun_uniform(seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the limit using the below formula and then apply uniform distribution limit = sqrt(3 / fan_in) where, fan_in represents the number of input units fan_in represents the number of input units fan_out represents the number of output units fan_out represents the number of output units Generates value using glorot normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.glorot_normal(seed=None) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) It finds the stddev using the below formula and then apply normal distribution stddev = sqrt(2 / (fan_in + fan_out)) where, fan_in represents the number of input units fan_in represents the number of input units fan_out represents the number of output units fan_out represents the number of output units Generates value using glorot uniform distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.glorot_uniform(seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the limit using the below formula and then apply uniform distribution limit = sqrt(6 / (fan_in + fan_out)) where, fan_in represent the number of input units. fan_in represent the number of input units. fan_out represents the number of output units fan_out represents the number of output units Generates value using he normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the stddev using the below formula and then apply normal distribution. stddev = sqrt(2 / fan_in) where, fan_in represent the number of input units. Generates value using he uniform distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.he_normal(seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the limit using the below formula and then apply uniform distribution. limit = sqrt(6 / fan_in) where, fan_in represent the number of input units. Generates a random orthogonal matrix. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Orthogonal(gain = 1.0, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) where, gain represent the multiplication factor of the matrix. Generates identity matrix. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Identity(gain = 1.0) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) In machine learning, a constraint will be set on the parameter (weight) during optimization phase. <>Constraints module provides different functions to set the constraint on the layer. Some of the constraint functions are as follows. Constrains weights to be non-negative. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Identity(gain = 1.0) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) where, kernel_constraint represent the constraint to be used in the layer. Constrains weights to be unit norm. from keras.models import Sequential from keras.layers import Activation, Dense from keras import constraints my_constrain = constraints.UnitNorm(axis = 0) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_constraint = my_constrain)) Constrains weight to norm less than or equals to the given value. from keras.models import Sequential from keras.layers import Activation, Dense from keras import constraints my_constrain = constraints.MaxNorm(max_value = 2, axis = 0) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_constraint = my_constrain)) where, max_value represent the upper bound max_value represent the upper bound axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension Constrains weights to be norm between specified minimum and maximum values. from keras.models import Sequential from keras.layers import Activation, Dense from keras import constraints my_constrain = constraints.MinMaxNorm(min_value = 0.0, max_value = 1.0, rate = 1.0, axis = 0) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_constraint = my_constrain)) where, rate represent the rate at which the weight constrain is applied. In machine learning, regularizers are used in the optimization phase. It applies some penalties on the layer parameter during optimization. Keras regularization module provides below functions to set penalties on the layer. Regularization applies per-layer basis only. It provides L1 based regularization. from keras.models import Sequential from keras.layers import Activation, Dense from keras import regularizers my_regularizer = regularizers.l1(0.) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_regularizer = my_regularizer)) where, kernel_regularizer represent the rate at which the weight constrain is applied. It provides L2 based regularization. from keras.models import Sequential from keras.layers import Activation, Dense from keras import regularizers my_regularizer = regularizers.l2(0.) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_regularizer = my_regularizer)) It provides both L1 and L2 based regularization. from keras.models import Sequential from keras.layers import Activation, Dense from keras import regularizers my_regularizer = regularizers.l2(0.) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_regularizer = my_regularizer)) In machine learning, activation function is a special function used to find whether a specific neuron is activated or not. Basically, the activation function does a nonlinear transformation of the input data and thus enable the neurons to learn better. Output of a neuron depends on the activation function. As you recall the concept of single perception, the output of a perceptron (neuron) is simply the result of the activation function, which accepts the summation of all input multiplied with its corresponding weight plus overall bias, if any available. result = Activation(SUMOF(input * weight) + bias) So, activation function plays an important role in the successful learning of the model. Keras provides a lot of activation function in the activations module. Let us learn all the activations available in the module. Applies Linear function. Does nothing. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'linear', input_shape = (784,))) Where, activation refers the activation function of the layer. It can be specified simply by the name of the function and the layer will use corresponding activators. Applies Exponential linear unit. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'elu', input_shape = (784,))) Applies Scaled exponential linear unit. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'selu', input_shape = (784,))) Applies Rectified Linear Unit. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) Applies Softmax function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'softmax', input_shape = (784,))) Applies Softplus function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'softplus', input_shape = (784,))) Applies Softsign function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'softsign', input_shape = (784,))) Applies Hyperbolic tangent function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'tanh', input_shape = (784,))) Applies Sigmoid function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'sigmoid', input_shape = (784,))) Applies Hard Sigmoid function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'hard_sigmoid', input_shape = (784,))) Applies exponential function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'exponential', input_shape = (784,))) Dense Layer Dense layer is the regular deeply connected neural network layer. Dropout Layers Dropout is one of the important concept in the machine learning. Flatten Layers Flatten is used to flatten the input. Reshape Layers Reshape is used to change the shape of the input. Permute Layers Permute is also used to change the shape of the input using pattern. RepeatVector Layers RepeatVector is used to repeat the input for set number, n of times. Lambda Layers Lambda is used to transform the input data using an expression or function. Convolution Layers Keras contains a lot of layers for creating Convolution based ANN, popularly called as Convolution Neural Network (CNN). Pooling Layer It is used to perform max pooling operations on temporal data. Locally connected layer Locally connected layers are similar to Conv1D layer but the difference is Conv1D layer weights are shared but here weights are unshared. Merge Layer It is used to merge a list of inputs. Embedding Layer It performs embedding operations in input layer. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2367, "s": 2051, "text": "As learned earlier, Keras layers are the primary building block of Keras models. Each layer receives input information, do some computation and finally output the transformed information. The output of one layer will flow into the next layer as its input. Let us learn complete details about layers in this chapter." }, { "code": null, "e": 2836, "s": 2367, "text": "A Keras layer requires shape of the input (input_shape) to understand the structure of the input data, initializer to set the weight for each input and finally activators to transform the output to make it non-linear. In between, constraints restricts and specify the range in which the weight of input data to be generated and regularizer will try to optimize the layer (and the model) by dynamically applying the penalties on the weights during optimization process." }, { "code": null, "e": 2921, "s": 2836, "text": "To summarise, Keras layer requires below minimum details to create a complete layer." }, { "code": null, "e": 2945, "s": 2921, "text": "Shape of the input data" }, { "code": null, "e": 2984, "s": 2945, "text": "Number of neurons / units in the layer" }, { "code": null, "e": 2997, "s": 2984, "text": "Initializers" }, { "code": null, "e": 3010, "s": 2997, "text": "Regularizers" }, { "code": null, "e": 3022, "s": 3010, "text": "Constraints" }, { "code": null, "e": 3034, "s": 3022, "text": "Activations" }, { "code": null, "e": 3245, "s": 3034, "text": "Let us understand the basic concept in the next chapter. Before understanding the basic concept, let us create a simple Keras layer using Sequential model API to get the idea of how Keras model and layer works." }, { "code": null, "e": 3667, "s": 3245, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \nfrom keras import regularizers \nfrom keras import constraints \n\nmodel = Sequential() \n\nmodel.add(Dense(32, input_shape=(16,), kernel_initializer = 'he_uniform', \n kernel_regularizer = None, kernel_constraint = 'MaxNorm', activation = 'relu')) \nmodel.add(Dense(16, activation = 'relu')) \nmodel.add(Dense(8))" }, { "code": null, "e": 3674, "s": 3667, "text": "where," }, { "code": null, "e": 3714, "s": 3674, "text": "Line 1-5 imports the necessary modules." }, { "code": null, "e": 3754, "s": 3714, "text": "Line 1-5 imports the necessary modules." }, { "code": null, "e": 3803, "s": 3754, "text": "Line 7 creates a new model using Sequential API." }, { "code": null, "e": 3852, "s": 3803, "text": "Line 7 creates a new model using Sequential API." }, { "code": null, "e": 4672, "s": 3852, "text": "Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional.\n\nFirst parameter represents the number of units (neurons).\ninput_shape represent the shape of input data.\nkernel_initializer represent initializer to be used. he_uniform function is set as value.\nkernel_regularizer represent regularizer to be used. None is set as value.\nkernel_constraint represent constraint to be used. MaxNorm function is set as value.\nactivation represent activation to be used. relu function is set as value.\n\n" }, { "code": null, "e": 5059, "s": 4672, "text": "Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional." }, { "code": null, "e": 5117, "s": 5059, "text": "First parameter represents the number of units (neurons)." }, { "code": null, "e": 5175, "s": 5117, "text": "First parameter represents the number of units (neurons)." }, { "code": null, "e": 5222, "s": 5175, "text": "input_shape represent the shape of input data." }, { "code": null, "e": 5269, "s": 5222, "text": "input_shape represent the shape of input data." }, { "code": null, "e": 5359, "s": 5269, "text": "kernel_initializer represent initializer to be used. he_uniform function is set as value." }, { "code": null, "e": 5449, "s": 5359, "text": "kernel_initializer represent initializer to be used. he_uniform function is set as value." }, { "code": null, "e": 5524, "s": 5449, "text": "kernel_regularizer represent regularizer to be used. None is set as value." }, { "code": null, "e": 5599, "s": 5524, "text": "kernel_regularizer represent regularizer to be used. None is set as value." }, { "code": null, "e": 5684, "s": 5599, "text": "kernel_constraint represent constraint to be used. MaxNorm function is set as value." }, { "code": null, "e": 5769, "s": 5684, "text": "kernel_constraint represent constraint to be used. MaxNorm function is set as value." }, { "code": null, "e": 5844, "s": 5769, "text": "activation represent activation to be used. relu function is set as value." }, { "code": null, "e": 5919, "s": 5844, "text": "activation represent activation to be used. relu function is set as value." }, { "code": null, "e": 6009, "s": 5919, "text": "Line 10 creates second Dense layer with 16 units and set relu as the activation function." }, { "code": null, "e": 6099, "s": 6009, "text": "Line 10 creates second Dense layer with 16 units and set relu as the activation function." }, { "code": null, "e": 6147, "s": 6099, "text": "Line 11 creates final Dense layer with 8 units." }, { "code": null, "e": 6195, "s": 6147, "text": "Line 11 creates final Dense layer with 8 units." }, { "code": null, "e": 6284, "s": 6195, "text": "Let us understand the basic concept of layer as well as how Keras supports each concept." }, { "code": null, "e": 6687, "s": 6284, "text": "In machine learning, all type of input data like text, images or videos will be first converted into array of numbers and then feed into the algorithm. Input numbers may be single dimensional array, two dimensional array (matrix) or multi-dimensional array. We can specify the dimensional information using shape, a tuple of integers. For example, (4,2) represent matrix with four rows and two columns." }, { "code": null, "e": 6834, "s": 6687, "text": ">>> import numpy as np \n>>> shape = (4, 2) \n>>> input = np.zeros(shape) \n>>> print(input) \n[\n [0. 0.] \n [0. 0.] \n [0. 0.] \n [0. 0.]\n] \n>>>" }, { "code": null, "e": 6946, "s": 6834, "text": "Similarly, (3,4,2) three dimensional matrix having three collections of 4x2 matrix (two rows and four columns)." }, { "code": null, "e": 7160, "s": 6946, "text": ">>> import numpy as np \n>>> shape = (3, 4, 2) \n>>> input = np.zeros(shape) \n>>> print(input)\n[\n [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] \n [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] \n [[0. 0.] [0. 0.] [0. 0.] [0. 0.]]\n]\n>>>" }, { "code": null, "e": 7275, "s": 7160, "text": "To create the first layer of the model (or input layer of the model), shape of the input data should be specified." }, { "code": null, "e": 7473, "s": 7275, "text": "In Machine Learning, weight will be assigned to all input data. Initializers module provides different functions to set these initial weight. Some of the Keras Initializer function are as follows −" }, { "code": null, "e": 7505, "s": 7473, "text": "Generates 0 for all input data." }, { "code": null, "e": 7772, "s": 7505, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Zeros() \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 7849, "s": 7772, "text": "Where, kernel_initializer represent the initializer for kernel of the model." }, { "code": null, "e": 7881, "s": 7849, "text": "Generates 1 for all input data." }, { "code": null, "e": 8125, "s": 7881, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Ones() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 8203, "s": 8125, "text": "Generates a constant value (say, 5) specified by the user for all input data." }, { "code": null, "e": 8460, "s": 8203, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Constant(value = 0) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)\n)" }, { "code": null, "e": 8502, "s": 8460, "text": "where, value represent the constant value" }, { "code": null, "e": 8559, "s": 8502, "text": "Generates value using normal distribution of input data." }, { "code": null, "e": 8848, "s": 8559, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.RandomNormal(mean=0.0, \nstddev = 0.05, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 8855, "s": 8848, "text": "where," }, { "code": null, "e": 8912, "s": 8855, "text": "mean represent the mean of the random values to generate" }, { "code": null, "e": 8969, "s": 8912, "text": "mean represent the mean of the random values to generate" }, { "code": null, "e": 9042, "s": 8969, "text": "stddev represent the standard deviation of the random values to generate" }, { "code": null, "e": 9115, "s": 9042, "text": "stddev represent the standard deviation of the random values to generate" }, { "code": null, "e": 9167, "s": 9115, "text": "seed represent the values to generate random number" }, { "code": null, "e": 9219, "s": 9167, "text": "seed represent the values to generate random number" }, { "code": null, "e": 9277, "s": 9219, "text": "Generates value using uniform distribution of input data." }, { "code": null, "e": 9491, "s": 9277, "text": "from keras import initializers \n\nmy_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 9498, "s": 9491, "text": "where," }, { "code": null, "e": 9564, "s": 9498, "text": "minval represent the lower bound of the random values to generate" }, { "code": null, "e": 9630, "s": 9564, "text": "minval represent the lower bound of the random values to generate" }, { "code": null, "e": 9696, "s": 9630, "text": "maxval represent the upper bound of the random values to generate" }, { "code": null, "e": 9762, "s": 9696, "text": "maxval represent the upper bound of the random values to generate" }, { "code": null, "e": 9829, "s": 9762, "text": "Generates value using truncated normal distribution of input data." }, { "code": null, "e": 10120, "s": 9829, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.TruncatedNormal(mean = 0.0, stddev = 0.05, seed = None\nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 10223, "s": 10120, "text": "Generates value based on the input shape and output shape of the layer along with the specified scale." }, { "code": null, "e": 10549, "s": 10223, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.VarianceScaling(\n scale = 1.0, mode = 'fan_in', distribution = 'normal', seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n skernel_initializer = my_init))" }, { "code": null, "e": 10556, "s": 10549, "text": "where," }, { "code": null, "e": 10591, "s": 10556, "text": "scale represent the scaling factor" }, { "code": null, "e": 10626, "s": 10591, "text": "scale represent the scaling factor" }, { "code": null, "e": 10687, "s": 10626, "text": "mode represent any one of fan_in, fan_out and fan_avg values" }, { "code": null, "e": 10748, "s": 10687, "text": "mode represent any one of fan_in, fan_out and fan_avg values" }, { "code": null, "e": 10799, "s": 10748, "text": "distribution represent either of normal or uniform" }, { "code": null, "e": 10850, "s": 10799, "text": "distribution represent either of normal or uniform" }, { "code": null, "e": 10973, "s": 10850, "text": "It finds the stddev value for normal distribution using below formula and then find the weights using normal distribution," }, { "code": null, "e": 10999, "s": 10973, "text": "stddev = sqrt(scale / n)\n" }, { "code": null, "e": 11018, "s": 10999, "text": "where n represent," }, { "code": null, "e": 11058, "s": 11018, "text": "number of input units for mode = fan_in" }, { "code": null, "e": 11098, "s": 11058, "text": "number of input units for mode = fan_in" }, { "code": null, "e": 11137, "s": 11098, "text": "number of out units for mode = fan_out" }, { "code": null, "e": 11176, "s": 11137, "text": "number of out units for mode = fan_out" }, { "code": null, "e": 11236, "s": 11176, "text": "average number of input and output units for mode = fan_avg" }, { "code": null, "e": 11296, "s": 11236, "text": "average number of input and output units for mode = fan_avg" }, { "code": null, "e": 11425, "s": 11296, "text": "Similarly, it finds the limit for uniform distribution using below formula and then find the weights using uniform distribution," }, { "code": null, "e": 11454, "s": 11425, "text": "limit = sqrt(3 * scale / n)\n" }, { "code": null, "e": 11517, "s": 11454, "text": "Generates value using lecun normal distribution of input data." }, { "code": null, "e": 11811, "s": 11517, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None)\nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 11890, "s": 11811, "text": "It finds the stddev using the below formula and then apply normal distribution" }, { "code": null, "e": 11917, "s": 11890, "text": "stddev = sqrt(1 / fan_in)\n" }, { "code": null, "e": 11968, "s": 11917, "text": "where, fan_in represent the number of input units." }, { "code": null, "e": 12032, "s": 11968, "text": "Generates value using lecun uniform distribution of input data." }, { "code": null, "e": 12296, "s": 12032, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.lecun_uniform(seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 12375, "s": 12296, "text": "It finds the limit using the below formula and then apply uniform distribution" }, { "code": null, "e": 12401, "s": 12375, "text": "limit = sqrt(3 / fan_in)\n" }, { "code": null, "e": 12408, "s": 12401, "text": "where," }, { "code": null, "e": 12452, "s": 12408, "text": "fan_in represents the number of input units" }, { "code": null, "e": 12496, "s": 12452, "text": "fan_in represents the number of input units" }, { "code": null, "e": 12542, "s": 12496, "text": "fan_out represents the number of output units" }, { "code": null, "e": 12588, "s": 12542, "text": "fan_out represents the number of output units" }, { "code": null, "e": 12652, "s": 12588, "text": "Generates value using glorot normal distribution of input data." }, { "code": null, "e": 12914, "s": 12652, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.glorot_normal(seed=None) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)\n)" }, { "code": null, "e": 12993, "s": 12914, "text": "It finds the stddev using the below formula and then apply normal distribution" }, { "code": null, "e": 13032, "s": 12993, "text": "stddev = sqrt(2 / (fan_in + fan_out))\n" }, { "code": null, "e": 13039, "s": 13032, "text": "where," }, { "code": null, "e": 13083, "s": 13039, "text": "fan_in represents the number of input units" }, { "code": null, "e": 13127, "s": 13083, "text": "fan_in represents the number of input units" }, { "code": null, "e": 13173, "s": 13127, "text": "fan_out represents the number of output units" }, { "code": null, "e": 13219, "s": 13173, "text": "fan_out represents the number of output units" }, { "code": null, "e": 13284, "s": 13219, "text": "Generates value using glorot uniform distribution of input data." }, { "code": null, "e": 13549, "s": 13284, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.glorot_uniform(seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 13628, "s": 13549, "text": "It finds the limit using the below formula and then apply uniform distribution" }, { "code": null, "e": 13666, "s": 13628, "text": "limit = sqrt(6 / (fan_in + fan_out))\n" }, { "code": null, "e": 13673, "s": 13666, "text": "where," }, { "code": null, "e": 13717, "s": 13673, "text": "fan_in represent the number of input units." }, { "code": null, "e": 13761, "s": 13717, "text": "fan_in represent the number of input units." }, { "code": null, "e": 13807, "s": 13761, "text": "fan_out represents the number of output units" }, { "code": null, "e": 13853, "s": 13807, "text": "fan_out represents the number of output units" }, { "code": null, "e": 13913, "s": 13853, "text": "Generates value using he normal distribution of input data." }, { "code": null, "e": 14208, "s": 13913, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 14288, "s": 14208, "text": "It finds the stddev using the below formula and then apply normal distribution." }, { "code": null, "e": 14315, "s": 14288, "text": "stddev = sqrt(2 / fan_in)\n" }, { "code": null, "e": 14366, "s": 14315, "text": "where, fan_in represent the number of input units." }, { "code": null, "e": 14427, "s": 14366, "text": "Generates value using he uniform distribution of input data." }, { "code": null, "e": 14687, "s": 14427, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.he_normal(seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 14767, "s": 14687, "text": "It finds the limit using the below formula and then apply uniform distribution." }, { "code": null, "e": 14793, "s": 14767, "text": "limit = sqrt(6 / fan_in)\n" }, { "code": null, "e": 14844, "s": 14793, "text": "where, fan_in represent the number of input units." }, { "code": null, "e": 14882, "s": 14844, "text": "Generates a random orthogonal matrix." }, { "code": null, "e": 15155, "s": 14882, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Orthogonal(gain = 1.0, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 15218, "s": 15155, "text": "where, gain represent the multiplication factor of the matrix." }, { "code": null, "e": 15245, "s": 15218, "text": "Generates identity matrix." }, { "code": null, "e": 15503, "s": 15245, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Identity(gain = 1.0) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)\n)" }, { "code": null, "e": 15737, "s": 15503, "text": "In machine learning, a constraint will be set on the parameter (weight) during optimization phase. <>Constraints module provides different functions to set the constraint on the layer. Some of the constraint functions are as follows." }, { "code": null, "e": 15776, "s": 15737, "text": "Constrains weights to be non-negative." }, { "code": null, "e": 16038, "s": 15776, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Identity(gain = 1.0) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init)\n)" }, { "code": null, "e": 16113, "s": 16038, "text": "where, kernel_constraint represent the constraint to be used in the layer." }, { "code": null, "e": 16149, "s": 16113, "text": "Constrains weights to be unit norm." }, { "code": null, "e": 16434, "s": 16149, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import constraints \n\nmy_constrain = constraints.UnitNorm(axis = 0) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_constraint = my_constrain))" }, { "code": null, "e": 16500, "s": 16434, "text": "Constrains weight to norm less than or equals to the given value." }, { "code": null, "e": 16799, "s": 16500, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import constraints \n\nmy_constrain = constraints.MaxNorm(max_value = 2, axis = 0) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_constraint = my_constrain))" }, { "code": null, "e": 16806, "s": 16799, "text": "where," }, { "code": null, "e": 16842, "s": 16806, "text": "max_value represent the upper bound" }, { "code": null, "e": 16878, "s": 16842, "text": "max_value represent the upper bound" }, { "code": null, "e": 17057, "s": 16878, "text": "axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension" }, { "code": null, "e": 17236, "s": 17057, "text": "axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension" }, { "code": null, "e": 17312, "s": 17236, "text": "Constrains weights to be norm between specified minimum and maximum values." }, { "code": null, "e": 17645, "s": 17312, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import constraints \n\nmy_constrain = constraints.MinMaxNorm(min_value = 0.0, max_value = 1.0, rate = 1.0, axis = 0) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_constraint = my_constrain))" }, { "code": null, "e": 17718, "s": 17645, "text": "where, rate represent the rate at which the weight constrain is applied." }, { "code": null, "e": 17987, "s": 17718, "text": "In machine learning, regularizers are used in the optimization phase. It applies some penalties on the layer parameter during optimization. Keras regularization module provides below functions to set penalties on the layer. Regularization applies per-layer basis only." }, { "code": null, "e": 18024, "s": 17987, "text": "It provides L1 based regularization." }, { "code": null, "e": 18305, "s": 18024, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import regularizers \n\nmy_regularizer = regularizers.l1(0.) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_regularizer = my_regularizer))\n" }, { "code": null, "e": 18392, "s": 18305, "text": "where, kernel_regularizer represent the rate at which the weight constrain is applied." }, { "code": null, "e": 18429, "s": 18392, "text": "It provides L2 based regularization." }, { "code": null, "e": 18709, "s": 18429, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import regularizers \n\nmy_regularizer = regularizers.l2(0.) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_regularizer = my_regularizer))" }, { "code": null, "e": 18758, "s": 18709, "text": "It provides both L1 and L2 based regularization." }, { "code": null, "e": 19037, "s": 18758, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import regularizers \n\nmy_regularizer = regularizers.l2(0.) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,),\n kernel_regularizer = my_regularizer))" }, { "code": null, "e": 19345, "s": 19037, "text": "In machine learning, activation function is a special function used to find whether a specific neuron is activated or not. Basically, the activation function does a nonlinear transformation of the input data and thus enable the neurons to learn better. Output of a neuron depends on the activation function." }, { "code": null, "e": 19597, "s": 19345, "text": "As you recall the concept of single perception, the output of a perceptron (neuron) is simply the result of the activation function, which accepts the summation of all input multiplied with its corresponding weight plus overall bias, if any available." }, { "code": null, "e": 19648, "s": 19597, "text": "result = Activation(SUMOF(input * weight) + bias)\n" }, { "code": null, "e": 19866, "s": 19648, "text": "So, activation function plays an important role in the successful learning of the model. Keras provides a lot of activation function in the activations module. Let us learn all the activations available in the module." }, { "code": null, "e": 19905, "s": 19866, "text": "Applies Linear function. Does nothing." }, { "code": null, "e": 20077, "s": 19905, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'linear', input_shape = (784,)))\n" }, { "code": null, "e": 20244, "s": 20077, "text": "Where, activation refers the activation function of the layer. It can be specified simply by the name of the function and the layer will use corresponding activators." }, { "code": null, "e": 20277, "s": 20244, "text": "Applies Exponential linear unit." }, { "code": null, "e": 20445, "s": 20277, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'elu', input_shape = (784,)))" }, { "code": null, "e": 20485, "s": 20445, "text": "Applies Scaled exponential linear unit." }, { "code": null, "e": 20654, "s": 20485, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'selu', input_shape = (784,)))" }, { "code": null, "e": 20685, "s": 20654, "text": "Applies Rectified Linear Unit." }, { "code": null, "e": 20854, "s": 20685, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,)))" }, { "code": null, "e": 20880, "s": 20854, "text": "Applies Softmax function." }, { "code": null, "e": 21052, "s": 20880, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'softmax', input_shape = (784,)))" }, { "code": null, "e": 21079, "s": 21052, "text": "Applies Softplus function." }, { "code": null, "e": 21252, "s": 21079, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'softplus', input_shape = (784,)))" }, { "code": null, "e": 21279, "s": 21252, "text": "Applies Softsign function." }, { "code": null, "e": 21452, "s": 21279, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'softsign', input_shape = (784,)))" }, { "code": null, "e": 21489, "s": 21452, "text": "Applies Hyperbolic tangent function." }, { "code": null, "e": 21657, "s": 21489, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'tanh', input_shape = (784,)))" }, { "code": null, "e": 21683, "s": 21657, "text": "Applies Sigmoid function." }, { "code": null, "e": 21855, "s": 21683, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'sigmoid', input_shape = (784,)))" }, { "code": null, "e": 21886, "s": 21855, "text": "Applies Hard Sigmoid function." }, { "code": null, "e": 22063, "s": 21886, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'hard_sigmoid', input_shape = (784,)))" }, { "code": null, "e": 22093, "s": 22063, "text": "Applies exponential function." }, { "code": null, "e": 22269, "s": 22093, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'exponential', input_shape = (784,)))" }, { "code": null, "e": 22281, "s": 22269, "text": "Dense Layer" }, { "code": null, "e": 22347, "s": 22281, "text": "Dense layer is the regular deeply connected neural network layer." }, { "code": null, "e": 22362, "s": 22347, "text": "Dropout Layers" }, { "code": null, "e": 22427, "s": 22362, "text": "Dropout is one of the important concept in the machine learning." }, { "code": null, "e": 22442, "s": 22427, "text": "Flatten Layers" }, { "code": null, "e": 22480, "s": 22442, "text": "Flatten is used to flatten the input." }, { "code": null, "e": 22495, "s": 22480, "text": "Reshape Layers" }, { "code": null, "e": 22545, "s": 22495, "text": "Reshape is used to change the shape of the input." }, { "code": null, "e": 22560, "s": 22545, "text": "Permute Layers" }, { "code": null, "e": 22629, "s": 22560, "text": "Permute is also used to change the shape of the input using pattern." }, { "code": null, "e": 22649, "s": 22629, "text": "RepeatVector Layers" }, { "code": null, "e": 22718, "s": 22649, "text": "RepeatVector is used to repeat the input for set number, n of times." }, { "code": null, "e": 22732, "s": 22718, "text": "Lambda Layers" }, { "code": null, "e": 22808, "s": 22732, "text": "Lambda is used to transform the input data using an expression or function." }, { "code": null, "e": 22827, "s": 22808, "text": "Convolution Layers" }, { "code": null, "e": 22948, "s": 22827, "text": "Keras contains a lot of layers for creating Convolution based ANN, popularly called as Convolution Neural Network (CNN)." }, { "code": null, "e": 22962, "s": 22948, "text": "Pooling Layer" }, { "code": null, "e": 23025, "s": 22962, "text": "It is used to perform max pooling operations on temporal data." }, { "code": null, "e": 23049, "s": 23025, "text": "Locally connected layer" }, { "code": null, "e": 23187, "s": 23049, "text": "Locally connected layers are similar to Conv1D layer but the difference is Conv1D layer weights are shared but here weights are unshared." }, { "code": null, "e": 23199, "s": 23187, "text": "Merge Layer" }, { "code": null, "e": 23237, "s": 23199, "text": "It is used to merge a list of inputs." }, { "code": null, "e": 23253, "s": 23237, "text": "Embedding Layer" }, { "code": null, "e": 23302, "s": 23253, "text": "It performs embedding operations in input layer." }, { "code": null, "e": 23336, "s": 23302, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 23353, "s": 23336, "text": " Abhilash Nelson" }, { "code": null, "e": 23386, "s": 23353, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 23408, "s": 23386, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 23441, "s": 23408, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 23463, "s": 23441, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 23496, "s": 23463, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 23518, "s": 23496, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 23551, "s": 23518, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 23573, "s": 23551, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 23606, "s": 23573, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 23617, "s": 23606, "text": " Mike West" }, { "code": null, "e": 23624, "s": 23617, "text": " Print" }, { "code": null, "e": 23635, "s": 23624, "text": " Add Notes" } ]
Bootstrap - Responsive utilities
Bootstrap provides some handful helper classes, for faster mobile-friendly development. These can be used for showing and hiding content by device via media query, combined with large, small, and medium devices. Use these sparingly and avoid creating entirely different versions of the same site. Responsive utilities are currently only available for block and table toggling. The following table lists the print classes. Use these for toggling the content for print. The following example demonstrates the use of above listed helper classes. Resize your browser or load the example on different devices to test the responsive utility classes. <div class = "container" style = "padding: 40px;"> <div class = "row visible-on"> <div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8; box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;"> <span class = "hidden-xs">Extra small</span> <span class = "visible-xs">✔ Visible on x-small</span> </div> <div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8; box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;"> <span class = "hidden-sm">Small</span> <span class = "visible-sm">✔ Visible on small</span> </div> <div class = "clearfix visible-xs"></div> <div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8; box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;"> <span class = "hidden-md">Medium</span> <span class = "visible-md">✔ Visible on medium</span> </div> <div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8; box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;"> <span class = "hidden-lg">Large</span> <span class = "visible-lg">✔ Visible on large</span> </div> </div> </div> Checkmarks indicates that the element is visible in your current viewport. 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3543, "s": 3331, "text": "Bootstrap provides some handful helper classes, for faster mobile-friendly development. These can be used for showing and hiding content by device via media query, combined with large, small, and medium devices." }, { "code": null, "e": 3708, "s": 3543, "text": "Use these sparingly and avoid creating entirely different versions of the same site. Responsive utilities are currently only available for block and table toggling." }, { "code": null, "e": 3799, "s": 3708, "text": "The following table lists the print classes. Use these for toggling the content for print." }, { "code": null, "e": 3975, "s": 3799, "text": "The following example demonstrates the use of above listed helper classes. Resize your browser or load the example on different devices to test the responsive utility classes." }, { "code": null, "e": 5303, "s": 3975, "text": "<div class = \"container\" style = \"padding: 40px;\">\n <div class = \"row visible-on\">\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <span class = \"hidden-xs\">Extra small</span>\n <span class = \"visible-xs\">✔ Visible on x-small</span>\n </div>\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <span class = \"hidden-sm\">Small</span>\n <span class = \"visible-sm\">✔ Visible on small</span>\n </div>\n \n <div class = \"clearfix visible-xs\"></div>\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <span class = \"hidden-md\">Medium</span>\n <span class = \"visible-md\">✔ Visible on medium</span>\n </div>\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <span class = \"hidden-lg\">Large</span>\n <span class = \"visible-lg\">✔ Visible on large</span>\n </div>\n \n </div> \n</div>" }, { "code": null, "e": 5378, "s": 5303, "text": "Checkmarks indicates that the element is visible in your current viewport." }, { "code": null, "e": 5411, "s": 5378, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5425, "s": 5411, "text": " Anadi Sharma" }, { "code": null, "e": 5460, "s": 5425, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5477, "s": 5460, "text": " Frahaan Hussain" }, { "code": null, "e": 5514, "s": 5477, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 5542, "s": 5514, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5575, "s": 5542, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 5587, "s": 5575, "text": " Azaz Patel" }, { "code": null, "e": 5622, "s": 5587, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5639, "s": 5622, "text": " Muhammad Ismail" }, { "code": null, "e": 5672, "s": 5639, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 5692, "s": 5672, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 5699, "s": 5692, "text": " Print" }, { "code": null, "e": 5710, "s": 5699, "text": " Add Notes" } ]
JavaScript How to get all 'name' values in a JSON array?
Let’s say the following is our JSON array − var details = [ { "customerDetails": [ { "customerName": "John Smith", "customerCountryName": "US" } ] }, { "customerDetails": [ { "customerName": "David Miller", "customerCountryName": "AUS" } ] }, { "customerDetails": [ { "customerName": "Bob Taylor", "customerCountryName": "UK" } ] } ] To get only the CustomerName values, use the concept of map() − var details = [ { "customerDetails": [ { "customerName": "John Smith", "customerCountryName": "US" } ] }, { "customerDetails": [ { "customerName": "David Miller", "customerCountryName": "AUS" } ] }, { "customerDetails": [ { "customerName": "Bob Taylor", "customerCountryName": "UK" } ] } ] var allCustomerName = details.map(obj=> obj.customerDetails[0].customerName); console.log(allCustomerName); To run the above program, you need to use the following command − node fileName.js. Here my file name is demo206.js. PS C:\Users\Amit\javascript-code> node demo206.js [ 'John Smith', 'David Miller', 'Bob Taylor' ]
[ { "code": null, "e": 1106, "s": 1062, "text": "Let’s say the following is our JSON array −" }, { "code": null, "e": 1588, "s": 1106, "text": "var details = [\n {\n \"customerDetails\": [\n {\n \"customerName\": \"John Smith\",\n \"customerCountryName\": \"US\"\n }\n ]\n },\n {\n \"customerDetails\": [\n {\n \"customerName\": \"David Miller\",\n \"customerCountryName\": \"AUS\"\n }\n ]\n },\n {\n \"customerDetails\": [\n {\n \"customerName\": \"Bob Taylor\",\n \"customerCountryName\": \"UK\"\n }\n ]\n }\n]" }, { "code": null, "e": 1652, "s": 1588, "text": "To get only the CustomerName values, use the concept of map() −" }, { "code": null, "e": 2230, "s": 1652, "text": "var details = [\n {\n \"customerDetails\": [\n {\n \"customerName\": \"John Smith\",\n \"customerCountryName\": \"US\"\n }\n ]\n },\n {\n \"customerDetails\": [\n {\n \"customerName\": \"David Miller\",\n \"customerCountryName\": \"AUS\"\n }\n ]\n },\n {\n \"customerDetails\": [\n {\n \"customerName\": \"Bob Taylor\",\n \"customerCountryName\": \"UK\"\n }\n ]\n }\n]\nvar allCustomerName = details.map(obj=>\nobj.customerDetails[0].customerName);\nconsole.log(allCustomerName);" }, { "code": null, "e": 2296, "s": 2230, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 2314, "s": 2296, "text": "node fileName.js." }, { "code": null, "e": 2347, "s": 2314, "text": "Here my file name is demo206.js." }, { "code": null, "e": 2444, "s": 2347, "text": "PS C:\\Users\\Amit\\javascript-code> node demo206.js\n[ 'John Smith', 'David Miller', 'Bob Taylor' ]" } ]
Circular Dependency in Spring | Spring Circular Dependency proble
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to learn about what is Spring circular dependency problem? and how to resolve it. In our day to day development life, while implementing the spring applications, we may have a requirement like class A depending on class B and class B also depending on class A, though it is not a good practice sometimes you can’t avoid such types of dependencies. Spring considers this type of scenario as a circular dependency and is also given some good practices to handle this. Here, I am going to show you the most popular way to handle this scenario. In spring we have different types of dependency injections if we inject the dependency through the constructor arguments <constructor-arg>, and the two classes are depending on each other then spring will throw an exception like BeanCurrentlyInCreationException, this is where we get circular dependency in spring. In the case of constructor injection, the dependencies are injected while creating the object, so that, by the time creating the object of A, there is no object of B and vice versa. class A { private B b; public A(B b) { this.b = b; } } class B { private A a; public B(A a) { this.a = a; } } On the above, while creating object A, object B is required. Similarly to create an object for B, object A is required. Finally, A and B objects will not be created as these two are depends on each other and an exception will be thrown by the spring container. In order to solve the circular dependency problem on one side, the dependency injection type must be changed to setter injection. In the case of setter injection, the dependencies are injected after creating the object, not while creating the objects. class A { private B b; public void setB(B b) { this.b = b; } } class B { private A a; public void setA(A a) { this.a = a; } } In the above, the Spring container will inject objects of class B to A, like the following. A a = new A(); B b = new B(); a.setB(b); Spring ICO container Spring Loaded beans in IOC container Happy Learning 🙂 Dependency Injection (IoC) in spring with Example Spring Collection Dependency List Example Spring Collection Map Dependency Example @Autowired,@Qualifier,@Value annotations in Spring Spring Bean Autowire By Constructor Example Spring Bean Autowire ByName Example Spring Bean Autowire ByType Example BeanFactory Example in Spring spring expression language example Advantages of Spring Framework @Component,@Service,@Repository,@Controller in spring Types of Spring Bean Scopes Example Spring Java Configuration Example Spring JdbcTemplate CRUD Application @Qualifier annotation example in Spring Dependency Injection (IoC) in spring with Example Spring Collection Dependency List Example Spring Collection Map Dependency Example @Autowired,@Qualifier,@Value annotations in Spring Spring Bean Autowire By Constructor Example Spring Bean Autowire ByName Example Spring Bean Autowire ByType Example BeanFactory Example in Spring spring expression language example Advantages of Spring Framework @Component,@Service,@Repository,@Controller in spring Types of Spring Bean Scopes Example Spring Java Configuration Example Spring JdbcTemplate CRUD Application @Qualifier annotation example in Spring
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 511, "s": 398, "text": "In this tutorial, we are going to learn about what is Spring circular dependency problem? and how to resolve it." }, { "code": null, "e": 778, "s": 511, "text": "In our day to day development life, while implementing the spring applications, we may have a requirement like class A depending on class B and class B also depending on class A, though it is not a good practice sometimes you can’t avoid such types of dependencies." }, { "code": null, "e": 971, "s": 778, "text": "Spring considers this type of scenario as a circular dependency and is also given some good practices to handle this. Here, I am going to show you the most popular way to handle this scenario." }, { "code": null, "e": 1286, "s": 971, "text": "In spring we have different types of dependency injections if we inject the dependency through the constructor arguments <constructor-arg>, and the two classes are depending on each other then spring will throw an exception like BeanCurrentlyInCreationException, this is where we get circular dependency in spring." }, { "code": null, "e": 1468, "s": 1286, "text": "In the case of constructor injection, the dependencies are injected while creating the object, so that, by the time creating the object of A, there is no object of B and vice versa." }, { "code": null, "e": 1619, "s": 1468, "text": "class A {\n private B b;\n public A(B b) {\n this.b = b;\n }\n}\n\nclass B {\n private A a;\n public B(A a) {\n this.a = a;\n }\n}" }, { "code": null, "e": 1880, "s": 1619, "text": "On the above, while creating object A, object B is required. Similarly to create an object for B, object A is required. Finally, A and B objects will not be created as these two are depends on each other and an exception will be thrown by the spring container." }, { "code": null, "e": 2132, "s": 1880, "text": "In order to solve the circular dependency problem on one side, the dependency injection type must be changed to setter injection. In the case of setter injection, the dependencies are injected after creating the object, not while creating the objects." }, { "code": null, "e": 2299, "s": 2132, "text": "class A {\n private B b;\n public void setB(B b) {\n this.b = b;\n }\n}\n\nclass B {\n private A a;\n public void setA(A a) {\n this.a = a;\n }\n}" }, { "code": null, "e": 2391, "s": 2299, "text": "In the above, the Spring container will inject objects of class B to A, like the following." }, { "code": null, "e": 2432, "s": 2391, "text": "A a = new A();\nB b = new B();\na.setB(b);" }, { "code": null, "e": 2453, "s": 2432, "text": "Spring ICO container" }, { "code": null, "e": 2490, "s": 2453, "text": "Spring Loaded beans in IOC container" }, { "code": null, "e": 2507, "s": 2490, "text": "Happy Learning 🙂" }, { "code": null, "e": 3106, "s": 2507, "text": "\nDependency Injection (IoC) in spring with Example\nSpring Collection Dependency List Example\nSpring Collection Map Dependency Example\n@Autowired,@Qualifier,@Value annotations in Spring\nSpring Bean Autowire By Constructor Example\nSpring Bean Autowire ByName Example\nSpring Bean Autowire ByType Example\nBeanFactory Example in Spring\nspring expression language example\nAdvantages of Spring Framework\n@Component,@Service,@Repository,@Controller in spring\nTypes of Spring Bean Scopes Example\nSpring Java Configuration Example\nSpring JdbcTemplate CRUD Application\n@Qualifier annotation example in Spring\n" }, { "code": null, "e": 3156, "s": 3106, "text": "Dependency Injection (IoC) in spring with Example" }, { "code": null, "e": 3198, "s": 3156, "text": "Spring Collection Dependency List Example" }, { "code": null, "e": 3239, "s": 3198, "text": "Spring Collection Map Dependency Example" }, { "code": null, "e": 3290, "s": 3239, "text": "@Autowired,@Qualifier,@Value annotations in Spring" }, { "code": null, "e": 3334, "s": 3290, "text": "Spring Bean Autowire By Constructor Example" }, { "code": null, "e": 3370, "s": 3334, "text": "Spring Bean Autowire ByName Example" }, { "code": null, "e": 3406, "s": 3370, "text": "Spring Bean Autowire ByType Example" }, { "code": null, "e": 3436, "s": 3406, "text": "BeanFactory Example in Spring" }, { "code": null, "e": 3471, "s": 3436, "text": "spring expression language example" }, { "code": null, "e": 3502, "s": 3471, "text": "Advantages of Spring Framework" }, { "code": null, "e": 3556, "s": 3502, "text": "@Component,@Service,@Repository,@Controller in spring" }, { "code": null, "e": 3592, "s": 3556, "text": "Types of Spring Bean Scopes Example" }, { "code": null, "e": 3626, "s": 3592, "text": "Spring Java Configuration Example" }, { "code": null, "e": 3663, "s": 3626, "text": "Spring JdbcTemplate CRUD Application" } ]
Scala String replaceAll() method with example
03 Oct, 2019 The replaceAll() method is used to replace each of the stated sub-string of the string which matches the regular expression with the string we supply in the argument list. Method Definition: String replaceAll(String regex, String replacement)Return Type: It returns the stated string after replacing the stated sub-string with the string we provide. Example #1: // Scala program of replaceAll()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying replaceAll method val result = "csoNidhimso".replaceAll(".so", "##") // Displays output println(result) }} ##Nidhi## Example #2: // Scala program of replaceAll()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying replaceAll method val result = "csoNidhimsoSingh ".replaceAll(".so", "##") // Displays output println(result) }} ##Nidhi##Singh Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Oct, 2019" }, { "code": null, "e": 200, "s": 28, "text": "The replaceAll() method is used to replace each of the stated sub-string of the string which matches the regular expression with the string we supply in the argument list." }, { "code": null, "e": 378, "s": 200, "text": "Method Definition: String replaceAll(String regex, String replacement)Return Type: It returns the stated string after replacing the stated sub-string with the string we provide." }, { "code": null, "e": 390, "s": 378, "text": "Example #1:" }, { "code": "// Scala program of replaceAll()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying replaceAll method val result = \"csoNidhimso\".replaceAll(\".so\", \"##\") // Displays output println(result) }} ", "e": 694, "s": 390, "text": null }, { "code": null, "e": 705, "s": 694, "text": "##Nidhi##\n" }, { "code": null, "e": 717, "s": 705, "text": "Example #2:" }, { "code": "// Scala program of replaceAll()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying replaceAll method val result = \"csoNidhimsoSingh \".replaceAll(\".so\", \"##\") // Displays output println(result) }} ", "e": 1027, "s": 717, "text": null }, { "code": null, "e": 1043, "s": 1027, "text": "##Nidhi##Singh\n" }, { "code": null, "e": 1049, "s": 1043, "text": "Scala" }, { "code": null, "e": 1062, "s": 1049, "text": "Scala-Method" }, { "code": null, "e": 1076, "s": 1062, "text": "Scala-Strings" }, { "code": null, "e": 1082, "s": 1076, "text": "Scala" } ]
Creating multiple process using fork()
09 Oct, 2017 Prerequisite – Introduction of fork, getpid() and getppid()Problem statement – Write a program to create one parent with three child using fork() function where each process find its Id. For example : Output :parent 28808 28809 my id is 28807 First child 0 28810 my id is 28808 Second child 28808 0 my id is 28809 third child 0 0 Explanation – Here, we had used fork() function to create four processes one Parent and three child processes. An existing process can create a new one by calling the fork( ) function. The new process created by fork() is called the child process. We are using here getpid() to get the process id In fork() the total process created is = 2^number of fork() Note – At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions. Code 1 – Using getpid() // C++ program to demonstrate creating processes using fork()#include <unistd.h>#include <stdio.h> int main(){ // Creating first child int n1 = fork(); // Creating second child. First child // also executes this line and creates // grandchild. int n2 = fork(); if (n1 > 0 && n2 > 0) { printf("parent\n"); printf("%d %d \n", n1, n2); printf(" my id is %d \n", getpid()); } else if (n1 == 0 && n2 > 0) { printf("First child\n"); printf("%d %d \n", n1, n2); printf("my id is %d \n", getpid()); } else if (n1 > 0 && n2 == 0) { printf("Second child\n"); printf("%d %d \n", n1, n2); printf("my id is %d \n", getpid()); } else { printf("third child\n"); printf("%d %d \n", n1, n2); printf(" my id is %d \n", getpid()); } return 0;} Output – parent 28808 28809 my id is 28807 First child 0 28810 my id is 28808 Second child 28808 0 my id is 28809 third child 0 0 Code 2 – Using getppid() // C++ program to demonstrate creating processes using fork()#include <unistd.h>#include <stdio.h> int main(){ // Creating first child int n1 = fork(); // Creating second child. First child // also executes this line and creates // grandchild. int n2 = fork(); if (n1 > 0 && n2 > 0) { printf("parent\n"); printf("%d %d \n", n1, n2); printf(" my id is %d \n", getpid()); printf(" my parentid is %d \n", getppid()); } else if (n1 == 0 && n2 > 0) { printf("First child\n"); printf("%d %d \n", n1, n2); printf("my id is %d \n", getpid()); printf(" my parentid is %d \n", getppid()); } else if (n1 > 0 && n2 == 0) { printf("second child\n"); printf("%d %d \n", n1, n2); printf("my id is %d \n", getpid()); printf(" my parentid is %d \n", getppid()); } else { printf("third child\n"); printf("%d %d \n", n1, n2); printf(" my id is %d \n", getpid()); printf(" my parentid is %d \n", getppid()); } return 0;} Output – parent 5219 5220 my id is 5217 my parentid is 5215 First child 0 5221 my id is 5219 my parentid is 1 second child 5219 0 my id is 5220 my parentid is 1 third child 0 0 my id is 5221 my parentid is 1 This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. system-programming C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Oct, 2017" }, { "code": null, "e": 253, "s": 52, "text": "Prerequisite – Introduction of fork, getpid() and getppid()Problem statement – Write a program to create one parent with three child using fork() function where each process find its Id. For example :" }, { "code": null, "e": 395, "s": 253, "text": "Output :parent\n28808 28809 \n my id is 28807 \nFirst child\n0 28810 \nmy id is 28808 \nSecond child\n28808 0 \nmy id is 28809 \nthird child\n0 0 \n \n" }, { "code": null, "e": 506, "s": 395, "text": "Explanation – Here, we had used fork() function to create four processes one Parent and three child processes." }, { "code": null, "e": 580, "s": 506, "text": "An existing process can create a new one by calling the fork( ) function." }, { "code": null, "e": 643, "s": 580, "text": "The new process created by fork() is called the child process." }, { "code": null, "e": 692, "s": 643, "text": "We are using here getpid() to get the process id" }, { "code": null, "e": 752, "s": 692, "text": "In fork() the total process created is = 2^number of fork()" }, { "code": null, "e": 1005, "s": 752, "text": "Note – At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions." }, { "code": null, "e": 1029, "s": 1005, "text": "Code 1 – Using getpid()" }, { "code": "// C++ program to demonstrate creating processes using fork()#include <unistd.h>#include <stdio.h> int main(){ // Creating first child int n1 = fork(); // Creating second child. First child // also executes this line and creates // grandchild. int n2 = fork(); if (n1 > 0 && n2 > 0) { printf(\"parent\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\" my id is %d \\n\", getpid()); } else if (n1 == 0 && n2 > 0) { printf(\"First child\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\"my id is %d \\n\", getpid()); } else if (n1 > 0 && n2 == 0) { printf(\"Second child\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\"my id is %d \\n\", getpid()); } else { printf(\"third child\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\" my id is %d \\n\", getpid()); } return 0;}", "e": 1896, "s": 1029, "text": null }, { "code": null, "e": 1905, "s": 1896, "text": "Output –" }, { "code": null, "e": 2037, "s": 1905, "text": "parent\n28808 28809 \n my id is 28807 \nFirst child\n0 28810 \nmy id is 28808 \nSecond child\n28808 0 \nmy id is 28809 \nthird child\n0 0 \n" }, { "code": null, "e": 2062, "s": 2037, "text": "Code 2 – Using getppid()" }, { "code": "// C++ program to demonstrate creating processes using fork()#include <unistd.h>#include <stdio.h> int main(){ // Creating first child int n1 = fork(); // Creating second child. First child // also executes this line and creates // grandchild. int n2 = fork(); if (n1 > 0 && n2 > 0) { printf(\"parent\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\" my id is %d \\n\", getpid()); printf(\" my parentid is %d \\n\", getppid()); } else if (n1 == 0 && n2 > 0) { printf(\"First child\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\"my id is %d \\n\", getpid()); printf(\" my parentid is %d \\n\", getppid()); } else if (n1 > 0 && n2 == 0) { printf(\"second child\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\"my id is %d \\n\", getpid()); printf(\" my parentid is %d \\n\", getppid()); } else { printf(\"third child\\n\"); printf(\"%d %d \\n\", n1, n2); printf(\" my id is %d \\n\", getpid()); printf(\" my parentid is %d \\n\", getppid()); } return 0;}", "e": 3138, "s": 2062, "text": null }, { "code": null, "e": 3147, "s": 3138, "text": "Output –" }, { "code": null, "e": 3366, "s": 3147, "text": "parent\n5219 5220 \n my id is 5217 \n my parentid is 5215 \nFirst child\n0 5221 \nmy id is 5219 \n my parentid is 1 \nsecond child\n5219 0 \nmy id is 5220 \nmy parentid is 1 \nthird child\n0 0 \n my id is 5221 \n my parentid is 1 \n" }, { "code": null, "e": 3673, "s": 3366, "text": "This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3798, "s": 3673, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3817, "s": 3798, "text": "system-programming" }, { "code": null, "e": 3821, "s": 3817, "text": "C++" }, { "code": null, "e": 3825, "s": 3821, "text": "CPP" } ]
Split a String into a Number of Substrings in Java
17 Feb, 2022 Given a String, the task it to split the String into a number of substrings. A String in java can be of 0 or more characters. Examples : (a) "" is a String in java with 0 character (b) "d" is a String in java with 1 character (c) "This is a sentence." is a string with 19 characters. Substring: A String that is a part of another string is called substring of the other string. Example 1: Let us consider the string bat. The possible substrings are: (1) "b" (2) "ba" (3) "bat", every string is a substring of itself (4) "a" (5) "at" (6) "t" (7) "" , "" is a substring of every string Example 2: Let us consider the string The Cat. The possible substrings are: (1) "T" (2) "Th" (3) "The" (4) "The " (5) "The C" (6) "The Ca" (7) "The Cat", every string is a substring of itself (8) "h" (9) "he" (10) "he " (11) "he C" (12) "he Ca" (13) "he Cat" (14) "e" (15) "e " (16) "e C" (17) "e Ca" (18) "e Cat" (19) " " (20) " C" (21) " Ca" (22) " Cat" (23) "C" (24) "Ca" (25) "Cat" (26) "a" (27) "at" (28) "t" (29) "" , "" is a substring of every string Note: Total number of substrings of a string of length N is (N * (N + 1)) / 2. This is after excluding the empty string “” because it is a substring of all strings. Approach: Let us consider a string which has n characters: 1. For each character at index i (0 to n-1): find substrings of length 1, 2, ..., n-i Example: Let our string be cat, here n = 3 (the length of string) here, index of 'c' is 0 index of 'a' is 1 index of 't' is 2 Loop from i = 0 to 2: (since n-1 = 2) When i = 0: Substring of length 1 : "c" Substring of length 2 : "ca" Substring of length 3 : "cat" , (substring of length n-i or 3-0 = 3) When i = 1: Substring of length 1 : "a" Substring of length 2 : "at" , (substring of length n-i or 3-1 = 2) When i = 2: Substring of length 1 : "t" , (substring of length n-i or 3-2 = 1) Example: Java // Java Program to split a string into all possible// substrings excluding the string with 0 characters i.e. "" import java.io.*;import java.util.ArrayList; class SubstringsOfAString { // function to split a string into all its substrings // and return the list as an object of ArrayList public static ArrayList<String> splitSubstrings(String s) { // variables to traverse through the // string int i, j; // to store the length of the // string int stringLength = s.length(); // List object to store the list of // all substrings of the string s ArrayList<String> subStringList = new ArrayList<String>(); // first for loop for (i = 0; i < stringLength; i++) { for (j = i + 1; j <= stringLength; j++) { subStringList.add(s.substring(i, j)); } } // end of first for loop // returning the list (object // of ArrayList) of substrings // of string s return subStringList; } public static void main(String[] args) { // here "The Cat" is our input string String stringInput = new String("The Cat"); ArrayList<String> subStringList = SubstringsOfAString.splitSubstrings( stringInput); System.out.println( "\nSubstring list printed as an ArrayList : "); System.out.println(subStringList); System.out.println( "\n\nAll substrings printed 1 per line : "); int count = 1; // each substring would be printed // within double quotes for (String it : subStringList) { System.out.println("(" + count + ") \"" + it + "\""); count++; } }} Substring list printed as an ArrayList : [T, Th, The, The , The C, The Ca, The Cat, h, he, he , he C, he Ca, he Cat, e, e , e C, e Ca, e Cat, , C, Ca, Cat, C, Ca, Cat, a, at, t] All substrings printed 1 per line : (1) "T" (2) "Th" (3) "The" (4) "The " (5) "The C" (6) "The Ca" (7) "The Cat" (8) "h" (9) "he" (10) "he " (11) "he C" (12) "he Ca" (13) "he Cat" (14) "e" (15) "e " (16) "e C" (17) "e Ca" (18) "e Cat" (19) " " (20) " C" (21) " Ca" (22) " Cat" (23) "C" (24) "Ca" (25) "Cat" (26) "a" (27) "at" (28) "t" Time Complexity: O(n2) where n is the length of a string Output 1: When string Input = bat Substring list printed as an ArrayList : [b, ba, bat, a, at, t] All substrings printed 1 per line : (1) "b" (2) "ba" (3) "bat" (4) "a" (5) "at" (6) "t" Output 2: When string Input = The Cat Substring list printed as an ArrayList : [T, Th, The, The , The C, The Ca, The Cat, h, he, he , he C, he Ca, he Cat, e, e , e C, e Ca, e Cat, , C, Ca, Cat, C, Ca, Cat, a, at, t] All substrings printed 1 per line : (1) "T" (2) "Th" (3) "The" (4) "The " (5) "The C" (6) "The Ca" (7) "The Cat" (8) "h" (9) "he" (10) "he " (11) "he C" (12) "he Ca" (13) "he Cat" (14) "e" (15) "e " (16) "e C" (17) "e Ca" (18) "e Cat" (19) " " (20) " C" (21) " Ca" (22) " Cat" (23) "C" (24) "Ca" (25) "Cat" (26) "a" (27) "at" (28) "t" sagar0719kumar Java-String-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Feb, 2022" }, { "code": null, "e": 129, "s": 52, "text": "Given a String, the task it to split the String into a number of substrings." }, { "code": null, "e": 179, "s": 129, "text": "A String in java can be of 0 or more characters. " }, { "code": null, "e": 190, "s": 179, "text": "Examples :" }, { "code": null, "e": 338, "s": 190, "text": "(a) \"\" is a String in java with 0 character\n(b) \"d\" is a String in java with 1 character\n(c) \"This is a sentence.\" is a string with 19 characters.\n" }, { "code": null, "e": 432, "s": 338, "text": "Substring: A String that is a part of another string is called substring of the other string." }, { "code": null, "e": 504, "s": 432, "text": "Example 1: Let us consider the string bat. The possible substrings are:" }, { "code": null, "e": 640, "s": 504, "text": "(1) \"b\"\n(2) \"ba\"\n(3) \"bat\", every string is a substring of itself\n(4) \"a\"\n(5) \"at\"\n(6) \"t\"\n(7) \"\" , \"\" is a substring of every string\n" }, { "code": null, "e": 717, "s": 640, "text": "Example 2: Let us consider the string The Cat. The possible substrings are: " }, { "code": null, "e": 1102, "s": 717, "text": "(1) \"T\"\n(2) \"Th\"\n(3) \"The\"\n(4) \"The \"\n(5) \"The C\"\n(6) \"The Ca\"\n(7) \"The Cat\", every string is a substring of itself\n(8) \"h\"\n(9) \"he\"\n(10) \"he \"\n(11) \"he C\"\n(12) \"he Ca\"\n(13) \"he Cat\"\n(14) \"e\"\n(15) \"e \"\n(16) \"e C\"\n(17) \"e Ca\"\n(18) \"e Cat\"\n(19) \" \"\n(20) \" C\"\n(21) \" Ca\"\n(22) \" Cat\"\n(23) \"C\"\n(24) \"Ca\"\n(25) \"Cat\"\n(26) \"a\"\n(27) \"at\"\n(28) \"t\"\n(29) \"\" , \"\" is a substring of every string\n\n" }, { "code": null, "e": 1267, "s": 1102, "text": "Note: Total number of substrings of a string of length N is (N * (N + 1)) / 2. This is after excluding the empty string “” because it is a substring of all strings." }, { "code": null, "e": 1277, "s": 1267, "text": "Approach:" }, { "code": null, "e": 1977, "s": 1277, "text": "Let us consider a string which has n characters:\n1. For each character at index i (0 to n-1):\n find substrings of length 1, 2, ..., n-i\n \n\nExample: Let our string be cat, here n = 3 (the length of string)\nhere, \n index of 'c' is 0\n index of 'a' is 1\n index of 't' is 2\n \nLoop from i = 0 to 2: (since n-1 = 2)\n\nWhen i = 0:\n Substring of length 1 : \"c\" \n Substring of length 2 : \"ca\" \n Substring of length 3 : \"cat\" , (substring of length n-i or 3-0 = 3)\n \nWhen i = 1:\n Substring of length 1 : \"a\"\n Substring of length 2 : \"at\" , (substring of length n-i or 3-1 = 2)\n \nWhen i = 2:\n Substring of length 1 : \"t\" , (substring of length n-i or 3-2 = 1)\n" }, { "code": null, "e": 1987, "s": 1977, "text": "Example: " }, { "code": null, "e": 1992, "s": 1987, "text": "Java" }, { "code": "// Java Program to split a string into all possible// substrings excluding the string with 0 characters i.e. \"\" import java.io.*;import java.util.ArrayList; class SubstringsOfAString { // function to split a string into all its substrings // and return the list as an object of ArrayList public static ArrayList<String> splitSubstrings(String s) { // variables to traverse through the // string int i, j; // to store the length of the // string int stringLength = s.length(); // List object to store the list of // all substrings of the string s ArrayList<String> subStringList = new ArrayList<String>(); // first for loop for (i = 0; i < stringLength; i++) { for (j = i + 1; j <= stringLength; j++) { subStringList.add(s.substring(i, j)); } } // end of first for loop // returning the list (object // of ArrayList) of substrings // of string s return subStringList; } public static void main(String[] args) { // here \"The Cat\" is our input string String stringInput = new String(\"The Cat\"); ArrayList<String> subStringList = SubstringsOfAString.splitSubstrings( stringInput); System.out.println( \"\\nSubstring list printed as an ArrayList : \"); System.out.println(subStringList); System.out.println( \"\\n\\nAll substrings printed 1 per line : \"); int count = 1; // each substring would be printed // within double quotes for (String it : subStringList) { System.out.println(\"(\" + count + \") \\\"\" + it + \"\\\"\"); count++; } }}", "e": 3809, "s": 1992, "text": null }, { "code": null, "e": 4332, "s": 3809, "text": "Substring list printed as an ArrayList : \n[T, Th, The, The , The C, The Ca, The Cat, h, he, he , he C, he Ca, he Cat, e, e , e C, e Ca, e Cat, , C, Ca, Cat, C, Ca, Cat, a, at, t]\n\n\nAll substrings printed 1 per line : \n(1) \"T\"\n(2) \"Th\"\n(3) \"The\"\n(4) \"The \"\n(5) \"The C\"\n(6) \"The Ca\"\n(7) \"The Cat\"\n(8) \"h\"\n(9) \"he\"\n(10) \"he \"\n(11) \"he C\"\n(12) \"he Ca\"\n(13) \"he Cat\"\n(14) \"e\"\n(15) \"e \"\n(16) \"e C\"\n(17) \"e Ca\"\n(18) \"e Cat\"\n(19) \" \"\n(20) \" C\"\n(21) \" Ca\"\n(22) \" Cat\"\n(23) \"C\"\n(24) \"Ca\"\n(25) \"Cat\"\n(26) \"a\"\n(27) \"at\"\n(28) \"t\"\n\n" }, { "code": null, "e": 4392, "s": 4332, "text": "Time Complexity: O(n2) where n is the length of a string " }, { "code": null, "e": 4426, "s": 4392, "text": "Output 1: When string Input = bat" }, { "code": null, "e": 4583, "s": 4426, "text": "Substring list printed as an ArrayList : \n[b, ba, bat, a, at, t]\n\n\nAll substrings printed 1 per line : \n(1) \"b\"\n(2) \"ba\"\n(3) \"bat\"\n(4) \"a\"\n(5) \"at\"\n(6) \"t\"\n" }, { "code": null, "e": 4621, "s": 4583, "text": "Output 2: When string Input = The Cat" }, { "code": null, "e": 5143, "s": 4621, "text": "Substring list printed as an ArrayList : \n[T, Th, The, The , The C, The Ca, The Cat, h, he, he , he C, he Ca, he Cat, e, e , e C, e Ca, e Cat, , C, Ca, Cat, C, Ca, Cat, a, at, t]\n\n\nAll substrings printed 1 per line : \n(1) \"T\"\n(2) \"Th\"\n(3) \"The\"\n(4) \"The \"\n(5) \"The C\"\n(6) \"The Ca\"\n(7) \"The Cat\"\n(8) \"h\"\n(9) \"he\"\n(10) \"he \"\n(11) \"he C\"\n(12) \"he Ca\"\n(13) \"he Cat\"\n(14) \"e\"\n(15) \"e \"\n(16) \"e C\"\n(17) \"e Ca\"\n(18) \"e Cat\"\n(19) \" \"\n(20) \" C\"\n(21) \" Ca\"\n(22) \" Cat\"\n(23) \"C\"\n(24) \"Ca\"\n(25) \"Cat\"\n(26) \"a\"\n(27) \"at\"\n(28) \"t\"\n" }, { "code": null, "e": 5158, "s": 5143, "text": "sagar0719kumar" }, { "code": null, "e": 5179, "s": 5158, "text": "Java-String-Programs" }, { "code": null, "e": 5184, "s": 5179, "text": "Java" }, { "code": null, "e": 5198, "s": 5184, "text": "Java Programs" }, { "code": null, "e": 5203, "s": 5198, "text": "Java" } ]
Morse Code Implementation
08 Feb, 2021 Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.The algorithm is very simple. Every character in the English language is substituted by a series of ‘dots’ and ‘dashes’ or sometimes just singular ‘dot’ or ‘dash’ and vice versa.Every text string is converted into the series of dots and dashes. For this every character is converted into its Morse code and appended in encoded message. Here we have copied space as it is. We have considered both numbers and alphabets. Examples: Input : geeksforgeeks Output : --...-.-.....-.---.-.--...-.-... Input : program Output : .--..-.-----..-..--- C++ Java Python 3 C# PHP // CPP program to demonstrate Morse code#include <iostream>using namespace std; // function to encode a alphabet as// Morse codestring morseEncode(char x){ // refer to the Morse table // image attached in the article switch (x) { case 'a': return ".-"; case 'b': return "-..."; case 'c': return "-.-."; case 'd': return "-.."; case 'e': return "."; case 'f': return "..-."; case 'g': return "--."; case 'h': return "...."; case 'i': return ".."; case 'j': return ".---"; case 'k': return "-.-"; case 'l': return ".-.."; case 'm': return "--"; case 'n': return "-."; case 'o': return "---"; case 'p': return ".--."; case 'q': return "--.-"; case 'r': return ".-."; case 's': return "..."; case 't': return "-"; case 'u': return "..-"; case 'v': return "...-"; case 'w': return ".--"; case 'x': return "-..-"; case 'y': return "-.--"; case 'z': return "--.."; case '1': return ".----"; case '2': return "..---"; case '3': return "...--"; case '4': return "....-"; case '5': return "....."; case '6': return "-...."; case '7': return "--..."; case '8': return "---.."; case '9': return "----."; case '0': return "-----"; default: cerr << "Found invalid character: " << x << ' ' << std::endl; exit(0); }} void morseCode(string s){ // character by character print // Morse code for (int i = 0; s[i]; i++) cout << morseEncode(s[i]); cout << endl;} // Driver's codeint main(){ string s = "geeksforgeeks"; morseCode(s); return 0;} // Java program to demonstrate Morse codeclass GFG{ // function to encode a alphabet as // Morse code static String morseEncode(char x) { // refer to the Morse table // image attached in the article switch (x) { case 'a': return ".-"; case 'b': return "-..."; case 'c': return "-.-."; case 'd': return "-.."; case 'e': return "."; case 'f': return "..-."; case 'g': return "--."; case 'h': return "...."; case 'i': return ".."; case 'j': return ".---"; case 'k': return "-.-"; case 'l': return ".-.."; case 'm': return "--"; case 'n': return "-."; case 'o': return "---"; case 'p': return ".--."; case 'q': return "--.-"; case 'r': return ".-."; case 's': return "..."; case 't': return "-"; case 'u': return "..-"; case 'v': return "...-"; case 'w': return ".--"; case 'x': return "-..-"; case 'y': return "-.--"; // for space case 'z': return "--.."; case '1': return ".----"; case '2': return "..---"; case '3': return "...--"; case '4': return "....-"; case '5': return "....."; case '6': return "-...."; case '7': return "--..."; case '8': return "---.."; case '9': return "----."; case '0': return "-----"; } return ""; } static void morseCode(String s) { // character by character print // Morse code for (int i = 0;i<s.length(); i++) System.out.print(morseEncode(s.charAt(i))); System.out.println(); } // Driver code public static void main (String[] args) { String s = "geeksforgeeks"; morseCode(s); }} // This code is contributed by Anant Agarwal. # Python3 program to demonstrate Morse code # function to encode a alphabet as# Morse codedef morseEncode(x): # refer to the Morse table # image attached in the article if x is 'a': return ".-" elif x is 'b': return "-..." elif x is 'c': return "-.-." elif x is 'd': return "-.." elif x is 'e': return "." elif x is 'f': return "..-." elif x is 'g': return "--." elif x is 'h': return "...." elif x is 'i': return ".." elif x is 'j': return ".---" elif x is 'k': return "-.-" elif x is 'l': return ".-.." elif x is 'm': return "--" elif x is 'n': return "-." elif x is 'o': return "---" elif x is 'p': return ".--." elif x is 'q': return "--.-" elif x is 'r': return ".-." elif x is 's': return "..." elif x is 't': return "-" elif x is 'u': return "..-" elif x is 'v': return "...-" elif x is 'w': return ".--" elif x is 'x': return "-..-" elif x is 'y': return "-.--" elif x is 'z': return "--.." elif x is '1': return ".----"; elif x is '2': return "..---"; elif x is '3': return "...--"; elif x is '4': return "....-"; elif x is '5': return "....."; elif x is '6': return "-...."; elif x is '7': return "--..."; elif x is '8': return "---.."; elif x is '9': return "----."; elif x is '0': return "-----"; # character by character print# Morse codedef morseCode(s): for character in s: print(morseEncode(character), end = "") # Driver Codeif __name__ == "__main__": s = "geeksforgeeks" morseCode(s) # This code is contributed# by Vivek Kumar Singh // C# program to demonstrate Morse codeusing System; class GFG{ // function to encode a alphabet as // Morse code static string morseEncode(char x) { // refer to the Morse table // image attached in the article switch (x) { case 'a': return ".-"; case 'b': return "-..."; case 'c': return "-.-."; case 'd': return "-.."; case 'e': return "."; case 'f': return "..-."; case 'g': return "--."; case 'h': return "...."; case 'i': return ".."; case 'j': return ".---"; case 'k': return "-.-"; case 'l': return ".-.."; case 'm': return "--"; case 'n': return "-."; case 'o': return "---"; case 'p': return ".--."; case 'q': return "--.-"; case 'r': return ".-."; case 's': return "..."; case 't': return "-"; case 'u': return "..-"; case 'v': return "...-"; case 'w': return ".--"; case 'x': return "-..-"; case 'y': return "-.--"; // for space case 'z': return "--.."; case '1': return ".----"; case '2': return "..---"; case '3': return "...--"; case '4': return "....-"; case '5': return "....."; case '6': return "-...."; case '7': return "--..."; case '8': return "---.."; case '9': return "----."; case '0': return "-----"; } return ""; } static void morseCode(string s) { // character by character print // Morse code for (int i = 0;i<s.Length; i++) Console.Write(morseEncode(s[i])); Console.WriteLine(); } // Driver code public static void Main () { string s = "geeksforgeeks"; morseCode(s); }} // This code is contributed by vt_m. <?php// php program to demonstrate// Morse code // function to encode a // alphabet as Morse codefunction morseEncode($x){ // refer to the Morse table // image attached in the article switch ($x) { case 'a': return ".-"; case 'b': return "-..."; case 'c': return "-.-."; case 'd': return "-.."; case 'e': return "."; case 'f': return "..-."; case 'g': return "--."; case 'h': return "...."; case 'i': return ".."; case 'j': return ".---"; case 'k': return "-.-"; case 'l': return ".-.."; case 'm': return "--"; case 'n': return "-."; case 'o': return "---"; case 'p': return ".--."; case 'q': return "--.-"; case 'r': return ".-."; case 's': return "..."; case 't': return "-"; case 'u': return "..-"; case 'v': return "...-"; case 'w': return ".--"; case 'x': return "-..-"; case 'y': return "-.--"; case '1': return ".----"; case '2': return "..---"; case '3': return "...--"; case '4': return "....-"; case '5': return "....."; case '6': return "-...."; case '7': return "--..."; case '8': return "---.."; case '9': return "----."; case '0': return "-----"; // for space case 'z': return "--.."; }} function morseCode($s){ // Character by character // print Morse code for ($i = 0; $i<strlen($s); $i++) echo morseEncode($s[$i]); echo "\n";} // Driver code$s = "geeksforgeeks";morseCode($s); // This code is contributed by mits?> Output: --...-.-.....-.---.-.--...-.-... Mithun Kumar Vivekkumar Singh siddhantdugar241 encoding-decoding Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Feb, 2021" }, { "code": null, "e": 735, "s": 54, "text": "Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.The algorithm is very simple. Every character in the English language is substituted by a series of ‘dots’ and ‘dashes’ or sometimes just singular ‘dot’ or ‘dash’ and vice versa.Every text string is converted into the series of dots and dashes. For this every character is converted into its Morse code and appended in encoded message. Here we have copied space as it is. We have considered both numbers and alphabets. " }, { "code": null, "e": 746, "s": 735, "text": "Examples: " }, { "code": null, "e": 859, "s": 746, "text": "Input : geeksforgeeks\nOutput : --...-.-.....-.---.-.--...-.-...\n\nInput : program\nOutput : .--..-.-----..-..---" }, { "code": null, "e": 863, "s": 859, "text": "C++" }, { "code": null, "e": 868, "s": 863, "text": "Java" }, { "code": null, "e": 877, "s": 868, "text": "Python 3" }, { "code": null, "e": 880, "s": 877, "text": "C#" }, { "code": null, "e": 884, "s": 880, "text": "PHP" }, { "code": "// CPP program to demonstrate Morse code#include <iostream>using namespace std; // function to encode a alphabet as// Morse codestring morseEncode(char x){ // refer to the Morse table // image attached in the article switch (x) { case 'a': return \".-\"; case 'b': return \"-...\"; case 'c': return \"-.-.\"; case 'd': return \"-..\"; case 'e': return \".\"; case 'f': return \"..-.\"; case 'g': return \"--.\"; case 'h': return \"....\"; case 'i': return \"..\"; case 'j': return \".---\"; case 'k': return \"-.-\"; case 'l': return \".-..\"; case 'm': return \"--\"; case 'n': return \"-.\"; case 'o': return \"---\"; case 'p': return \".--.\"; case 'q': return \"--.-\"; case 'r': return \".-.\"; case 's': return \"...\"; case 't': return \"-\"; case 'u': return \"..-\"; case 'v': return \"...-\"; case 'w': return \".--\"; case 'x': return \"-..-\"; case 'y': return \"-.--\"; case 'z': return \"--..\"; case '1': return \".----\"; case '2': return \"..---\"; case '3': return \"...--\"; case '4': return \"....-\"; case '5': return \".....\"; case '6': return \"-....\"; case '7': return \"--...\"; case '8': return \"---..\"; case '9': return \"----.\"; case '0': return \"-----\"; default: cerr << \"Found invalid character: \" << x << ' ' << std::endl; exit(0); }} void morseCode(string s){ // character by character print // Morse code for (int i = 0; s[i]; i++) cout << morseEncode(s[i]); cout << endl;} // Driver's codeint main(){ string s = \"geeksforgeeks\"; morseCode(s); return 0;}", "e": 2738, "s": 884, "text": null }, { "code": "// Java program to demonstrate Morse codeclass GFG{ // function to encode a alphabet as // Morse code static String morseEncode(char x) { // refer to the Morse table // image attached in the article switch (x) { case 'a': return \".-\"; case 'b': return \"-...\"; case 'c': return \"-.-.\"; case 'd': return \"-..\"; case 'e': return \".\"; case 'f': return \"..-.\"; case 'g': return \"--.\"; case 'h': return \"....\"; case 'i': return \"..\"; case 'j': return \".---\"; case 'k': return \"-.-\"; case 'l': return \".-..\"; case 'm': return \"--\"; case 'n': return \"-.\"; case 'o': return \"---\"; case 'p': return \".--.\"; case 'q': return \"--.-\"; case 'r': return \".-.\"; case 's': return \"...\"; case 't': return \"-\"; case 'u': return \"..-\"; case 'v': return \"...-\"; case 'w': return \".--\"; case 'x': return \"-..-\"; case 'y': return \"-.--\"; // for space case 'z': return \"--..\"; case '1': return \".----\"; case '2': return \"..---\"; case '3': return \"...--\"; case '4': return \"....-\"; case '5': return \".....\"; case '6': return \"-....\"; case '7': return \"--...\"; case '8': return \"---..\"; case '9': return \"----.\"; case '0': return \"-----\"; } return \"\"; } static void morseCode(String s) { // character by character print // Morse code for (int i = 0;i<s.length(); i++) System.out.print(morseEncode(s.charAt(i))); System.out.println(); } // Driver code public static void main (String[] args) { String s = \"geeksforgeeks\"; morseCode(s); }} // This code is contributed by Anant Agarwal.", "e": 5292, "s": 2738, "text": null }, { "code": "# Python3 program to demonstrate Morse code # function to encode a alphabet as# Morse codedef morseEncode(x): # refer to the Morse table # image attached in the article if x is 'a': return \".-\" elif x is 'b': return \"-...\" elif x is 'c': return \"-.-.\" elif x is 'd': return \"-..\" elif x is 'e': return \".\" elif x is 'f': return \"..-.\" elif x is 'g': return \"--.\" elif x is 'h': return \"....\" elif x is 'i': return \"..\" elif x is 'j': return \".---\" elif x is 'k': return \"-.-\" elif x is 'l': return \".-..\" elif x is 'm': return \"--\" elif x is 'n': return \"-.\" elif x is 'o': return \"---\" elif x is 'p': return \".--.\" elif x is 'q': return \"--.-\" elif x is 'r': return \".-.\" elif x is 's': return \"...\" elif x is 't': return \"-\" elif x is 'u': return \"..-\" elif x is 'v': return \"...-\" elif x is 'w': return \".--\" elif x is 'x': return \"-..-\" elif x is 'y': return \"-.--\" elif x is 'z': return \"--..\" elif x is '1': return \".----\"; elif x is '2': return \"..---\"; elif x is '3': return \"...--\"; elif x is '4': return \"....-\"; elif x is '5': return \".....\"; elif x is '6': return \"-....\"; elif x is '7': return \"--...\"; elif x is '8': return \"---..\"; elif x is '9': return \"----.\"; elif x is '0': return \"-----\"; # character by character print# Morse codedef morseCode(s): for character in s: print(morseEncode(character), end = \"\") # Driver Codeif __name__ == \"__main__\": s = \"geeksforgeeks\" morseCode(s) # This code is contributed# by Vivek Kumar Singh", "e": 7130, "s": 5292, "text": null }, { "code": "// C# program to demonstrate Morse codeusing System; class GFG{ // function to encode a alphabet as // Morse code static string morseEncode(char x) { // refer to the Morse table // image attached in the article switch (x) { case 'a': return \".-\"; case 'b': return \"-...\"; case 'c': return \"-.-.\"; case 'd': return \"-..\"; case 'e': return \".\"; case 'f': return \"..-.\"; case 'g': return \"--.\"; case 'h': return \"....\"; case 'i': return \"..\"; case 'j': return \".---\"; case 'k': return \"-.-\"; case 'l': return \".-..\"; case 'm': return \"--\"; case 'n': return \"-.\"; case 'o': return \"---\"; case 'p': return \".--.\"; case 'q': return \"--.-\"; case 'r': return \".-.\"; case 's': return \"...\"; case 't': return \"-\"; case 'u': return \"..-\"; case 'v': return \"...-\"; case 'w': return \".--\"; case 'x': return \"-..-\"; case 'y': return \"-.--\"; // for space case 'z': return \"--..\"; case '1': return \".----\"; case '2': return \"..---\"; case '3': return \"...--\"; case '4': return \"....-\"; case '5': return \".....\"; case '6': return \"-....\"; case '7': return \"--...\"; case '8': return \"---..\"; case '9': return \"----.\"; case '0': return \"-----\"; } return \"\"; } static void morseCode(string s) { // character by character print // Morse code for (int i = 0;i<s.Length; i++) Console.Write(morseEncode(s[i])); Console.WriteLine(); } // Driver code public static void Main () { string s = \"geeksforgeeks\"; morseCode(s); }} // This code is contributed by vt_m.", "e": 9674, "s": 7130, "text": null }, { "code": "<?php// php program to demonstrate// Morse code // function to encode a // alphabet as Morse codefunction morseEncode($x){ // refer to the Morse table // image attached in the article switch ($x) { case 'a': return \".-\"; case 'b': return \"-...\"; case 'c': return \"-.-.\"; case 'd': return \"-..\"; case 'e': return \".\"; case 'f': return \"..-.\"; case 'g': return \"--.\"; case 'h': return \"....\"; case 'i': return \"..\"; case 'j': return \".---\"; case 'k': return \"-.-\"; case 'l': return \".-..\"; case 'm': return \"--\"; case 'n': return \"-.\"; case 'o': return \"---\"; case 'p': return \".--.\"; case 'q': return \"--.-\"; case 'r': return \".-.\"; case 's': return \"...\"; case 't': return \"-\"; case 'u': return \"..-\"; case 'v': return \"...-\"; case 'w': return \".--\"; case 'x': return \"-..-\"; case 'y': return \"-.--\"; case '1': return \".----\"; case '2': return \"..---\"; case '3': return \"...--\"; case '4': return \"....-\"; case '5': return \".....\"; case '6': return \"-....\"; case '7': return \"--...\"; case '8': return \"---..\"; case '9': return \"----.\"; case '0': return \"-----\"; // for space case 'z': return \"--..\"; }} function morseCode($s){ // Character by character // print Morse code for ($i = 0; $i<strlen($s); $i++) echo morseEncode($s[$i]); echo \"\\n\";} // Driver code$s = \"geeksforgeeks\";morseCode($s); // This code is contributed by mits?>", "e": 11358, "s": 9674, "text": null }, { "code": null, "e": 11368, "s": 11358, "text": "Output: " }, { "code": null, "e": 11401, "s": 11368, "text": "--...-.-.....-.---.-.--...-.-..." }, { "code": null, "e": 11416, "s": 11403, "text": "Mithun Kumar" }, { "code": null, "e": 11433, "s": 11416, "text": "Vivekkumar Singh" }, { "code": null, "e": 11450, "s": 11433, "text": "siddhantdugar241" }, { "code": null, "e": 11468, "s": 11450, "text": "encoding-decoding" }, { "code": null, "e": 11476, "s": 11468, "text": "Strings" }, { "code": null, "e": 11484, "s": 11476, "text": "Strings" } ]
How to use Anchor tag as submit button ?
07 Apr, 2021 The <a> (anchor tag) in HTML is used to create a hyperlink on the webpage. This hyperlink is used to link the webpage to other web pages. It’s either used to provide an absolute reference or a relative reference as its “href” value. Syntax: <a href = "link"> Link Name </a> The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. You can use href=”#top” or href=”#” to link to the top of the current page. To use the anchor tag as submit button, we need the help of JavaScript. To submit the form, we use JavaScript .submit() function. The function submits the form. Syntax: document.getElementById("GFG").submit(); Note: “GFG” is the ‘id’ mentioned in the form element. Example 1: index.html <!DOCTYPE html><html> <body> <h2>Use Anchor tag as Submit button</h2> <form id="GFG" action="submit.php" method="POST"> Username <br /> <input type="text" name="UserName" id="UserName" /> <br /> Password <br /> <input type="password" name="Password" id="Password" /> <br /> <a href="#" onclick="myFunction()"> Click here to submit form </a> </form> <script> function myFunction() { document.getElementById("GFG").submit(); } </script> </body></html> Note: We can also call the .submit() function, by writing JavaScript as <a href="javascript:$('GFG').submit();" >Click here to submit form</a> Example 2: HTML Code: index.html <!DOCTYPE html><html> <body> <h1>Use Anchor tag as Submit button</h1> <form id="GFG" action="submit.php" method="POST"> Username <br /> <input type="text" name="UserName" id="UserName" /> <br /> Password <br /> <input type="password" name="Password" id="Password" /> <br /> <a href="javascript:$('GFG').submit();"> Click here to submit form </a> </form> </body></html> Output: anchor tag PHP code: The following code is the content for “submit.php” used in the above HTML code. We have to add some PHP code to send data to the database (use local server XAMPP to test the below code). submit.php <?php$servername = "localhost";$username = "root";$password = "";$dbname = "student"; // Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}$name= $_POST['UserName'];$pwd= $_POST['Password']; $sql = "INSERT INTO student (firstname, password) VALUES ('$name','$pwd')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully";} else { echo "Error: " . $sql . "<br>" . mysqli_error($conn);} mysqli_close($conn);?> Output: Now, add some data in the form. Suppose Username is ‘Akshit’ and password is ‘123’ Now, add some data in the form. Suppose Username is ‘Akshit’ and password is ‘123’ Now click on the hyperlink “Click here to submit form“. Now click on the hyperlink “Click here to submit form“. Let us have a look at the ‘student’ database.Data table Let us have a look at the ‘student’ database. Data table HTML-Tags jQuery-Methods PHP-MySQL Picked HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Apr, 2021" }, { "code": null, "e": 286, "s": 53, "text": "The <a> (anchor tag) in HTML is used to create a hyperlink on the webpage. This hyperlink is used to link the webpage to other web pages. It’s either used to provide an absolute reference or a relative reference as its “href” value." }, { "code": null, "e": 294, "s": 286, "text": "Syntax:" }, { "code": null, "e": 327, "s": 294, "text": "<a href = \"link\"> Link Name </a>" }, { "code": null, "e": 545, "s": 327, "text": "The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. You can use href=”#top” or href=”#” to link to the top of the current page." }, { "code": null, "e": 707, "s": 545, "text": "To use the anchor tag as submit button, we need the help of JavaScript. To submit the form, we use JavaScript .submit() function. The function submits the form." }, { "code": null, "e": 715, "s": 707, "text": "Syntax:" }, { "code": null, "e": 756, "s": 715, "text": "document.getElementById(\"GFG\").submit();" }, { "code": null, "e": 811, "s": 756, "text": "Note: “GFG” is the ‘id’ mentioned in the form element." }, { "code": null, "e": 822, "s": 811, "text": "Example 1:" }, { "code": null, "e": 833, "s": 822, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <body> <h2>Use Anchor tag as Submit button</h2> <form id=\"GFG\" action=\"submit.php\" method=\"POST\"> Username <br /> <input type=\"text\" name=\"UserName\" id=\"UserName\" /> <br /> Password <br /> <input type=\"password\" name=\"Password\" id=\"Password\" /> <br /> <a href=\"#\" onclick=\"myFunction()\"> Click here to submit form </a> </form> <script> function myFunction() { document.getElementById(\"GFG\").submit(); } </script> </body></html>", "e": 1486, "s": 833, "text": null }, { "code": null, "e": 1558, "s": 1486, "text": "Note: We can also call the .submit() function, by writing JavaScript as" }, { "code": null, "e": 1629, "s": 1558, "text": "<a href=\"javascript:$('GFG').submit();\" >Click here to submit form</a>" }, { "code": null, "e": 1640, "s": 1629, "text": "Example 2:" }, { "code": null, "e": 1651, "s": 1640, "text": "HTML Code:" }, { "code": null, "e": 1662, "s": 1651, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <body> <h1>Use Anchor tag as Submit button</h1> <form id=\"GFG\" action=\"submit.php\" method=\"POST\"> Username <br /> <input type=\"text\" name=\"UserName\" id=\"UserName\" /> <br /> Password <br /> <input type=\"password\" name=\"Password\" id=\"Password\" /> <br /> <a href=\"javascript:$('GFG').submit();\"> Click here to submit form </a> </form> </body></html>", "e": 2183, "s": 1662, "text": null }, { "code": null, "e": 2191, "s": 2183, "text": "Output:" }, { "code": null, "e": 2202, "s": 2191, "text": "anchor tag" }, { "code": null, "e": 2399, "s": 2202, "text": "PHP code: The following code is the content for “submit.php” used in the above HTML code. We have to add some PHP code to send data to the database (use local server XAMPP to test the below code)." }, { "code": null, "e": 2410, "s": 2399, "text": "submit.php" }, { "code": "<?php$servername = \"localhost\";$username = \"root\";$password = \"\";$dbname = \"student\"; // Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) { die(\"Connection failed: \" . mysqli_connect_error());}$name= $_POST['UserName'];$pwd= $_POST['Password']; $sql = \"INSERT INTO student (firstname, password) VALUES ('$name','$pwd')\"; if (mysqli_query($conn, $sql)) { echo \"New record created successfully\";} else { echo \"Error: \" . $sql . \"<br>\" . mysqli_error($conn);} mysqli_close($conn);?>", "e": 2963, "s": 2410, "text": null }, { "code": null, "e": 2971, "s": 2963, "text": "Output:" }, { "code": null, "e": 3054, "s": 2971, "text": "Now, add some data in the form. Suppose Username is ‘Akshit’ and password is ‘123’" }, { "code": null, "e": 3137, "s": 3054, "text": "Now, add some data in the form. Suppose Username is ‘Akshit’ and password is ‘123’" }, { "code": null, "e": 3194, "s": 3137, "text": "Now click on the hyperlink “Click here to submit form“." }, { "code": null, "e": 3251, "s": 3194, "text": "Now click on the hyperlink “Click here to submit form“." }, { "code": null, "e": 3307, "s": 3251, "text": "Let us have a look at the ‘student’ database.Data table" }, { "code": null, "e": 3353, "s": 3307, "text": "Let us have a look at the ‘student’ database." }, { "code": null, "e": 3364, "s": 3353, "text": "Data table" }, { "code": null, "e": 3374, "s": 3364, "text": "HTML-Tags" }, { "code": null, "e": 3389, "s": 3374, "text": "jQuery-Methods" }, { "code": null, "e": 3399, "s": 3389, "text": "PHP-MySQL" }, { "code": null, "e": 3406, "s": 3399, "text": "Picked" }, { "code": null, "e": 3411, "s": 3406, "text": "HTML" }, { "code": null, "e": 3418, "s": 3411, "text": "JQuery" }, { "code": null, "e": 3435, "s": 3418, "text": "Web Technologies" }, { "code": null, "e": 3440, "s": 3435, "text": "HTML" } ]
How to overlap two Barplots in Seaborn?
25 Jan, 2022 Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and colour palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas. Bar Plot is used to represent categories of data using rectangular bars. We can overlap two barplots in seaborn by creating subplots. Steps required to overlap two barplots in seaborn: Importing seaborn and matplotlib library, seaborn for plotting graph and matplotlib for using subplot().Creating dataframe.Creating two subplots on the same axes.Displaying the plot. Importing seaborn and matplotlib library, seaborn for plotting graph and matplotlib for using subplot(). Creating dataframe. Creating two subplots on the same axes. Displaying the plot. Below are some examples based on the above approach: Example 1: Python3 # importing all required librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'X': [1, 2, 3], 'Y': [3, 4, 5], 'Z': [2, 1, 2]}) # creating subplotsax = plt.subplots() # plotting columnsax = sns.barplot(x=df["X"], y=df["Y"], color='b')ax = sns.barplot(x=df["X"], y=df["Z"], color='r') # renaming the axesax.set(xlabel="x-axis", ylabel="y-axis") # visualizing illustrationplt.show() Output: Example 2: Python3 #importing all required librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt #creating dataframedf=pd.DataFrame({ 'X':[i for i in range(10,110,10)], 'Y':[i for i in range(100,0,-10)], 'Z':[i for i in range(10,110,10)]}) #creating subplotsax=plt.subplots() #plotting columnsax=sns.barplot(x=df["X"],y=df["Y"],color = 'lime')ax=sns.barplot(x=df["X"],y=df["Z"],color = 'green') #renaming the axesax.set(xlabel="x-axis", ylabel="y-axis") # visualizing illustrationplt.show() Output: clintra Picked Python-Seaborn Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jan, 2022" }, { "code": null, "e": 326, "s": 28, "text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and colour palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas." }, { "code": null, "e": 460, "s": 326, "text": "Bar Plot is used to represent categories of data using rectangular bars. We can overlap two barplots in seaborn by creating subplots." }, { "code": null, "e": 511, "s": 460, "text": "Steps required to overlap two barplots in seaborn:" }, { "code": null, "e": 695, "s": 511, "text": "Importing seaborn and matplotlib library, seaborn for plotting graph and matplotlib for using subplot().Creating dataframe.Creating two subplots on the same axes.Displaying the plot." }, { "code": null, "e": 801, "s": 695, "text": "Importing seaborn and matplotlib library, seaborn for plotting graph and matplotlib for using subplot()." }, { "code": null, "e": 821, "s": 801, "text": "Creating dataframe." }, { "code": null, "e": 861, "s": 821, "text": "Creating two subplots on the same axes." }, { "code": null, "e": 882, "s": 861, "text": "Displaying the plot." }, { "code": null, "e": 935, "s": 882, "text": "Below are some examples based on the above approach:" }, { "code": null, "e": 946, "s": 935, "text": "Example 1:" }, { "code": null, "e": 954, "s": 946, "text": "Python3" }, { "code": "# importing all required librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'X': [1, 2, 3], 'Y': [3, 4, 5], 'Z': [2, 1, 2]}) # creating subplotsax = plt.subplots() # plotting columnsax = sns.barplot(x=df[\"X\"], y=df[\"Y\"], color='b')ax = sns.barplot(x=df[\"X\"], y=df[\"Z\"], color='r') # renaming the axesax.set(xlabel=\"x-axis\", ylabel=\"y-axis\") # visualizing illustrationplt.show()", "e": 1411, "s": 954, "text": null }, { "code": null, "e": 1419, "s": 1411, "text": "Output:" }, { "code": null, "e": 1430, "s": 1419, "text": "Example 2:" }, { "code": null, "e": 1438, "s": 1430, "text": "Python3" }, { "code": "#importing all required librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt #creating dataframedf=pd.DataFrame({ 'X':[i for i in range(10,110,10)], 'Y':[i for i in range(100,0,-10)], 'Z':[i for i in range(10,110,10)]}) #creating subplotsax=plt.subplots() #plotting columnsax=sns.barplot(x=df[\"X\"],y=df[\"Y\"],color = 'lime')ax=sns.barplot(x=df[\"X\"],y=df[\"Z\"],color = 'green') #renaming the axesax.set(xlabel=\"x-axis\", ylabel=\"y-axis\") # visualizing illustrationplt.show()", "e": 1946, "s": 1438, "text": null }, { "code": null, "e": 1958, "s": 1950, "text": "Output:" }, { "code": null, "e": 1970, "s": 1962, "text": "clintra" }, { "code": null, "e": 1977, "s": 1970, "text": "Picked" }, { "code": null, "e": 1992, "s": 1977, "text": "Python-Seaborn" }, { "code": null, "e": 2016, "s": 1992, "text": "Technical Scripter 2020" }, { "code": null, "e": 2023, "s": 2016, "text": "Python" }, { "code": null, "e": 2042, "s": 2023, "text": "Technical Scripter" } ]
How to trigger a file download when clicking an HTML button or JavaScript?
21 Jul, 2021 To trigger a file download on a button click we will use a custom function or HTML 5 download attribute.Approach 1: Using Download attribute The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded. The name of the file can be set using the attribute value name, if not provided then the original filename will be used.Syntax <a download="filename"> filename: attribute specifies the name for the file that will be downloaded.Example: html <!DOCTYPE html><html> <body> <style> p { color: green; } </style> <p>How to trigger a file download when clicking an HTML button or JavaScript? <p> <!-- GFG is the name of the file to be downloaded--> <!-- In order to run the code, the location of the file "geeksforgeeks.png" needs to be changed to your local directory, both the HTML and downloadable file needs to be present in the same directory --> <a href="geeksforgeeks.png" download="GFG"> <button type="button">Download</button> </a> </body></html> Output: Approach 2: Using a custom javascript function firstly made a textarea where all the text input will be issued. make an anchor tag using createElement property and then assigning it the download and href attribute. encodeURIComponent will encode everything with special meaning, so you use it for components of URIs. For example, if we have text like “Hello: Geek ?”, there are special characters in this, so encodeURIComponent will encode them and append it for further usage. data:text/plain; charset=utf-8 is the attribute value of href (like href=” “), it specifies that the value must be of type text and with UTF-8 type encoding. The click() method simulates a mouse-click on an element. After that we simply call our download function with the text from textarea and our file name “GFG.txt” as parameters on the input button with id ‘btn’. Example: html <!DOCTYPE html><html> <body> <style> p { color: green; } </style> <p> How to trigger a file download when clicking an HTML button or JavaScript? <p> <textarea id="text"> Welcome to GeeksforGeeks </textarea> <br/> <input type="button" id="btn" value="Download" /> <script> function download(file, text) { //creating an invisible element var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8, ' + encodeURIComponent(text)); element.setAttribute('download', file); // Above code is equivalent to // <a href="path of file" download="file name"> document.body.appendChild(element); //onClick property element.click(); document.body.removeChild(element); } // Start file download. document.getElementById("btn") .addEventListener("click", function() { // Generate download of hello.txt // file with some content var text = document.getElementById("text").value; var filename = "GFG.txt"; download(filename, text); }, false); </script> </body></html> Output: Approach 3: Using a custom javascript function with Axios LibraryIn this example, we will download images and file using Axios. This requires a little intermediate knowledge of the JavaScript to work and in this example a Axios library will be used. html <!DOCTYPE html><!DOCTYPE html><html> <head> <title>Download Images using Axios</title> <style> .scroll { height: 1000px; background-color: white; } </style> </head> <body> <p id="dest"> <h1 style="color: green"> GeeksforGeeks </h1> </p> <button onclick="download()"> Download Image </button> <p class="scroll"> By clicking the download button will generate a random image. </p> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"> </script> <script> function download(){ axios({ url:'https://source.unsplash.com/random/500x500', method:'GET', responseType: 'blob' }) .then((response) => { const url = window.URL .createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'image.jpg'); document.body.appendChild(link); link.click(); }) } </script></html></html> JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. polokghosh53 JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jul, 2021" }, { "code": null, "e": 436, "s": 52, "text": "To trigger a file download on a button click we will use a custom function or HTML 5 download attribute.Approach 1: Using Download attribute The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded. The name of the file can be set using the attribute value name, if not provided then the original filename will be used.Syntax " }, { "code": null, "e": 461, "s": 436, "text": "<a download=\"filename\">\n" }, { "code": null, "e": 548, "s": 461, "text": "filename: attribute specifies the name for the file that will be downloaded.Example: " }, { "code": null, "e": 553, "s": 548, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <style> p { color: green; } </style> <p>How to trigger a file download when clicking an HTML button or JavaScript? <p> <!-- GFG is the name of the file to be downloaded--> <!-- In order to run the code, the location of the file \"geeksforgeeks.png\" needs to be changed to your local directory, both the HTML and downloadable file needs to be present in the same directory --> <a href=\"geeksforgeeks.png\" download=\"GFG\"> <button type=\"button\">Download</button> </a> </body></html>", "e": 1229, "s": 553, "text": null }, { "code": null, "e": 1239, "s": 1229, "text": "Output: " }, { "code": null, "e": 1288, "s": 1239, "text": "Approach 2: Using a custom javascript function " }, { "code": null, "e": 1353, "s": 1288, "text": "firstly made a textarea where all the text input will be issued." }, { "code": null, "e": 1456, "s": 1353, "text": "make an anchor tag using createElement property and then assigning it the download and href attribute." }, { "code": null, "e": 1719, "s": 1456, "text": "encodeURIComponent will encode everything with special meaning, so you use it for components of URIs. For example, if we have text like “Hello: Geek ?”, there are special characters in this, so encodeURIComponent will encode them and append it for further usage." }, { "code": null, "e": 1935, "s": 1719, "text": "data:text/plain; charset=utf-8 is the attribute value of href (like href=” “), it specifies that the value must be of type text and with UTF-8 type encoding. The click() method simulates a mouse-click on an element." }, { "code": null, "e": 2088, "s": 1935, "text": "After that we simply call our download function with the text from textarea and our file name “GFG.txt” as parameters on the input button with id ‘btn’." }, { "code": null, "e": 2099, "s": 2088, "text": "Example: " }, { "code": null, "e": 2104, "s": 2099, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <style> p { color: green; } </style> <p> How to trigger a file download when clicking an HTML button or JavaScript? <p> <textarea id=\"text\"> Welcome to GeeksforGeeks </textarea> <br/> <input type=\"button\" id=\"btn\" value=\"Download\" /> <script> function download(file, text) { //creating an invisible element var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8, ' + encodeURIComponent(text)); element.setAttribute('download', file); // Above code is equivalent to // <a href=\"path of file\" download=\"file name\"> document.body.appendChild(element); //onClick property element.click(); document.body.removeChild(element); } // Start file download. document.getElementById(\"btn\") .addEventListener(\"click\", function() { // Generate download of hello.txt // file with some content var text = document.getElementById(\"text\").value; var filename = \"GFG.txt\"; download(filename, text); }, false); </script> </body></html>", "e": 3660, "s": 2104, "text": null }, { "code": null, "e": 3670, "s": 3660, "text": "Output: " }, { "code": null, "e": 3921, "s": 3670, "text": "Approach 3: Using a custom javascript function with Axios LibraryIn this example, we will download images and file using Axios. This requires a little intermediate knowledge of the JavaScript to work and in this example a Axios library will be used. " }, { "code": null, "e": 3926, "s": 3921, "text": "html" }, { "code": "<!DOCTYPE html><!DOCTYPE html><html> <head> <title>Download Images using Axios</title> <style> .scroll { height: 1000px; background-color: white; } </style> </head> <body> <p id=\"dest\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> </p> <button onclick=\"download()\"> Download Image </button> <p class=\"scroll\"> By clicking the download button will generate a random image. </p> </body> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js\"> </script> <script> function download(){ axios({ url:'https://source.unsplash.com/random/500x500', method:'GET', responseType: 'blob' }) .then((response) => { const url = window.URL .createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'image.jpg'); document.body.appendChild(link); link.click(); }) } </script></html></html>", "e": 5144, "s": 3926, "text": null }, { "code": null, "e": 5363, "s": 5144, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 5376, "s": 5363, "text": "polokghosh53" }, { "code": null, "e": 5392, "s": 5376, "text": "JavaScript-Misc" }, { "code": null, "e": 5399, "s": 5392, "text": "Picked" }, { "code": null, "e": 5410, "s": 5399, "text": "JavaScript" }, { "code": null, "e": 5427, "s": 5410, "text": "Web Technologies" }, { "code": null, "e": 5454, "s": 5427, "text": "Web technologies Questions" } ]
Displaying XML Using CSS
09 Jun, 2022 XML stands for Extensible Markup Language. It is a dynamic markup language. It is used to transform data from one form to another form.An XML file can be displayed using two ways. These are as follows :- Cascading Style SheetExtensible Stylesheet Language TransformationDisplaying XML file using CSS :CSS can be used to display the contents of the XML document in a clear and precise manner. It gives the design and style to whole XML document.Basic steps in defining a CSS style sheet for XML :For defining the style rules for the XML document, the following things should be done :-Define the style rules for the text elements such as font-size, color, font-weight, etc.Define each element either as a block, inline or list element, using the display property of CSS.Identify the titles and bold them.Linking XML with CSS :In order to display the XML file using CSS, link XML file with CSS. Below is the syntax for linking the XML file with CSS:<?xml-stylesheet type="text/css" href="name_of_css_file.css"?>Example 1.In this example, the XML file is created that contains the information about five books and displaying the XML file using CSS.XML file :Creating Books.xml as :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Rule.css"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books>In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules.CSS FILE :Creating Rule.css as:-books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;}Output :Example 2.In this example, the XML file is created that contains the information about various sections in Geeks for Geeks and the topics they contains and after that displaying the XML file using CSS .XML file :Creating Section.xml as :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Geeks.css"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules.CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }Output :Advantages of displaying XML using CSS:CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster.Disadvantages of displaying XML using CSS :Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.My Personal Notes arrow_drop_upSave Cascading Style Sheet Extensible Stylesheet Language Transformation Displaying XML file using CSS :CSS can be used to display the contents of the XML document in a clear and precise manner. It gives the design and style to whole XML document. Basic steps in defining a CSS style sheet for XML :For defining the style rules for the XML document, the following things should be done :-Define the style rules for the text elements such as font-size, color, font-weight, etc.Define each element either as a block, inline or list element, using the display property of CSS.Identify the titles and bold them. Define the style rules for the text elements such as font-size, color, font-weight, etc.Define each element either as a block, inline or list element, using the display property of CSS.Identify the titles and bold them. Define the style rules for the text elements such as font-size, color, font-weight, etc. Define each element either as a block, inline or list element, using the display property of CSS. Identify the titles and bold them. Linking XML with CSS :In order to display the XML file using CSS, link XML file with CSS. Below is the syntax for linking the XML file with CSS:<?xml-stylesheet type="text/css" href="name_of_css_file.css"?> <?xml-stylesheet type="text/css" href="name_of_css_file.css"?> Example 1.In this example, the XML file is created that contains the information about five books and displaying the XML file using CSS.XML file :Creating Books.xml as :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Rule.css"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books>In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules.CSS FILE :Creating Rule.css as:-books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;}Output :Example 2.In this example, the XML file is created that contains the information about various sections in Geeks for Geeks and the topics they contains and after that displaying the XML file using CSS .XML file :Creating Section.xml as :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Geeks.css"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules.CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }Output :Advantages of displaying XML using CSS:CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster.Disadvantages of displaying XML using CSS :Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.My Personal Notes arrow_drop_upSave XML file :Creating Books.xml as :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Rule.css"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books>In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules. <?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Rule.css"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books> In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules. CSS FILE :Creating Rule.css as:-books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;} books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;} Output : Example 2.In this example, the XML file is created that contains the information about various sections in Geeks for Geeks and the topics they contains and after that displaying the XML file using CSS .XML file :Creating Section.xml as :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Geeks.css"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules.CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }Output :Advantages of displaying XML using CSS:CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster.Disadvantages of displaying XML using CSS :Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.My Personal Notes arrow_drop_upSave XML file :Creating Section.xml as :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Geeks.css"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules. <?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="Geeks.css"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks> In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules. CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange } Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange } Output : Advantages of displaying XML using CSS: CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster. CSS is used in XML or HTML to decorate the pages. CSS is used for interactive interface, so it is understandable by user. CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster. Disadvantages of displaying XML using CSS : Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user. Using CSS, no transformation can be applied to the XML documents. CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live. CSS have different level of versions, so it is confusing for the browser and user. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. surinderdawra388 CSS-Misc Web technologies-HTML and XML CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Jun, 2022" }, { "code": null, "e": 257, "s": 53, "text": "XML stands for Extensible Markup Language. It is a dynamic markup language. It is used to transform data from one form to another form.An XML file can be displayed using two ways. These are as follows :-" }, { "code": null, "e": 6390, "s": 257, "text": "Cascading Style SheetExtensible Stylesheet Language TransformationDisplaying XML file using CSS :CSS can be used to display the contents of the XML document in a clear and precise manner. It gives the design and style to whole XML document.Basic steps in defining a CSS style sheet for XML :For defining the style rules for the XML document, the following things should be done :-Define the style rules for the text elements such as font-size, color, font-weight, etc.Define each element either as a block, inline or list element, using the display property of CSS.Identify the titles and bold them.Linking XML with CSS :In order to display the XML file using CSS, link XML file with CSS. Below is the syntax for linking the XML file with CSS:<?xml-stylesheet type=\"text/css\" href=\"name_of_css_file.css\"?>Example 1.In this example, the XML file is created that contains the information about five books and displaying the XML file using CSS.XML file :Creating Books.xml as :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Rule.css\"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books>In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules.CSS FILE :Creating Rule.css as:-books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;}Output :Example 2.In this example, the XML file is created that contains the information about various sections in Geeks for Geeks and the topics they contains and after that displaying the XML file using CSS .XML file :Creating Section.xml as :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Geeks.css\"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules.CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }Output :Advantages of displaying XML using CSS:CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster.Disadvantages of displaying XML using CSS :Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 6412, "s": 6390, "text": "Cascading Style Sheet" }, { "code": null, "e": 6458, "s": 6412, "text": "Extensible Stylesheet Language Transformation" }, { "code": null, "e": 6633, "s": 6458, "text": "Displaying XML file using CSS :CSS can be used to display the contents of the XML document in a clear and precise manner. It gives the design and style to whole XML document." }, { "code": null, "e": 6993, "s": 6633, "text": "Basic steps in defining a CSS style sheet for XML :For defining the style rules for the XML document, the following things should be done :-Define the style rules for the text elements such as font-size, color, font-weight, etc.Define each element either as a block, inline or list element, using the display property of CSS.Identify the titles and bold them." }, { "code": null, "e": 7213, "s": 6993, "text": "Define the style rules for the text elements such as font-size, color, font-weight, etc.Define each element either as a block, inline or list element, using the display property of CSS.Identify the titles and bold them." }, { "code": null, "e": 7302, "s": 7213, "text": "Define the style rules for the text elements such as font-size, color, font-weight, etc." }, { "code": null, "e": 7400, "s": 7302, "text": "Define each element either as a block, inline or list element, using the display property of CSS." }, { "code": null, "e": 7435, "s": 7400, "text": "Identify the titles and bold them." }, { "code": null, "e": 7642, "s": 7435, "text": "Linking XML with CSS :In order to display the XML file using CSS, link XML file with CSS. Below is the syntax for linking the XML file with CSS:<?xml-stylesheet type=\"text/css\" href=\"name_of_css_file.css\"?>" }, { "code": null, "e": 7705, "s": 7642, "text": "<?xml-stylesheet type=\"text/css\" href=\"name_of_css_file.css\"?>" }, { "code": null, "e": 13033, "s": 7705, "text": "Example 1.In this example, the XML file is created that contains the information about five books and displaying the XML file using CSS.XML file :Creating Books.xml as :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Rule.css\"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books>In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules.CSS FILE :Creating Rule.css as:-books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;}Output :Example 2.In this example, the XML file is created that contains the information about various sections in Geeks for Geeks and the topics they contains and after that displaying the XML file using CSS .XML file :Creating Section.xml as :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Geeks.css\"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules.CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }Output :Advantages of displaying XML using CSS:CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster.Disadvantages of displaying XML using CSS :Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 14520, "s": 13033, "text": "XML file :Creating Books.xml as :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Rule.css\"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books>In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules." }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Rule.css\"?><books> <heading>Welcome To GeeksforGeeks </heading> <book> <title>Title -: Web Programming</title> <author>Author -: Chrisbates</author> <publisher>Publisher -: Wiley</publisher> <edition>Edition -: 3</edition> <price> Price -: 300</price> </book> <book> <title>Title -: Internet world-wide-web</title> <author>Author -: Ditel</author> <publisher>Publisher -: Pearson</publisher> <edition>Edition -: 3</edition> <price>Price -: 400</price> </book> <book> <title>Title -: Computer Networks</title> <author>Author -: Foruouzan</author> <publisher>Publisher -: Mc Graw Hill</publisher> <edition>Edition -: 5</edition> <price>Price -: 700</price> </book> <book> <title>Title -: DBMS Concepts</title> <author>Author -: Navath</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 5</edition> <price>Price -: 600</price> </book> <book> <title>Title -: Linux Programming</title> <author>Author -: Subhitab Das</author> <publisher>Publisher -: Oxford</publisher> <edition>Edition -: 8</edition> <price>Price -: 300</price> </book></books>", "e": 15866, "s": 14520, "text": null }, { "code": null, "e": 15974, "s": 15866, "text": "In the above example, Books.xml is linked with Rule.css which contains the corresponding style sheet rules." }, { "code": null, "e": 16294, "s": 15974, "text": "CSS FILE :Creating Rule.css as:-books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;}" }, { "code": "books { color: white; background-color : gray; width: 100%;} heading { color: green; font-size : 40px; background-color : powderblue;} heading, title, author, publisher, edition, price { display : block;} title { font-size : 25px; font-weight : bold;}", "e": 16582, "s": 16294, "text": null }, { "code": null, "e": 16591, "s": 16582, "text": "Output :" }, { "code": null, "e": 19970, "s": 16591, "text": "Example 2.In this example, the XML file is created that contains the information about various sections in Geeks for Geeks and the topics they contains and after that displaying the XML file using CSS .XML file :Creating Section.xml as :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Geeks.css\"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules.CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }Output :Advantages of displaying XML using CSS:CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster.Disadvantages of displaying XML using CSS :Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 21313, "s": 19970, "text": "XML file :Creating Section.xml as :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Geeks.css\"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules." }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"Geeks.css\"?><Geeks_for_Geeks> <title>Hello Everyone! Welcome to GeeksforGeeks</title> <geeks_section> <name>Algo</name> <topic1>Greedy Algo</topic1> <topic2>Randomised Algo</topic2> <topic3>Searching Algo</topic3> <topic4>Sorting Algo</topic4> </geeks_section> <geeks_section> <name>Data Structures</name> <topic1>Array</topic1> <topic2>Stack</topic2> <topic3>Queue</topic3> <topic4>Linked List</topic4> </geeks_section> <geeks_section> <name>Web Technology</name> <topic1>HTML</topic1> <topic2>CSS</topic2> <topic3>Java Script</topic3> <topic4>Php</topic4> </geeks_section> <geeks_section> <name>Languages</name> <topic1>C/C++</topic1> <topic2>Java</topic2> <topic3>Python</topic3> <topic4>Ruby</topic4> </geeks_section> <geeks_section> <name>DBMS</name> <topic1>Basics</topic1> <topic2>ER Diagram</topic2> <topic3>Normalization</topic3> <topic4>Transaction Concepts</topic4> </geeks_section></Geeks_for_Geeks>", "e": 22510, "s": 21313, "text": null }, { "code": null, "e": 22621, "s": 22510, "text": "In the above example, Section.xml is linked with Geeks.css which contains the corresponding style sheet rules." }, { "code": null, "e": 23586, "s": 22621, "text": "CSS FILE :Creating Geeks.css as:-Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }" }, { "code": "Geeks_for_Geeks { font-size:80%; margin:0.5em; font-family: Verdana; display:block; }geeks_section { display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-color:whitesmoke; }title { display:block; font-weight:bolder; text-align:center; font-size:30px; background-color: green; color: white; }name, topic1, topic2, topic3, topic4 { display:block; text-align:center; }name { color:green; text-decoration: underline ; font-weight:bolder; font-size:20px; }topic1 { color:green }topic2 { color:brown }topic3 { color:blue }topic4 { color:orange }", "e": 24518, "s": 23586, "text": null }, { "code": null, "e": 24527, "s": 24518, "text": "Output :" }, { "code": null, "e": 24567, "s": 24527, "text": "Advantages of displaying XML using CSS:" }, { "code": null, "e": 24824, "s": 24567, "text": "CSS is used in XML or HTML to decorate the pages.CSS is used for interactive interface, so it is understandable by user.CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster." }, { "code": null, "e": 24874, "s": 24824, "text": "CSS is used in XML or HTML to decorate the pages." }, { "code": null, "e": 24946, "s": 24874, "text": "CSS is used for interactive interface, so it is understandable by user." }, { "code": null, "e": 25083, "s": 24946, "text": "CSS enable multiple pages to share formatting, and reduce complexity and repetition in the structural content. So page loader is faster." }, { "code": null, "e": 25127, "s": 25083, "text": "Disadvantages of displaying XML using CSS :" }, { "code": null, "e": 25432, "s": 25127, "text": "Using CSS, no transformation can be applied to the XML documents.CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live.CSS have different level of versions, so it is confusing for the browser and user." }, { "code": null, "e": 25498, "s": 25432, "text": "Using CSS, no transformation can be applied to the XML documents." }, { "code": null, "e": 25656, "s": 25498, "text": "CSS uses different dimensions with different browsers. So the programmer has to run the code in different browser and test its compatibility to post it live." }, { "code": null, "e": 25739, "s": 25656, "text": "CSS have different level of versions, so it is confusing for the browser and user." }, { "code": null, "e": 25925, "s": 25739, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 25942, "s": 25925, "text": "surinderdawra388" }, { "code": null, "e": 25951, "s": 25942, "text": "CSS-Misc" }, { "code": null, "e": 25981, "s": 25951, "text": "Web technologies-HTML and XML" }, { "code": null, "e": 25985, "s": 25981, "text": "CSS" }, { "code": null, "e": 26002, "s": 25985, "text": "Web Technologies" } ]
Chinese Remainder Theorem | Set 1 (Introduction)
23 Aug, 2021 We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Basically, we are given k numbers which are pairwise coprime, and given remainders of these numbers when an unknown number x is divided by them. We need to find the minimum possible value of x that produces given remainders.Examples : Input: num[] = {5, 7}, rem[] = {1, 3} Output: 31 Explanation: 31 is the smallest number such that: (1) When we divide it by 5, we get remainder 1. (2) When we divide it by 7, we get remainder 3. Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the smallest number such that: (1) When we divide it by 3, we get remainder 2. (2) When we divide it by 4, we get remainder 3. (3) When we divide it by 5, we get remainder 1. Chinese Remainder Theorem states that there always exists an x that satisfies given congruences. Below is theorem statement adapted from wikipedia. Let num[0], num[1], ...num[k-1] be positive integers that are pairwise coprime. Then, for any given sequence of integers rem[0], rem[1], ... rem[k-1], there exists an integer x solving the following system of simultaneous congruences. The first part is clear that there exists an x. The second part basically states that all solutions (including the minimum one) produce the same remainder when divided by-product of n[0], num[1], .. num[k-1]. In the above example, the product is 3*4*5 = 60. And 11 is one solution, other solutions are 71, 131, .. etc. All these solutions produce the same remainder when divided by 60, i.e., they are of form 11 + m*60 where m >= 0.A Naive Approach to find x is to start with 1 and one by one increment it and check if dividing it with given elements in num[] produces corresponding remainders in rem[]. Once we find such an x, we return it. Below is the implementation of Naive Approach. C++ Java Python3 C# PHP Javascript // A C++ program to demonstrate working of Chinise remainder// Theorem#include<bits/stdc++.h>using namespace std; // k is size of num[] and rem[]. Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[] are pairwise coprime// (gcd for every pair is 1)int findMinX(int num[], int rem[], int k){ int x = 1; // Initialize result // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) int j; for (j=0; j<k; j++ ) if (x%num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } return x;} // Driver methodint main(void){ int num[] = {3, 4, 5}; int rem[] = {2, 3, 1}; int k = sizeof(num)/sizeof(num[0]); cout << "x is " << findMinX(num, rem, k); return 0;} // A Java program to demonstrate the working of Chinese remainder// Theoremimport java.io.*; class GFG { // k is size of num[] and rem[]. Returns the smallest // number x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise coprime // (gcd for every pair is 1) static int findMinX(int num[], int rem[], int k) { int x = 1; // Initialize result // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) int j; for (j=0; j<k; j++ ) if (x%num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } } // Driver method public static void main(String args[]) { int num[] = {3, 4, 5}; int rem[] = {2, 3, 1}; int k = num.length; System.out.println("x is " + findMinX(num, rem, k)); }} /*This code is contributed by Nikita Tiwari.*/ # A Python3 program to demonstrate# working of Chinise remainder Theorem # k is size of num[] and rem[].# Returns the smallest number x# such that:# x % num[0] = rem[0],# x % num[1] = rem[1],# ..................# x % num[k-2] = rem[k-1]# Assumption: Numbers in num[]# are pairwise coprime (gcd for# every pair is 1)def findMinX(num, rem, k): x = 1; # Initialize result # As per the Chinise remainder # theorem, this loop will # always break. while(True): # Check if remainder of # x % num[j] is rem[j] # or not (for all j from # 0 to k-1) j = 0; while(j < k): if (x % num[j] != rem[j]): break; j += 1; # If all remainders # matched, we found x if (j == k): return x; # Else try next number x += 1; # Driver Codenum = [3, 4, 5];rem = [2, 3, 1];k = len(num);print("x is", findMinX(num, rem, k)); # This code is contributed by mits // C# program to demonstrate working// of Chinise remainder Theoremusing System; class GFG{ // k is size of num[] and rem[]. // Returns the smallest // number x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] // are pairwise coprime // (gcd for every pair is 1) static int findMinX(int []num, int []rem, int k) { // Initialize result int x = 1; // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) int j; for (j = 0; j < k; j++ ) if (x % num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } } // Driver code public static void Main() { int []num = {3, 4, 5}; int []rem = {2, 3, 1}; int k = num.Length; Console.WriteLine("x is " + findMinX(num, rem, k)); }} // This code is contributed by Sam007. <?php// A PHP program to demonstrate// working of Chinise remainder Theorem // k is size of num[] and rem[].// Returns the smallest number x// such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[]// are pairwise coprime (gcd for// every pair is 1)function findMinX($num, $rem, $k){ $x = 1; // Initialize result // As per the Chinise remainder // theorem, this loop will // always break. while (true) { // Check if remainder of // x % num[j] is rem[j] // or not (for all j from // 0 to k-1) $j; for ($j = 0; $j < $k; $j++ ) if ($x % $num[$j] != $rem[$j]) break; // If all remainders // matched, we found x if ($j == $k) return $x; // Else try next number $x++; } return $x;} // Driver Code$num = array(3, 4, 5);$rem = array(2, 3, 1);$k = sizeof($num);echo "x is " , findMinX($num, $rem, $k); // This code is contributed by ajit?> <script> // A javascript program to demonstrate the working of Chinese remainder// Theorem // k is size of num and rem. Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num are pairwise coprime// (gcd for every pair is 1)function findMinX(num , rem , k){ var x = 1; // Initialize result // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) var j; for (j=0; j<k; j++ ) if (x%num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } } // Driver methodvar num = [3, 4, 5];var rem = [2, 3, 1];var k = num.length;document.write("x is " + findMinX(num, rem, k)); // This code is contributed by 29AjayKumar </script> Output : x is 11 Time Complexity : O(M), M is the product of all elements of num[] array. Auxiliary Space : O(1) See below link for an efficient method to find x.Chinese Remainder Theorem | Set 2 (Inverse Modulo based Implementation)This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 jit_t Mithun Kumar Adityasharma15 jyoti369 29AjayKumar sumitgumber28 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Aug, 2021" }, { "code": null, "e": 224, "s": 52, "text": "We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: " }, { "code": null, "e": 347, "s": 224, "text": " x % num[0] = rem[0], \n x % num[1] = rem[1], \n .......................\n x % num[k-1] = rem[k-1] " }, { "code": null, "e": 584, "s": 347, "text": "Basically, we are given k numbers which are pairwise coprime, and given remainders of these numbers when an unknown number x is divided by them. We need to find the minimum possible value of x that produces given remainders.Examples : " }, { "code": null, "e": 1045, "s": 584, "text": "Input: num[] = {5, 7}, rem[] = {1, 3}\nOutput: 31\nExplanation: \n31 is the smallest number such that:\n (1) When we divide it by 5, we get remainder 1. \n (2) When we divide it by 7, we get remainder 3.\n\nInput: num[] = {3, 4, 5}, rem[] = {2, 3, 1}\nOutput: 11\nExplanation: \n11 is the smallest number such that:\n (1) When we divide it by 3, we get remainder 2. \n (2) When we divide it by 4, we get remainder 3.\n (3) When we divide it by 5, we get remainder 1." }, { "code": null, "e": 1429, "s": 1045, "text": "Chinese Remainder Theorem states that there always exists an x that satisfies given congruences. Below is theorem statement adapted from wikipedia. Let num[0], num[1], ...num[k-1] be positive integers that are pairwise coprime. Then, for any given sequence of integers rem[0], rem[1], ... rem[k-1], there exists an integer x solving the following system of simultaneous congruences. " }, { "code": null, "e": 2119, "s": 1429, "text": "The first part is clear that there exists an x. The second part basically states that all solutions (including the minimum one) produce the same remainder when divided by-product of n[0], num[1], .. num[k-1]. In the above example, the product is 3*4*5 = 60. And 11 is one solution, other solutions are 71, 131, .. etc. All these solutions produce the same remainder when divided by 60, i.e., they are of form 11 + m*60 where m >= 0.A Naive Approach to find x is to start with 1 and one by one increment it and check if dividing it with given elements in num[] produces corresponding remainders in rem[]. Once we find such an x, we return it. Below is the implementation of Naive Approach. " }, { "code": null, "e": 2123, "s": 2119, "text": "C++" }, { "code": null, "e": 2128, "s": 2123, "text": "Java" }, { "code": null, "e": 2136, "s": 2128, "text": "Python3" }, { "code": null, "e": 2139, "s": 2136, "text": "C#" }, { "code": null, "e": 2143, "s": 2139, "text": "PHP" }, { "code": null, "e": 2154, "s": 2143, "text": "Javascript" }, { "code": "// A C++ program to demonstrate working of Chinise remainder// Theorem#include<bits/stdc++.h>using namespace std; // k is size of num[] and rem[]. Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[] are pairwise coprime// (gcd for every pair is 1)int findMinX(int num[], int rem[], int k){ int x = 1; // Initialize result // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) int j; for (j=0; j<k; j++ ) if (x%num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } return x;} // Driver methodint main(void){ int num[] = {3, 4, 5}; int rem[] = {2, 3, 1}; int k = sizeof(num)/sizeof(num[0]); cout << \"x is \" << findMinX(num, rem, k); return 0;}", "e": 3229, "s": 2154, "text": null }, { "code": "// A Java program to demonstrate the working of Chinese remainder// Theoremimport java.io.*; class GFG { // k is size of num[] and rem[]. Returns the smallest // number x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise coprime // (gcd for every pair is 1) static int findMinX(int num[], int rem[], int k) { int x = 1; // Initialize result // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) int j; for (j=0; j<k; j++ ) if (x%num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } } // Driver method public static void main(String args[]) { int num[] = {3, 4, 5}; int rem[] = {2, 3, 1}; int k = num.length; System.out.println(\"x is \" + findMinX(num, rem, k)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 4516, "s": 3229, "text": null }, { "code": "# A Python3 program to demonstrate# working of Chinise remainder Theorem # k is size of num[] and rem[].# Returns the smallest number x# such that:# x % num[0] = rem[0],# x % num[1] = rem[1],# ..................# x % num[k-2] = rem[k-1]# Assumption: Numbers in num[]# are pairwise coprime (gcd for# every pair is 1)def findMinX(num, rem, k): x = 1; # Initialize result # As per the Chinise remainder # theorem, this loop will # always break. while(True): # Check if remainder of # x % num[j] is rem[j] # or not (for all j from # 0 to k-1) j = 0; while(j < k): if (x % num[j] != rem[j]): break; j += 1; # If all remainders # matched, we found x if (j == k): return x; # Else try next number x += 1; # Driver Codenum = [3, 4, 5];rem = [2, 3, 1];k = len(num);print(\"x is\", findMinX(num, rem, k)); # This code is contributed by mits", "e": 5497, "s": 4516, "text": null }, { "code": "// C# program to demonstrate working// of Chinise remainder Theoremusing System; class GFG{ // k is size of num[] and rem[]. // Returns the smallest // number x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] // are pairwise coprime // (gcd for every pair is 1) static int findMinX(int []num, int []rem, int k) { // Initialize result int x = 1; // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) int j; for (j = 0; j < k; j++ ) if (x % num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } } // Driver code public static void Main() { int []num = {3, 4, 5}; int []rem = {2, 3, 1}; int k = num.Length; Console.WriteLine(\"x is \" + findMinX(num, rem, k)); }} // This code is contributed by Sam007.", "e": 6830, "s": 5497, "text": null }, { "code": "<?php// A PHP program to demonstrate// working of Chinise remainder Theorem // k is size of num[] and rem[].// Returns the smallest number x// such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num[]// are pairwise coprime (gcd for// every pair is 1)function findMinX($num, $rem, $k){ $x = 1; // Initialize result // As per the Chinise remainder // theorem, this loop will // always break. while (true) { // Check if remainder of // x % num[j] is rem[j] // or not (for all j from // 0 to k-1) $j; for ($j = 0; $j < $k; $j++ ) if ($x % $num[$j] != $rem[$j]) break; // If all remainders // matched, we found x if ($j == $k) return $x; // Else try next number $x++; } return $x;} // Driver Code$num = array(3, 4, 5);$rem = array(2, 3, 1);$k = sizeof($num);echo \"x is \" , findMinX($num, $rem, $k); // This code is contributed by ajit?>", "e": 7882, "s": 6830, "text": null }, { "code": "<script> // A javascript program to demonstrate the working of Chinese remainder// Theorem // k is size of num and rem. Returns the smallest// number x such that:// x % num[0] = rem[0],// x % num[1] = rem[1],// ..................// x % num[k-2] = rem[k-1]// Assumption: Numbers in num are pairwise coprime// (gcd for every pair is 1)function findMinX(num , rem , k){ var x = 1; // Initialize result // As per the Chinese remainder theorem, // this loop will always break. while (true) { // Check if remainder of x % num[j] is // rem[j] or not (for all j from 0 to k-1) var j; for (j=0; j<k; j++ ) if (x%num[j] != rem[j]) break; // If all remainders matched, we found x if (j == k) return x; // Else try next number x++; } } // Driver methodvar num = [3, 4, 5];var rem = [2, 3, 1];var k = num.length;document.write(\"x is \" + findMinX(num, rem, k)); // This code is contributed by 29AjayKumar </script>", "e": 8909, "s": 7882, "text": null }, { "code": null, "e": 8919, "s": 8909, "text": "Output : " }, { "code": null, "e": 8927, "s": 8919, "text": "x is 11" }, { "code": null, "e": 9001, "s": 8927, "text": "Time Complexity : O(M), M is the product of all elements of num[] array." }, { "code": null, "e": 9024, "s": 9001, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 9313, "s": 9024, "text": "See below link for an efficient method to find x.Chinese Remainder Theorem | Set 2 (Inverse Modulo based Implementation)This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 9320, "s": 9313, "text": "Sam007" }, { "code": null, "e": 9326, "s": 9320, "text": "jit_t" }, { "code": null, "e": 9339, "s": 9326, "text": "Mithun Kumar" }, { "code": null, "e": 9354, "s": 9339, "text": "Adityasharma15" }, { "code": null, "e": 9363, "s": 9354, "text": "jyoti369" }, { "code": null, "e": 9375, "s": 9363, "text": "29AjayKumar" }, { "code": null, "e": 9389, "s": 9375, "text": "sumitgumber28" }, { "code": null, "e": 9402, "s": 9389, "text": "Mathematical" }, { "code": null, "e": 9415, "s": 9402, "text": "Mathematical" } ]
HTML | DOM createElement() Method
24 Jul, 2019 In HTML document, the document.createElement() is a method used to create the HTML element. The element specified using elementName is created or an unknown HTML element is created if the specified elementName is not recognized. Syntax var element = document.createElement("elementName"); In the above syntax, elementName is passed as a parameter. elementName specifies the type of the created element. The nodeName of the created element is initialized to the elementName value. The document.createElement() returns the newly created element. Example 1: This example illustrates how to create a <p> element. Input : <!DOCTYPE html><html> <head> <script> function createparagraph() { var x = document.createElement("p"); var t = document.createTextNode("Paragraph is created."); x.appendChild(t); document.body.appendChild(x); } </script></head> <body> <button onclick="createparagraph()">CreateParagraph</button></body> </html> Output:Initially: After pressing Create Paragraph button: Explanation: Start with creating a <p> element using document.createElement(). Create a text node using document.createTextNode(). Now, append the text to <p> using appendChild(). Append the <p> to <body> using appendChild(). Example 2: This example illustrates how to create a <p> element and append it to a <div> element.Input : <!DOCTYPE html><html> <head> <script> function createparagraph() { var x = document.createElement("p"); var t = document.createTextNode("Paragraph is created."); x.appendChild(t); document.getElementById("divid").appendChild(x); } </script></head> <body> <div id="divid"> A div element</div> <button onclick="createparagraph()">CreateParagraph</button></body> </html> Output: Initially: After pressing the CreateParagraph button:Supported Browser: The browsers supported by DOM createElement() Methodare listed below: Google Chrome Internet Explorer Firefox Opera SAfari HTML-DOM HTML-Methods Picked 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 Roadmap to Learn JavaScript For Beginners REST API (Introduction) Node.js fs.readFileSync() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jul, 2019" }, { "code": null, "e": 257, "s": 28, "text": "In HTML document, the document.createElement() is a method used to create the HTML element. The element specified using elementName is created or an unknown HTML element is created if the specified elementName is not recognized." }, { "code": null, "e": 264, "s": 257, "text": "Syntax" }, { "code": null, "e": 318, "s": 264, "text": "var element = document.createElement(\"elementName\");\n" }, { "code": null, "e": 573, "s": 318, "text": "In the above syntax, elementName is passed as a parameter. elementName specifies the type of the created element. The nodeName of the created element is initialized to the elementName value. The document.createElement() returns the newly created element." }, { "code": null, "e": 638, "s": 573, "text": "Example 1: This example illustrates how to create a <p> element." }, { "code": null, "e": 646, "s": 638, "text": "Input :" }, { "code": "<!DOCTYPE html><html> <head> <script> function createparagraph() { var x = document.createElement(\"p\"); var t = document.createTextNode(\"Paragraph is created.\"); x.appendChild(t); document.body.appendChild(x); } </script></head> <body> <button onclick=\"createparagraph()\">CreateParagraph</button></body> </html> ", "e": 1064, "s": 646, "text": null }, { "code": null, "e": 1082, "s": 1064, "text": "Output:Initially:" }, { "code": null, "e": 1122, "s": 1082, "text": "After pressing Create Paragraph button:" }, { "code": null, "e": 1135, "s": 1122, "text": "Explanation:" }, { "code": null, "e": 1201, "s": 1135, "text": "Start with creating a <p> element using document.createElement()." }, { "code": null, "e": 1253, "s": 1201, "text": "Create a text node using document.createTextNode()." }, { "code": null, "e": 1302, "s": 1253, "text": "Now, append the text to <p> using appendChild()." }, { "code": null, "e": 1348, "s": 1302, "text": "Append the <p> to <body> using appendChild()." }, { "code": null, "e": 1453, "s": 1348, "text": "Example 2: This example illustrates how to create a <p> element and append it to a <div> element.Input :" }, { "code": "<!DOCTYPE html><html> <head> <script> function createparagraph() { var x = document.createElement(\"p\"); var t = document.createTextNode(\"Paragraph is created.\"); x.appendChild(t); document.getElementById(\"divid\").appendChild(x); } </script></head> <body> <div id=\"divid\"> A div element</div> <button onclick=\"createparagraph()\">CreateParagraph</button></body> </html>", "e": 1910, "s": 1453, "text": null }, { "code": null, "e": 1918, "s": 1910, "text": "Output:" }, { "code": null, "e": 1929, "s": 1918, "text": "Initially:" }, { "code": null, "e": 2060, "s": 1929, "text": "After pressing the CreateParagraph button:Supported Browser: The browsers supported by DOM createElement() Methodare listed below:" }, { "code": null, "e": 2074, "s": 2060, "text": "Google Chrome" }, { "code": null, "e": 2092, "s": 2074, "text": "Internet Explorer" }, { "code": null, "e": 2100, "s": 2092, "text": "Firefox" }, { "code": null, "e": 2106, "s": 2100, "text": "Opera" }, { "code": null, "e": 2113, "s": 2106, "text": "SAfari" }, { "code": null, "e": 2122, "s": 2113, "text": "HTML-DOM" }, { "code": null, "e": 2135, "s": 2122, "text": "HTML-Methods" }, { "code": null, "e": 2142, "s": 2135, "text": "Picked" }, { "code": null, "e": 2159, "s": 2142, "text": "Web Technologies" }, { "code": null, "e": 2257, "s": 2159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2290, "s": 2257, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2352, "s": 2290, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2413, "s": 2352, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2463, "s": 2413, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2506, "s": 2463, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2578, "s": 2506, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2618, "s": 2578, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2660, "s": 2618, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2684, "s": 2660, "text": "REST API (Introduction)" } ]
Python | random.sample() function
29 Aug, 2018 sample() is an inbuilt function of random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random sampling without replacement. Syntax : random.sample(sequence, k) Parameters:sequence: Can be a list, tuple, string, or set.k: An Integer value, it specify the length of a sample. Returns: k length new list of elements chosen from the sequence. Code #1: Simple implementation of sample() function. # Python3 program to demonstrate# the use of sample() function . # import random from random import sample # Prints list of random items of given lengthlist1 = [1, 2, 3, 4, 5] print(sample(list1,3)) Output: [2, 3, 5] Code #2: Basic use of sample() function. # Python3 program to demonstrate# the use of sample() function . # import random import random # Prints list of random items of# length 3 from the given list.list1 = [1, 2, 3, 4, 5, 6] print("With list:", random.sample(list1, 3)) # Prints list of random items of# length 4 from the given string. string = "GeeksforGeeks"print("With string:", random.sample(string, 4)) # Prints list of random items of# length 4 from the given tuple.tuple1 = ("ankit", "geeks", "computer", "science", "portal", "scientist", "btech")print("With tuple:", random.sample(tuple1, 4)) # Prints list of random items of# length 3 from the given set.set1 = {"a", "b", "c", "d", "e"}print("With set:", random.sample(set1, 3)) Output: With list: [3, 1, 2] With string: ['e', 'f', 'G', 'G'] With tuple: ['ankit', 'portal', 'geeks', 'computer'] With set: ['b', 'd', 'c'] Note: Output will be different everytime as it returns a random item. Code #3: Raise Exception If the sample size i.e. k is larger than the sequence size, ValueError is raised. # Python3 program to demonstrate the# error of sample() function.import random list1 = [1, 2, 3, 4] # exception raisedprint(random.sample(list1, 5)) Output: Traceback (most recent call last): File "C:/Users/user/AppData/Local/Programs/Python/Python36/all_prgm/geeks_article/sample_method_article.py", line 8, in print(random.sample(list1, 5)) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\random.py", line 317, in sample raise ValueError("Sample larger than population or is negative") ValueError: Sample larger than population or is negative Python-Built-in-functions python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Aug, 2018" }, { "code": null, "e": 263, "s": 53, "text": "sample() is an inbuilt function of random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random sampling without replacement." }, { "code": null, "e": 299, "s": 263, "text": "Syntax : random.sample(sequence, k)" }, { "code": null, "e": 413, "s": 299, "text": "Parameters:sequence: Can be a list, tuple, string, or set.k: An Integer value, it specify the length of a sample." }, { "code": null, "e": 478, "s": 413, "text": "Returns: k length new list of elements chosen from the sequence." }, { "code": null, "e": 531, "s": 478, "text": "Code #1: Simple implementation of sample() function." }, { "code": "# Python3 program to demonstrate# the use of sample() function . # import random from random import sample # Prints list of random items of given lengthlist1 = [1, 2, 3, 4, 5] print(sample(list1,3))", "e": 734, "s": 531, "text": null }, { "code": null, "e": 742, "s": 734, "text": "Output:" }, { "code": null, "e": 752, "s": 742, "text": "[2, 3, 5]" }, { "code": null, "e": 794, "s": 752, "text": " Code #2: Basic use of sample() function." }, { "code": "# Python3 program to demonstrate# the use of sample() function . # import random import random # Prints list of random items of# length 3 from the given list.list1 = [1, 2, 3, 4, 5, 6] print(\"With list:\", random.sample(list1, 3)) # Prints list of random items of# length 4 from the given string. string = \"GeeksforGeeks\"print(\"With string:\", random.sample(string, 4)) # Prints list of random items of# length 4 from the given tuple.tuple1 = (\"ankit\", \"geeks\", \"computer\", \"science\", \"portal\", \"scientist\", \"btech\")print(\"With tuple:\", random.sample(tuple1, 4)) # Prints list of random items of# length 3 from the given set.set1 = {\"a\", \"b\", \"c\", \"d\", \"e\"}print(\"With set:\", random.sample(set1, 3))", "e": 1519, "s": 794, "text": null }, { "code": null, "e": 1527, "s": 1519, "text": "Output:" }, { "code": null, "e": 1661, "s": 1527, "text": "With list: [3, 1, 2]\nWith string: ['e', 'f', 'G', 'G']\nWith tuple: ['ankit', 'portal', 'geeks', 'computer']\nWith set: ['b', 'd', 'c']" }, { "code": null, "e": 1756, "s": 1661, "text": "Note: Output will be different everytime as it returns a random item. Code #3: Raise Exception" }, { "code": null, "e": 1838, "s": 1756, "text": "If the sample size i.e. k is larger than the sequence size, ValueError is raised." }, { "code": "# Python3 program to demonstrate the# error of sample() function.import random list1 = [1, 2, 3, 4] # exception raisedprint(random.sample(list1, 5)) ", "e": 1992, "s": 1838, "text": null }, { "code": null, "e": 2000, "s": 1992, "text": "Output:" }, { "code": null, "e": 2417, "s": 2000, "text": "Traceback (most recent call last):\n File \"C:/Users/user/AppData/Local/Programs/Python/Python36/all_prgm/geeks_article/sample_method_article.py\", line 8, in \n print(random.sample(list1, 5))\n File \"C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36\\lib\\random.py\", line 317, in sample\n raise ValueError(\"Sample larger than population or is negative\")\nValueError: Sample larger than population or is negative\n" }, { "code": null, "e": 2443, "s": 2417, "text": "Python-Built-in-functions" }, { "code": null, "e": 2458, "s": 2443, "text": "python-modules" }, { "code": null, "e": 2465, "s": 2458, "text": "Python" }, { "code": null, "e": 2563, "s": 2465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2591, "s": 2563, "text": "Read JSON file using Python" }, { "code": null, "e": 2613, "s": 2591, "text": "Python map() function" }, { "code": null, "e": 2663, "s": 2613, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2681, "s": 2663, "text": "Python Dictionary" }, { "code": null, "e": 2725, "s": 2681, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2767, "s": 2725, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2790, "s": 2767, "text": "Taking input in Python" }, { "code": null, "e": 2812, "s": 2790, "text": "Enumerate() in Python" }, { "code": null, "e": 2847, "s": 2812, "text": "Read a file line by line in Python" } ]
Reverse alternate K nodes in a Singly Linked List
03 Jul, 2022 Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6->9->8->7->NULL. Method 1 (Process 2k nodes and recursively call for rest of the list) This method is basically an extension of the method discussed in this post. kAltReverse(struct node *head, int k) 1) Reverse first k nodes. 2) In the modified list head points to the kth node. So change next of head to (k+1)th node 3) Move the current pointer to skip next k nodes. 4) Call the kAltReverse() recursively for rest of the n - 2k nodes. 5) Return new head of the list. C++ Java Python3 C# Javascript // C++ program to reverse alternate// k nodes in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node { public: int data; Node* next; }; /* Reverses alternate k nodes and returns the pointer to the new head node */Node *kAltReverse(Node *head, int k) { Node* current = head; Node* next; Node* prev = NULL; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != NULL && count < k) { next = current->next; current->next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if(head != NULL) head->next = current; /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while(count < k-1 && current != NULL ) { current = current->next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if(current != NULL) current->next = kAltReverse(current->next, k); /* 5) prev is new head of the input list */ return prev; } /* UTILITY FUNCTIONS *//* Function to push a node */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print linked list */void printList(Node *node) { int count = 0; while(node != NULL) { cout<<node->data<<" "; node = node->next; count++; } } /* Driver code*/int main(void) { /* Start with the empty list */ Node* head = NULL; int i; // create a list 1->2->3->4->5...... ->20 for(i = 20; i > 0; i--) push(&head, i); cout<<"Given linked list \n"; printList(head); head = kAltReverse(head, 3); cout<<"\n Modified Linked list \n"; printList(head); return(0); } // This code is contributed by rathbhupendra // Java program to reverse alternate k nodes in a linked list class LinkedList { static Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Reverses alternate k nodes and returns the pointer to the new head node */ Node kAltReverse(Node node, int k) { Node current = node; Node next = null, prev = null; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev; } void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } System.out.println("Given Linked List :"); list.printList(head); head = list.kAltReverse(head, 3); System.out.println(""); System.out.println("Modified Linked List :"); list.printList(head); }} // This code has been contributed by Mayank Jaiswal # Python3 program to reverse alternate# k nodes in a linked listimport math # Link list node class Node: def __init__(self, data): self.data = data self.next = None # Reverses alternate k nodes and #returns the pointer to the new head node def kAltReverse(head, k) : current = head next = None prev = None count = 0 #1) reverse first k nodes of the linked list while (current != None and count < k) : next = current.next current.next = prev prev = current current = next count = count + 1; # 2) Now head pos to the kth node. # So change next of head to (k+1)th node if(head != None): head.next = current # 3) We do not want to reverse next k # nodes. So move the current # pointer to skip next k nodes count = 0 while(count < k - 1 and current != None ): current = current.next count = count + 1 # 4) Recursively call for the list # starting from current.next. And make # rest of the list as next of first node if(current != None): current.next = kAltReverse(current.next, k) # 5) prev is new head of the input list return prev # UTILITY FUNCTIONS # Function to push a node def push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data # new_node.data = new_data # link the old list off the new node new_node.next = head_ref # move the head to po to the new node head_ref = new_node return head_ref # Function to print linked list def printList(node): count = 0 while(node != None): print(node.data, end = " ") node = node.next count = count + 1 # Driver codeif __name__=='__main__': # Start with the empty list head = None # create a list 1.2.3.4.5...... .20 for i in range(20, 0, -1): head = push(head, i) print("Given linked list ") printList(head) head = kAltReverse(head, 3) print("\nModified Linked list") printList(head) # This code is contributed by Srathore // C# program to reverse alternate// k nodes in a linked list using System;class LinkedList { static Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Reverses alternate k nodes and returns the pointer to the new head node */ Node kAltReverse(Node node, int k) { Node current = node; Node next = null, prev = null; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev; } void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } // Driver code public static void Main(String []args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } Console.WriteLine("Given Linked List :"); list.printList(head); head = list.kAltReverse(head, 3); Console.WriteLine(""); Console.WriteLine("Modified Linked List :"); list.printList(head); } } // This code has been contributed by Arnab Kundu <script> // JavaScript program to reverse // alternate k nodes in a linked listclass Node { constructor(d) { this.data = d; this.next = null; }} let head; // Reverses alternate k nodes and returns// the pointer to the new head node function kAltReverse(node, k){ let current = node; let next = null, prev = null; let count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev;} function printList(node){ while (node != null) { document.write(node.data + " "); node = node.next; }} function push(newdata){ let mynode = new Node(newdata); mynode.next = head; head = mynode;} // Driver code // Creating the linkedlistfor(let i = 20; i > 0; i--){ push(i);}document.write("Given Linked List :<br>");printList(head);head = kAltReverse(head, 3); document.write("<br>");document.write("Modified Linked List :<br>");printList(head); // This code is contributed by rag2127 </script> Output: Given linked list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Modified Linked list 3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19 Time Complexity: O(n) Space Complexity: O(n) Method 2 (Process k nodes and recursively call for rest of the list) The method 1 reverses the first k node and then moves the pointer to k nodes ahead. So method 1 uses two while loops and processes 2k nodes in one recursive call. This method processes only k nodes in a recursive call. It uses a third bool parameter b which decides whether to reverse the k elements or simply move the pointer. _kAltReverse(struct node *head, int k, bool b) 1) If b is true, then reverse first k nodes. 2) If b is false, then move the pointer k nodes ahead. 3) Call the kAltReverse() recursively for rest of the n - k nodes and link rest of the modified list with end of first k nodes. 4) Return new head of the list. C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; /* Link list node */class node { public: int data; node* next; }; /* Helper function for kAltReverse() */node * _kAltReverse(node *node, int k, bool b); /* Alternatively reverses the given linked list in groups of given size k. */node *kAltReverse(node *head, int k) { return _kAltReverse(head, k, true); } /* Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as true, otherwise moves the pointer k nodes aheadand recursively calls itself */node * _kAltReverse(node *Node, int k, bool b) { if(Node == NULL) return NULL; int count = 1; node *prev = NULL; node *current = Node; node *next; /* The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) If b is false, then it moves the current pointer */ while(current != NULL && count <= k) { next = current->next; /* Reverse the nodes only if b is true*/ if(b == true) current->next = prev; prev = current; current = next; count++; } /* 3) If b is true, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head */ if(b == true) { Node->next = _kAltReverse(current, k, !b); return prev; } /* If b is not true, then attach rest of the list after prev. So attach rest of the list after prev */ else { prev->next = _kAltReverse(current, k, !b); return Node; } } /* UTILITY FUNCTIONS *//* Function to push a node */void push(node** head_ref, int new_data) { /* allocate node */ node* new_node = new node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print linked list */void printList(node *node) { int count = 0; while(node != NULL) { cout << node->data << " "; node = node->next; count++; } } // Driver Codeint main(void) { /* Start with the empty list */ node* head = NULL; int i; // create a list 1->2->3->4->5...... ->20 for(i = 20; i > 0; i--) push(&head, i); cout << "Given linked list \n"; printList(head); head = kAltReverse(head, 3); cout << "\nModified Linked list \n"; printList(head); return(0); } // This code is contributed by rathbhupendra #include<stdio.h>#include<stdlib.h> /* Link list node */struct node{ int data; struct node* next;}; /* Helper function for kAltReverse() */struct node * _kAltReverse(struct node *node, int k, bool b); /* Alternatively reverses the given linked list in groups of given size k. */struct node *kAltReverse(struct node *head, int k){ return _kAltReverse(head, k, true);} /* Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as true, otherwise moves the pointer k nodes ahead and recursively calls itself */ struct node * _kAltReverse(struct node *node, int k, bool b){ if(node == NULL) return NULL; int count = 1; struct node *prev = NULL; struct node *current = node; struct node *next; /* The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) If b is false, then it moves the current pointer */ while(current != NULL && count <= k) { next = current->next; /* Reverse the nodes only if b is true*/ if(b == true) current->next = prev; prev = current; current = next; count++; } /* 3) If b is true, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head */ if(b == true) { node->next = _kAltReverse(current,k,!b); return prev; } /* If b is not true, then attach rest of the list after prev. So attach rest of the list after prev */ else { prev->next = _kAltReverse(current, k, !b); return node; }} /* UTILITY FUNCTIONS *//* Function to push a node */void push(struct node** head_ref, int new_data){ /* allocate node */ struct node* new_node = (struct node*) malloc(sizeof(struct node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct node *node){ int count = 0; while(node != NULL) { printf("%d ", node->data); node = node->next; count++; }} /* Driver program to test above function*/int main(void){ /* Start with the empty list */ struct node* head = NULL; int i; // create a list 1->2->3->4->5...... ->20 for(i = 20; i > 0; i--) push(&head, i); printf("\n Given linked list \n"); printList(head); head = kAltReverse(head, 3); printf("\n Modified Linked list \n"); printList(head); getchar(); return(0);} // Java program to reverse alternate k nodes in a linked list class LinkedList { static Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Alternatively reverses the given linked list in groups of given size k. */ Node kAltReverse(Node head, int k) { return _kAltReverse(head, k, true); } /* Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as true, otherwise moves the pointer k nodes ahead and recursively calls itself */ Node _kAltReverse(Node node, int k, boolean b) { if (node == null) { return null; } int count = 1; Node prev = null; Node current = node; Node next = null; /* The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) If b is false, then it moves the current pointer */ while (current != null && count <= k) { next = current.next; /* Reverse the nodes only if b is true*/ if (b == true) { current.next = prev; } prev = current; current = next; count++; } /* 3) If b is true, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head */ if (b == true) { node.next = _kAltReverse(current, k, !b); return prev; } /* If b is not true, then attach rest of the list after prev. So attach rest of the list after prev */ else { prev.next = _kAltReverse(current, k, !b); return node; } } void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } System.out.println("Given Linked List :"); list.printList(head); head = list.kAltReverse(head, 3); System.out.println(""); System.out.println("Modified Linked List :"); list.printList(head); }} // This code has been contributed by Mayank Jaiswal # Python code for above algorithm # Link list node class node: def __init__(self, data): self.data = data self.next = next # function to insert a node at the# beginning of the linked listdef push(head_ref, new_data): # allocate node new_node = node(0) # put in the data new_node.data = new_data # link the old list to the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref """ Alternatively reverses the given linked list in groups of given size k. """def kAltReverse(head, k) : return _kAltReverse(head, k, True) """ Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as True, otherwise moves the pointer k nodes aheadand recursively calls itself """def _kAltReverse(Node, k, b) : if(Node == None) : return None count = 1 prev = None current = Node next = None """ The loop serves two purposes 1) If b is True, then it reverses the k nodes 2) If b is false, then it moves the current pointer """ while(current != None and count <= k) : next = current.next """ Reverse the nodes only if b is True""" if(b == True) : current.next = prev prev = current current = next count = count + 1 """ 3) If b is True, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head """ if(b == True) : Node.next = _kAltReverse(current, k, not b) return prev else : """ If b is not True, then attach rest of the list after prev. So attach rest of the list after prev """ prev.next = _kAltReverse(current, k, not b) return Node """ Function to print linked list """def printList(node) : count = 0 while(node != None) : print( node.data, end = " ") node = node.next count = count + 1 # Driver Code """ Start with the empty list """head = Nonei = 20 # create a list 1->2->3->4->5...... ->20 while(i > 0 ): head = push(head, i) i = i - 1 print( "Given linked list ") printList(head) head = kAltReverse(head, 3) print( "\nModified Linked list ") printList(head) # This code is contributed by Arnab Kundu // C# Program for converting // singly linked list into // circular linked list. using System; public class LinkedList{ static Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Reverses alternate k nodes and returns the pointer to the new head node */ Node kAltReverse(Node node, int k) { Node current = node; Node next = null, prev = null; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev; } void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } public static void Main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } Console.WriteLine("Given Linked List :"); list.printList(head); head = list.kAltReverse(head, 3); Console.WriteLine(""); Console.WriteLine("Modified Linked List :"); list.printList(head); } } // This code is contributed 29AjayKumar <script>// javascript program to reverse alternate k nodes in a linked listvar head; class Node { constructor(val) { this.data = val; this.next = null; } } /* * Alternatively reverses the given linked list in groups of given size k. */ function kAltReverse(head , k) { return _kAltReverse(head, k, true); } /* * Helper function for kAltReverse(). It reverses k nodes of the list only if * the third parameter b is passed as true, otherwise moves the pointer k nodes * ahead and recursively calls itself */ function _kAltReverse(node , k, b) { if (node == null) { return null; } var count = 1;var prev = null;var current = node;var next = null; /* * The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) * If b is false, then it moves the current pointer */ while (current != null && count <= k) { next = current.next; /* Reverse the nodes only if b is true */ if (b == true) { current.next = prev; } prev = current; current = next; count++; } /* * 3) If b is true, then node is the kth node. So attach rest of the list after * node. 4) After attaching, return the new head */ if (b == true) { node.next = _kAltReverse(current, k, !b); return prev; } /* * If b is not true, then attach rest of the list after prev. So attach rest of * the list after prev */ else { prev.next = _kAltReverse(current, k, !b); return node; } } function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } function push(newdata) {var mynode = new Node(newdata); mynode.next = head; head = mynode; } // Creating the linkedlist for (i = 20; i > 0; i--) { push(i); } document.write("Given Linked List :<br/>"); printList(head); head = kAltReverse(head, 3); document.write("<br/>"); document.write("Modified Linked List :<br/>"); printList(head); // This code contributed by aashish1995</script> Output: Given linked list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Modified Linked list 3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19 Time Complexity: O(n) Space Complexity: O(n) Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem. 29AjayKumar andrew1234 rathbhupendra sapnasingh4991 Akanksha_Rai nidhi_biet aashish1995 rag2127 simmytarika5 ashutoshsinghgeeksforgeeks germanshephered48 surinderdawra388 hardikkoriintern Reverse Linked List Linked List Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) LinkedList in Java Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Add two numbers represented by linked lists | Set 1 Implementing a Linked List in Java using Class Detect and Remove Loop in a Linked List Function to check if a singly linked list is palindrome Queue - Linked List Implementation Implement a stack using singly linked list
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jul, 2022" }, { "code": null, "e": 225, "s": 54, "text": "Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm." }, { "code": null, "e": 235, "s": 225, "text": "Example: " }, { "code": null, "e": 331, "s": 235, "text": "Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3\nOutput: 3->2->1->4->5->6->9->8->7->NULL. " }, { "code": null, "e": 402, "s": 331, "text": "Method 1 (Process 2k nodes and recursively call for rest of the list) " }, { "code": null, "e": 479, "s": 402, "text": "This method is basically an extension of the method discussed in this post. " }, { "code": null, "e": 809, "s": 479, "text": "kAltReverse(struct node *head, int k)\n 1) Reverse first k nodes.\n 2) In the modified list head points to the kth node. So change next \n of head to (k+1)th node\n 3) Move the current pointer to skip next k nodes.\n 4) Call the kAltReverse() recursively for rest of the n - 2k nodes.\n 5) Return new head of the list." }, { "code": null, "e": 813, "s": 809, "text": "C++" }, { "code": null, "e": 818, "s": 813, "text": "Java" }, { "code": null, "e": 826, "s": 818, "text": "Python3" }, { "code": null, "e": 829, "s": 826, "text": "C#" }, { "code": null, "e": 840, "s": 829, "text": "Javascript" }, { "code": "// C++ program to reverse alternate// k nodes in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node { public: int data; Node* next; }; /* Reverses alternate k nodes and returns the pointer to the new head node */Node *kAltReverse(Node *head, int k) { Node* current = head; Node* next; Node* prev = NULL; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != NULL && count < k) { next = current->next; current->next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if(head != NULL) head->next = current; /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while(count < k-1 && current != NULL ) { current = current->next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if(current != NULL) current->next = kAltReverse(current->next, k); /* 5) prev is new head of the input list */ return prev; } /* UTILITY FUNCTIONS *//* Function to push a node */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print linked list */void printList(Node *node) { int count = 0; while(node != NULL) { cout<<node->data<<\" \"; node = node->next; count++; } } /* Driver code*/int main(void) { /* Start with the empty list */ Node* head = NULL; int i; // create a list 1->2->3->4->5...... ->20 for(i = 20; i > 0; i--) push(&head, i); cout<<\"Given linked list \\n\"; printList(head); head = kAltReverse(head, 3); cout<<\"\\n Modified Linked list \\n\"; printList(head); return(0); } // This code is contributed by rathbhupendra", "e": 3076, "s": 840, "text": null }, { "code": "// Java program to reverse alternate k nodes in a linked list class LinkedList { static Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Reverses alternate k nodes and returns the pointer to the new head node */ Node kAltReverse(Node node, int k) { Node current = node; Node next = null, prev = null; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev; } void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } System.out.println(\"Given Linked List :\"); list.printList(head); head = list.kAltReverse(head, 3); System.out.println(\"\"); System.out.println(\"Modified Linked List :\"); list.printList(head); }} // This code has been contributed by Mayank Jaiswal", "e": 5272, "s": 3076, "text": null }, { "code": "# Python3 program to reverse alternate# k nodes in a linked listimport math # Link list node class Node: def __init__(self, data): self.data = data self.next = None # Reverses alternate k nodes and #returns the pointer to the new head node def kAltReverse(head, k) : current = head next = None prev = None count = 0 #1) reverse first k nodes of the linked list while (current != None and count < k) : next = current.next current.next = prev prev = current current = next count = count + 1; # 2) Now head pos to the kth node. # So change next of head to (k+1)th node if(head != None): head.next = current # 3) We do not want to reverse next k # nodes. So move the current # pointer to skip next k nodes count = 0 while(count < k - 1 and current != None ): current = current.next count = count + 1 # 4) Recursively call for the list # starting from current.next. And make # rest of the list as next of first node if(current != None): current.next = kAltReverse(current.next, k) # 5) prev is new head of the input list return prev # UTILITY FUNCTIONS # Function to push a node def push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data # new_node.data = new_data # link the old list off the new node new_node.next = head_ref # move the head to po to the new node head_ref = new_node return head_ref # Function to print linked list def printList(node): count = 0 while(node != None): print(node.data, end = \" \") node = node.next count = count + 1 # Driver codeif __name__=='__main__': # Start with the empty list head = None # create a list 1.2.3.4.5...... .20 for i in range(20, 0, -1): head = push(head, i) print(\"Given linked list \") printList(head) head = kAltReverse(head, 3) print(\"\\nModified Linked list\") printList(head) # This code is contributed by Srathore", "e": 7405, "s": 5272, "text": null }, { "code": "// C# program to reverse alternate// k nodes in a linked list using System;class LinkedList { static Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Reverses alternate k nodes and returns the pointer to the new head node */ Node kAltReverse(Node node, int k) { Node current = node; Node next = null, prev = null; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev; } void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } // Driver code public static void Main(String []args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } Console.WriteLine(\"Given Linked List :\"); list.printList(head); head = list.kAltReverse(head, 3); Console.WriteLine(\"\"); Console.WriteLine(\"Modified Linked List :\"); list.printList(head); } } // This code has been contributed by Arnab Kundu", "e": 9807, "s": 7405, "text": null }, { "code": "<script> // JavaScript program to reverse // alternate k nodes in a linked listclass Node { constructor(d) { this.data = d; this.next = null; }} let head; // Reverses alternate k nodes and returns// the pointer to the new head node function kAltReverse(node, k){ let current = node; let next = null, prev = null; let count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev;} function printList(node){ while (node != null) { document.write(node.data + \" \"); node = node.next; }} function push(newdata){ let mynode = new Node(newdata); mynode.next = head; head = mynode;} // Driver code // Creating the linkedlistfor(let i = 20; i > 0; i--){ push(i);}document.write(\"Given Linked List :<br>\");printList(head);head = kAltReverse(head, 3); document.write(\"<br>\");document.write(\"Modified Linked List :<br>\");printList(head); // This code is contributed by rag2127 </script>", "e": 11615, "s": 9807, "text": null }, { "code": null, "e": 11624, "s": 11615, "text": "Output: " }, { "code": null, "e": 11765, "s": 11624, "text": "Given linked list\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\nModified Linked list\n3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19" }, { "code": null, "e": 11787, "s": 11765, "text": "Time Complexity: O(n)" }, { "code": null, "e": 11810, "s": 11787, "text": "Space Complexity: O(n)" }, { "code": null, "e": 11880, "s": 11810, "text": "Method 2 (Process k nodes and recursively call for rest of the list) " }, { "code": null, "e": 12044, "s": 11880, "text": "The method 1 reverses the first k node and then moves the pointer to k nodes ahead. So method 1 uses two while loops and processes 2k nodes in one recursive call. " }, { "code": null, "e": 12211, "s": 12044, "text": "This method processes only k nodes in a recursive call. It uses a third bool parameter b which decides whether to reverse the k elements or simply move the pointer. " }, { "code": null, "e": 12539, "s": 12211, "text": "_kAltReverse(struct node *head, int k, bool b)\n 1) If b is true, then reverse first k nodes.\n 2) If b is false, then move the pointer k nodes ahead.\n 3) Call the kAltReverse() recursively for rest of the n - k nodes and link \n rest of the modified list with end of first k nodes. \n 4) Return new head of the list." }, { "code": null, "e": 12543, "s": 12539, "text": "C++" }, { "code": null, "e": 12545, "s": 12543, "text": "C" }, { "code": null, "e": 12550, "s": 12545, "text": "Java" }, { "code": null, "e": 12558, "s": 12550, "text": "Python3" }, { "code": null, "e": 12561, "s": 12558, "text": "C#" }, { "code": null, "e": 12572, "s": 12561, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; /* Link list node */class node { public: int data; node* next; }; /* Helper function for kAltReverse() */node * _kAltReverse(node *node, int k, bool b); /* Alternatively reverses the given linked list in groups of given size k. */node *kAltReverse(node *head, int k) { return _kAltReverse(head, k, true); } /* Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as true, otherwise moves the pointer k nodes aheadand recursively calls itself */node * _kAltReverse(node *Node, int k, bool b) { if(Node == NULL) return NULL; int count = 1; node *prev = NULL; node *current = Node; node *next; /* The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) If b is false, then it moves the current pointer */ while(current != NULL && count <= k) { next = current->next; /* Reverse the nodes only if b is true*/ if(b == true) current->next = prev; prev = current; current = next; count++; } /* 3) If b is true, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head */ if(b == true) { Node->next = _kAltReverse(current, k, !b); return prev; } /* If b is not true, then attach rest of the list after prev. So attach rest of the list after prev */ else { prev->next = _kAltReverse(current, k, !b); return Node; } } /* UTILITY FUNCTIONS *//* Function to push a node */void push(node** head_ref, int new_data) { /* allocate node */ node* new_node = new node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print linked list */void printList(node *node) { int count = 0; while(node != NULL) { cout << node->data << \" \"; node = node->next; count++; } } // Driver Codeint main(void) { /* Start with the empty list */ node* head = NULL; int i; // create a list 1->2->3->4->5...... ->20 for(i = 20; i > 0; i--) push(&head, i); cout << \"Given linked list \\n\"; printList(head); head = kAltReverse(head, 3); cout << \"\\nModified Linked list \\n\"; printList(head); return(0); } // This code is contributed by rathbhupendra", "e": 15257, "s": 12572, "text": null }, { "code": "#include<stdio.h>#include<stdlib.h> /* Link list node */struct node{ int data; struct node* next;}; /* Helper function for kAltReverse() */struct node * _kAltReverse(struct node *node, int k, bool b); /* Alternatively reverses the given linked list in groups of given size k. */struct node *kAltReverse(struct node *head, int k){ return _kAltReverse(head, k, true);} /* Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as true, otherwise moves the pointer k nodes ahead and recursively calls itself */ struct node * _kAltReverse(struct node *node, int k, bool b){ if(node == NULL) return NULL; int count = 1; struct node *prev = NULL; struct node *current = node; struct node *next; /* The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) If b is false, then it moves the current pointer */ while(current != NULL && count <= k) { next = current->next; /* Reverse the nodes only if b is true*/ if(b == true) current->next = prev; prev = current; current = next; count++; } /* 3) If b is true, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head */ if(b == true) { node->next = _kAltReverse(current,k,!b); return prev; } /* If b is not true, then attach rest of the list after prev. So attach rest of the list after prev */ else { prev->next = _kAltReverse(current, k, !b); return node; }} /* UTILITY FUNCTIONS *//* Function to push a node */void push(struct node** head_ref, int new_data){ /* allocate node */ struct node* new_node = (struct node*) malloc(sizeof(struct node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct node *node){ int count = 0; while(node != NULL) { printf(\"%d \", node->data); node = node->next; count++; }} /* Driver program to test above function*/int main(void){ /* Start with the empty list */ struct node* head = NULL; int i; // create a list 1->2->3->4->5...... ->20 for(i = 20; i > 0; i--) push(&head, i); printf(\"\\n Given linked list \\n\"); printList(head); head = kAltReverse(head, 3); printf(\"\\n Modified Linked list \\n\"); printList(head); getchar(); return(0);}", "e": 17951, "s": 15257, "text": null }, { "code": "// Java program to reverse alternate k nodes in a linked list class LinkedList { static Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Alternatively reverses the given linked list in groups of given size k. */ Node kAltReverse(Node head, int k) { return _kAltReverse(head, k, true); } /* Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as true, otherwise moves the pointer k nodes ahead and recursively calls itself */ Node _kAltReverse(Node node, int k, boolean b) { if (node == null) { return null; } int count = 1; Node prev = null; Node current = node; Node next = null; /* The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) If b is false, then it moves the current pointer */ while (current != null && count <= k) { next = current.next; /* Reverse the nodes only if b is true*/ if (b == true) { current.next = prev; } prev = current; current = next; count++; } /* 3) If b is true, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head */ if (b == true) { node.next = _kAltReverse(current, k, !b); return prev; } /* If b is not true, then attach rest of the list after prev. So attach rest of the list after prev */ else { prev.next = _kAltReverse(current, k, !b); return node; } } void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } System.out.println(\"Given Linked List :\"); list.printList(head); head = list.kAltReverse(head, 3); System.out.println(\"\"); System.out.println(\"Modified Linked List :\"); list.printList(head); }} // This code has been contributed by Mayank Jaiswal", "e": 20490, "s": 17951, "text": null }, { "code": "# Python code for above algorithm # Link list node class node: def __init__(self, data): self.data = data self.next = next # function to insert a node at the# beginning of the linked listdef push(head_ref, new_data): # allocate node new_node = node(0) # put in the data new_node.data = new_data # link the old list to the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref \"\"\" Alternatively reverses the given linked list in groups of given size k. \"\"\"def kAltReverse(head, k) : return _kAltReverse(head, k, True) \"\"\" Helper function for kAltReverse(). It reverses k nodes of the list only if the third parameter b is passed as True, otherwise moves the pointer k nodes aheadand recursively calls itself \"\"\"def _kAltReverse(Node, k, b) : if(Node == None) : return None count = 1 prev = None current = Node next = None \"\"\" The loop serves two purposes 1) If b is True, then it reverses the k nodes 2) If b is false, then it moves the current pointer \"\"\" while(current != None and count <= k) : next = current.next \"\"\" Reverse the nodes only if b is True\"\"\" if(b == True) : current.next = prev prev = current current = next count = count + 1 \"\"\" 3) If b is True, then node is the kth node. So attach rest of the list after node. 4) After attaching, return the new head \"\"\" if(b == True) : Node.next = _kAltReverse(current, k, not b) return prev else : \"\"\" If b is not True, then attach rest of the list after prev. So attach rest of the list after prev \"\"\" prev.next = _kAltReverse(current, k, not b) return Node \"\"\" Function to print linked list \"\"\"def printList(node) : count = 0 while(node != None) : print( node.data, end = \" \") node = node.next count = count + 1 # Driver Code \"\"\" Start with the empty list \"\"\"head = Nonei = 20 # create a list 1->2->3->4->5...... ->20 while(i > 0 ): head = push(head, i) i = i - 1 print( \"Given linked list \") printList(head) head = kAltReverse(head, 3) print( \"\\nModified Linked list \") printList(head) # This code is contributed by Arnab Kundu", "e": 22967, "s": 20490, "text": null }, { "code": "// C# Program for converting // singly linked list into // circular linked list. using System; public class LinkedList{ static Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Reverses alternate k nodes and returns the pointer to the new head node */ Node kAltReverse(Node node, int k) { Node current = node; Node next = null, prev = null; int count = 0; /*1) reverse first k nodes of the linked list */ while (current != null && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } /* 2) Now head points to the kth node. So change next of head to (k+1)th node*/ if (node != null) { node.next = current; } /* 3) We do not want to reverse next k nodes. So move the current pointer to skip next k nodes */ count = 0; while (count < k - 1 && current != null) { current = current.next; count++; } /* 4) Recursively call for the list starting from current->next. And make rest of the list as next of first node */ if (current != null) { current.next = kAltReverse(current.next, k); } /* 5) prev is new head of the input list */ return prev; } void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } void push(int newdata) { Node mynode = new Node(newdata); mynode.next = head; head = mynode; } public static void Main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist for (int i = 20; i > 0; i--) { list.push(i); } Console.WriteLine(\"Given Linked List :\"); list.printList(head); head = list.kAltReverse(head, 3); Console.WriteLine(\"\"); Console.WriteLine(\"Modified Linked List :\"); list.printList(head); } } // This code is contributed 29AjayKumar", "e": 25354, "s": 22967, "text": null }, { "code": "<script>// javascript program to reverse alternate k nodes in a linked listvar head; class Node { constructor(val) { this.data = val; this.next = null; } } /* * Alternatively reverses the given linked list in groups of given size k. */ function kAltReverse(head , k) { return _kAltReverse(head, k, true); } /* * Helper function for kAltReverse(). It reverses k nodes of the list only if * the third parameter b is passed as true, otherwise moves the pointer k nodes * ahead and recursively calls itself */ function _kAltReverse(node , k, b) { if (node == null) { return null; } var count = 1;var prev = null;var current = node;var next = null; /* * The loop serves two purposes 1) If b is true, then it reverses the k nodes 2) * If b is false, then it moves the current pointer */ while (current != null && count <= k) { next = current.next; /* Reverse the nodes only if b is true */ if (b == true) { current.next = prev; } prev = current; current = next; count++; } /* * 3) If b is true, then node is the kth node. So attach rest of the list after * node. 4) After attaching, return the new head */ if (b == true) { node.next = _kAltReverse(current, k, !b); return prev; } /* * If b is not true, then attach rest of the list after prev. So attach rest of * the list after prev */ else { prev.next = _kAltReverse(current, k, !b); return node; } } function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } function push(newdata) {var mynode = new Node(newdata); mynode.next = head; head = mynode; } // Creating the linkedlist for (i = 20; i > 0; i--) { push(i); } document.write(\"Given Linked List :<br/>\"); printList(head); head = kAltReverse(head, 3); document.write(\"<br/>\"); document.write(\"Modified Linked List :<br/>\"); printList(head); // This code contributed by aashish1995</script>", "e": 27788, "s": 25354, "text": null }, { "code": null, "e": 27797, "s": 27788, "text": "Output: " }, { "code": null, "e": 27938, "s": 27797, "text": "Given linked list\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\nModified Linked list\n3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19" }, { "code": null, "e": 27961, "s": 27938, "text": "Time Complexity: O(n) " }, { "code": null, "e": 27984, "s": 27961, "text": "Space Complexity: O(n)" }, { "code": null, "e": 28100, "s": 27984, "text": "Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem." }, { "code": null, "e": 28112, "s": 28100, "text": "29AjayKumar" }, { "code": null, "e": 28123, "s": 28112, "text": "andrew1234" }, { "code": null, "e": 28137, "s": 28123, "text": "rathbhupendra" }, { "code": null, "e": 28152, "s": 28137, "text": "sapnasingh4991" }, { "code": null, "e": 28165, "s": 28152, "text": "Akanksha_Rai" }, { "code": null, "e": 28176, "s": 28165, "text": "nidhi_biet" }, { "code": null, "e": 28188, "s": 28176, "text": "aashish1995" }, { "code": null, "e": 28196, "s": 28188, "text": "rag2127" }, { "code": null, "e": 28209, "s": 28196, "text": "simmytarika5" }, { "code": null, "e": 28236, "s": 28209, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 28254, "s": 28236, "text": "germanshephered48" }, { "code": null, "e": 28271, "s": 28254, "text": "surinderdawra388" }, { "code": null, "e": 28288, "s": 28271, "text": "hardikkoriintern" }, { "code": null, "e": 28296, "s": 28288, "text": "Reverse" }, { "code": null, "e": 28308, "s": 28296, "text": "Linked List" }, { "code": null, "e": 28320, "s": 28308, "text": "Linked List" }, { "code": null, "e": 28328, "s": 28320, "text": "Reverse" }, { "code": null, "e": 28426, "s": 28328, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28474, "s": 28426, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 28493, "s": 28474, "text": "LinkedList in Java" }, { "code": null, "e": 28525, "s": 28493, "text": "Introduction to Data Structures" }, { "code": null, "e": 28589, "s": 28525, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 28641, "s": 28589, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 28688, "s": 28641, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 28728, "s": 28688, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 28784, "s": 28728, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 28819, "s": 28784, "text": "Queue - Linked List Implementation" } ]
ER diagram of Bank Management System
20 Sep, 2021 ER diagram is known as Entity-Relationship diagram. It is used to analyze to structure of the Database. It shows relationships between entities and their attributes. An ER model provides a means of communication. ER diagram of Bank has the following description : Bank have Customer. Banks are identified by a name, code, address of main office. Banks have branches. Branches are identified by a branch_no., branch_name, address. Customers are identified by name, cust-id, phone number, address. Customer can have one or more accounts. Accounts are identified by account_no., acc_type, balance. Customer can avail loans. Loans are identified by loan_id, loan_type and amount. Account and loans are related to bank’s branch. ER Diagram of Bank Management System : This bank ER diagram illustrates key information about bank, including entities such as branches, customers, accounts, and loans. It allows us to understand the relationships between entities. Entities and their Attributes are : Bank Entity : Attributes of Bank Entity are Bank Name, Code and Address. Code is Primary Key for Bank Entity. Customer Entity : Attributes of Customer Entity are Customer_id, Name, Phone Number and Address. Customer_id is Primary Key for Customer Entity. Branch Entity : Attributes of Branch Entity are Branch_id, Name and Address. Branch_id is Primary Key for Branch Entity. Account Entity : Attributes of Account Entity are Account_number, Account_Type and Balance. Account_number is Primary Key for Account Entity. Loan Entity : Attributes of Loan Entity are Loan_id, Loan_Type and Amount. Loan_id is Primary Key for Loan Entity. Relationships are : Bank has Branches => 1 : N One Bank can have many Branches but one Branch can not belong to many Banks, so the relationship between Bank and Branch is one to many relationship. Branch maintain Accounts => 1 : N One Branch can have many Accounts but one Account can not belong to many Branches, so the relationship between Branch and Account is one to many relationship. Branch offer Loans => 1 : N One Branch can have many Loans but one Loan can not belong to many Branches, so the relationship between Branch and Loan is one to many relationship. Account held by Customers => M : N One Customer can have more than one Accounts and also One Account can be held by one or more Customers, so the relationship between Account and Customers is many to many relationship. Loan availed by Customer => M : N (Assume loan can be jointly held by many Customers). One Customer can have more than one Loans and also One Loan can be availed by one or more Customers, so the relationship between Loan and Customers is many to many relationship. pradiptamukherjee DBMS-ER model DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Sep, 2021" }, { "code": null, "e": 266, "s": 52, "text": "ER diagram is known as Entity-Relationship diagram. It is used to analyze to structure of the Database. It shows relationships between entities and their attributes. An ER model provides a means of communication. " }, { "code": null, "e": 319, "s": 266, "text": "ER diagram of Bank has the following description : " }, { "code": null, "e": 339, "s": 319, "text": "Bank have Customer." }, { "code": null, "e": 401, "s": 339, "text": "Banks are identified by a name, code, address of main office." }, { "code": null, "e": 422, "s": 401, "text": "Banks have branches." }, { "code": null, "e": 485, "s": 422, "text": "Branches are identified by a branch_no., branch_name, address." }, { "code": null, "e": 551, "s": 485, "text": "Customers are identified by name, cust-id, phone number, address." }, { "code": null, "e": 591, "s": 551, "text": "Customer can have one or more accounts." }, { "code": null, "e": 650, "s": 591, "text": "Accounts are identified by account_no., acc_type, balance." }, { "code": null, "e": 676, "s": 650, "text": "Customer can avail loans." }, { "code": null, "e": 731, "s": 676, "text": "Loans are identified by loan_id, loan_type and amount." }, { "code": null, "e": 779, "s": 731, "text": "Account and loans are related to bank’s branch." }, { "code": null, "e": 819, "s": 779, "text": "ER Diagram of Bank Management System : " }, { "code": null, "e": 1015, "s": 821, "text": "This bank ER diagram illustrates key information about bank, including entities such as branches, customers, accounts, and loans. It allows us to understand the relationships between entities. " }, { "code": null, "e": 1053, "s": 1015, "text": "Entities and their Attributes are : " }, { "code": null, "e": 1163, "s": 1053, "text": "Bank Entity : Attributes of Bank Entity are Bank Name, Code and Address. Code is Primary Key for Bank Entity." }, { "code": null, "e": 1308, "s": 1163, "text": "Customer Entity : Attributes of Customer Entity are Customer_id, Name, Phone Number and Address. Customer_id is Primary Key for Customer Entity." }, { "code": null, "e": 1429, "s": 1308, "text": "Branch Entity : Attributes of Branch Entity are Branch_id, Name and Address. Branch_id is Primary Key for Branch Entity." }, { "code": null, "e": 1571, "s": 1429, "text": "Account Entity : Attributes of Account Entity are Account_number, Account_Type and Balance. Account_number is Primary Key for Account Entity." }, { "code": null, "e": 1686, "s": 1571, "text": "Loan Entity : Attributes of Loan Entity are Loan_id, Loan_Type and Amount. Loan_id is Primary Key for Loan Entity." }, { "code": null, "e": 1708, "s": 1686, "text": "Relationships are : " }, { "code": null, "e": 1887, "s": 1708, "text": "Bank has Branches => 1 : N One Bank can have many Branches but one Branch can not belong to many Banks, so the relationship between Bank and Branch is one to many relationship. " }, { "code": null, "e": 2082, "s": 1887, "text": "Branch maintain Accounts => 1 : N One Branch can have many Accounts but one Account can not belong to many Branches, so the relationship between Branch and Account is one to many relationship. " }, { "code": null, "e": 2262, "s": 2082, "text": "Branch offer Loans => 1 : N One Branch can have many Loans but one Loan can not belong to many Branches, so the relationship between Branch and Loan is one to many relationship. " }, { "code": null, "e": 2483, "s": 2262, "text": "Account held by Customers => M : N One Customer can have more than one Accounts and also One Account can be held by one or more Customers, so the relationship between Account and Customers is many to many relationship. " }, { "code": null, "e": 2749, "s": 2483, "text": "Loan availed by Customer => M : N (Assume loan can be jointly held by many Customers). One Customer can have more than one Loans and also One Loan can be availed by one or more Customers, so the relationship between Loan and Customers is many to many relationship. " }, { "code": null, "e": 2767, "s": 2749, "text": "pradiptamukherjee" }, { "code": null, "e": 2781, "s": 2767, "text": "DBMS-ER model" }, { "code": null, "e": 2786, "s": 2781, "text": "DBMS" }, { "code": null, "e": 2791, "s": 2786, "text": "DBMS" } ]
Prolog - Backtracking
In this chapter, we will discuss the backtracking in Prolog. Backtracking is a procedure, in which prolog searches the truth value of different predicates by checking whether they are correct or not. The backtracking term is quite common in algorithm designing, and in different programming environments. In Prolog, until it reaches proper destination, it tries to backtrack. When the destination is found, it stops. Let us see how backtracking takes place using one tree like structure − Suppose A to G are some rules and facts. We start from A and want to reach G. The proper path will be A-C-G, but at first, it will go from A to B, then B to D. When it finds that D is not the destination, it backtracks to B, then go to E, and backtracks again to B, as there is no other child of B, then it backtracks to A, thus it searches for G, and finally found G in the path A-C-G. (Dashed lines are indicating the backtracking.) So when it finds G, it stops. Now we know, what is the backtracking in Prolog. Let us see one example, Note − While we are running some prolog code, during backtracking there may be multiple answers, we can press semicolon (;) to get next answers one by one, that helps to backtrack. Otherwise when we get one result, it will stop. Now, consider a situation, where two people X and Y can pay each other, but the condition is that a boy can pay to a girl, so X will be a boy, and Y will be a girl. So for these we have defined some facts and rules − boy(tom). boy(bob). girl(alice). girl(lili). pay(X,Y) :- boy(X), girl(Y). Following is the illustration of the above scenario − As X will be a boy, so there are two choices, and for each boy there are two choices alice and lili. Now let us see the output, how backtracking is working. | ?- [backtrack]. compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code... D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 5 lines read - 703 bytes written, 22 ms yes | ?- pay(X,Y). X = tom Y = alice ? (15 ms) yes | ?- pay(X,Y). X = tom Y = alice ? ; X = tom Y = lili ? ; X = bob Y = alice ? ; X = bob Y = lili yes | ?- trace. The debugger will first creep -- showing everything (trace) (16 ms) yes {trace} | ?- pay(X,Y). 1 1 Call: pay(_23,_24) ? 2 2 Call: boy(_23) ? 2 2 Exit: boy(tom) ? 3 2 Call: girl(_24) ? 3 2 Exit: girl(alice) ? 1 1 Exit: pay(tom,alice) ? X = tom Y = alice ? ; 1 1 Redo: pay(tom,alice) ? 3 2 Redo: girl(alice) ? 3 2 Exit: girl(lili) ? 1 1 Exit: pay(tom,lili) ? X = tom Y = lili ? ; 1 1 Redo: pay(tom,lili) ? 2 2 Redo: boy(tom) ? 2 2 Exit: boy(bob) ? 3 2 Call: girl(_24) ? 3 2 Exit: girl(alice) ? 1 1 Exit: pay(bob,alice) ? X = bob Y = alice ? ; 1 1 Redo: pay(bob,alice) ? 3 2 Redo: girl(alice) ? 3 2 Exit: girl(lili) ? 1 1 Exit: pay(bob,lili) ? X = bob Y = lili yes {trace} | ?- So far we have seen some concepts of backtracking. Now let us see some drawbacks of backtracking. Sometimes we write the same predicates more than once when our program demands, for example to write recursive rules or to make some decision making systems. In such cases uncontrolled backtracking may cause inefficiency in a program. To resolve this, we will use the Cut in Prolog. Suppose we have some rules as follows − Rule 1 &minnus; if X < 3 then Y = 0 Rule 1 &minnus; if X < 3 then Y = 0 Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2 Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2 Rule 3 &minnus; if 6 <= X then Y = 4 Rule 3 &minnus; if 6 <= X then Y = 4 In Prolog syntax we can write, f(X,0) :- X < 3. % Rule 1 f(X,0) :- X < 3. % Rule 1 f(X,2) :- 3 =< X, X < 6. % Rule 2 f(X,2) :- 3 =< X, X < 6. % Rule 2 f(X,4) :- 6 =< X. % Rule 3 f(X,4) :- 6 =< X. % Rule 3 Now if we ask for a question as f (1,Y), 2 < Y. The first goal f(1,Y) instantiated Y to 0. The second goal becomes 2 < 0 which fails. Prolog tries through backtracking two unfruitful alternatives (Rule 2 and Rule 3). If we see closer, we can observe that − The three rules are mutually exclusive and one of them at most will succeed. The three rules are mutually exclusive and one of them at most will succeed. As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail. As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail. So we can use cut to resolve this. The cut can be expressed using Exclamation symbol. The prolog syntax is as follows − f (X,0) :- X < 3, !. % Rule 1 f (X,0) :- X < 3, !. % Rule 1 f (X,2) :- 3 =< X, X < 6, !. % Rule 2 f (X,2) :- 3 =< X, X < 6, !. % Rule 2 f (X,4) :- 6 =< X. % Rule 3 f (X,4) :- 6 =< X. % Rule 3 Now if we use the same question, ?- f (1,Y), 2 < Y. Prolog choose rule 1 since 1 < 3 and fails the goal 2 < Y fails. Prolog will try to backtrack, but not beyond the point marked ! In the program, rule 2 and rule 3 will not be generated. Let us see this in below execution − f(X,0) :- X < 3. % Rule 1 f(X,2) :- 3 =< X, X < 6. % Rule 2 f(X,4) :- 6 =< X. % Rule 3 | ?- [backtrack]. compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code... D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1224 bytes written, 17 ms yes | ?- f(1,Y), 2<Y. no | ?- trace . The debugger will first creep -- showing everything (trace) yes {trace} | ?- f(1,Y), 2<Y. 1 1 Call: f(1,_23) ? 2 2 Call: 1<3 ? 2 2 Exit: 1<3 ? 1 1 Exit: f(1,0) ? 3 1 Call: 2<0 ? 3 1 Fail: 2<0 ? 1 1 Redo: f(1,0) ? 2 2 Call: 3=<1 ? 2 2 Fail: 3=<1 ? 2 2 Call: 6=<1 ? 2 2 Fail: 6=<1 ? 1 1 Fail: f(1,_23) ? (46 ms) no {trace} | ?- Let us see the same using cut. f(X,0) :- X < 3,!. % Rule 1 f(X,2) :- 3 =< X, X < 6,!. % Rule 2 f(X,4) :- 6 =< X. % Rule 3 | ?- [backtrack]. 1 1 Call: [backtrack] ? compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code... D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1373 bytes written, 15 ms 1 1 Exit: [backtrack] ? (16 ms) yes {trace} | ?- f(1,Y), 2<Y. 1 1 Call: f(1,_23) ? 2 2 Call: 1<3 ? 2 2 Exit: 1<3 ? 1 1 Exit: f(1,0) ? 3 1 Call: 2<0 ? 3 1 Fail: 2<0 ? no {trace} | ?- Here we will perform failure when condition does not satisfy. Suppose we have a statement, “Mary likes all animals but snakes”, we will express this in Prolog. It would be very easy and straight forward, if the statement is “Mary likes all animals”. In that case we can write “Mary likes X if X is an animal”. And in prolog we can write this statement as, likes(mary, X) := animal(X). Our actual statement can be expressed as − If X is snake, then “Mary likes X” is not true If X is snake, then “Mary likes X” is not true Otherwise if X is an animal, then Mary likes X. Otherwise if X is an animal, then Mary likes X. In prolog we can write this as − likes(mary,X) :- snake(X), !, fail. likes(mary,X) :- snake(X), !, fail. likes(mary, X) :- animal(X). likes(mary, X) :- animal(X). The ‘fail’ statement causes the failure. Now let us see how it works in Prolog. animal(dog). animal(cat). animal(elephant). animal(tiger). animal(cobra). animal(python). snake(cobra). snake(python). likes(mary, X) :- snake(X), !, fail. likes(mary, X) :- animal(X). | ?- [negate_fail]. compiling D:/TP Prolog/Sample_Codes/negate_fail.pl for byte code... D:/TP Prolog/Sample_Codes/negate_fail.pl compiled, 11 lines read - 1118 bytes written, 17 ms yes | ?- likes(mary,elephant). yes | ?- likes(mary,tiger). yes | ?- likes(mary,python). no | ?- likes(mary,cobra). no | ?- trace . The debugger will first creep -- showing everything (trace) yes {trace} | ?- likes(mary,dog). 1 1 Call: likes(mary,dog) ? 2 2 Call: snake(dog) ? 2 2 Fail: snake(dog) ? 2 2 Call: animal(dog) ? 2 2 Exit: animal(dog) ? 1 1 Exit: likes(mary,dog) ? yes {trace} | ?- likes(mary,python). 1 1 Call: likes(mary,python) ? 2 2 Call: snake(python) ? 2 2 Exit: snake(python) ? 3 2 Call: fail ? 3 2 Fail: fail ? 1 1 Fail: likes(mary,python) ?
[ { "code": null, "e": 2643, "s": 2226, "text": "In this chapter, we will discuss the backtracking in Prolog. Backtracking is a procedure, in which prolog searches the truth value of different predicates by checking whether they are correct or not. The backtracking term is quite common in algorithm designing, and in different programming environments. In Prolog, until it reaches proper destination, it tries to backtrack. When the destination is found, it stops." }, { "code": null, "e": 2715, "s": 2643, "text": "Let us see how backtracking takes place using one tree like structure −" }, { "code": null, "e": 3180, "s": 2715, "text": "Suppose A to G are some rules and facts. We start from A and want to reach G. The proper path will be A-C-G, but at first, it will go from A to B, then B to D. When it finds that D is not the destination, it backtracks to B, then go to E, and backtracks again to B, as there is no other child of B, then it backtracks to A, thus it searches for G, and finally found G in the path A-C-G. (Dashed lines are indicating the backtracking.) So when it finds G, it stops." }, { "code": null, "e": 3253, "s": 3180, "text": "Now we know, what is the backtracking in Prolog. Let us see one example," }, { "code": null, "e": 3482, "s": 3253, "text": "Note − While we are running some prolog code, during backtracking there may be multiple answers, we can press semicolon (;) to get next answers one by one, that helps to backtrack. Otherwise when we get one result, it will stop." }, { "code": null, "e": 3699, "s": 3482, "text": "Now, consider a situation, where two people X and Y can pay each other, but the condition is that a boy can pay to a girl, so X will be a boy, and Y will be a girl. So for these we have defined some facts and rules −" }, { "code": null, "e": 3774, "s": 3699, "text": "boy(tom).\nboy(bob).\ngirl(alice).\ngirl(lili).\n\npay(X,Y) :- boy(X), girl(Y)." }, { "code": null, "e": 3828, "s": 3774, "text": "Following is the illustration of the above scenario −" }, { "code": null, "e": 3985, "s": 3828, "text": "As X will be a boy, so there are two choices, and for each boy there are two choices alice and lili. Now let us see the output, how backtracking is working." }, { "code": null, "e": 5080, "s": 3985, "text": "| ?- [backtrack].\ncompiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...\nD:/TP Prolog/Sample_Codes/backtrack.pl compiled, 5 lines read - 703 bytes written, 22 ms\n\nyes\n| ?- pay(X,Y).\n\nX = tom\nY = alice ?\n\n(15 ms) yes\n| ?- pay(X,Y).\n\nX = tom\nY = alice ? ;\n\nX = tom\nY = lili ? ;\n\nX = bob\nY = alice ? ;\n\nX = bob\nY = lili\n\nyes\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\n(16 ms) yes\n{trace}\n| ?- pay(X,Y).\n 1 1 Call: pay(_23,_24) ?\n 2 2 Call: boy(_23) ?\n 2 2 Exit: boy(tom) ?\n 3 2 Call: girl(_24) ?\n 3 2 Exit: girl(alice) ?\n 1 1 Exit: pay(tom,alice) ?\n \nX = tom\nY = alice ? ;\n 1 1 Redo: pay(tom,alice) ?\n 3 2 Redo: girl(alice) ?\n 3 2 Exit: girl(lili) ?\n 1 1 Exit: pay(tom,lili) ?\n \nX = tom\nY = lili ? ;\n 1 1 Redo: pay(tom,lili) ?\n 2 2 Redo: boy(tom) ?\n 2 2 Exit: boy(bob) ?\n 3 2 Call: girl(_24) ?\n 3 2 Exit: girl(alice) ?\n 1 1 Exit: pay(bob,alice) ?\n \nX = bob\nY = alice ? ;\n 1 1 Redo: pay(bob,alice) ?\n 3 2 Redo: girl(alice) ?\n 3 2 Exit: girl(lili) ?\n 1 1 Exit: pay(bob,lili) ?\nX = bob\nY = lili\n\nyes\n{trace}\n| ?-\n" }, { "code": null, "e": 5461, "s": 5080, "text": "So far we have seen some concepts of backtracking. Now let us see some drawbacks of backtracking. Sometimes we write the same predicates more than once when our program demands, for example to write recursive rules or to make some decision making systems. In such cases uncontrolled backtracking may cause inefficiency in a program. To resolve this, we will use the Cut in Prolog." }, { "code": null, "e": 5501, "s": 5461, "text": "Suppose we have some rules as follows −" }, { "code": null, "e": 5537, "s": 5501, "text": "Rule 1 &minnus; if X < 3 then Y = 0" }, { "code": null, "e": 5573, "s": 5537, "text": "Rule 1 &minnus; if X < 3 then Y = 0" }, { "code": null, "e": 5620, "s": 5573, "text": "Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2" }, { "code": null, "e": 5667, "s": 5620, "text": "Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2" }, { "code": null, "e": 5704, "s": 5667, "text": "Rule 3 &minnus; if 6 <= X then Y = 4" }, { "code": null, "e": 5741, "s": 5704, "text": "Rule 3 &minnus; if 6 <= X then Y = 4" }, { "code": null, "e": 5772, "s": 5741, "text": "In Prolog syntax we can write," }, { "code": null, "e": 5810, "s": 5772, "text": "f(X,0) :- X < 3. % Rule 1" }, { "code": null, "e": 5848, "s": 5810, "text": "f(X,0) :- X < 3. % Rule 1" }, { "code": null, "e": 5883, "s": 5848, "text": "f(X,2) :- 3 =< X, X < 6. % Rule 2" }, { "code": null, "e": 5918, "s": 5883, "text": "f(X,2) :- 3 =< X, X < 6. % Rule 2" }, { "code": null, "e": 5956, "s": 5918, "text": "f(X,4) :- 6 =< X. % Rule 3" }, { "code": null, "e": 5994, "s": 5956, "text": "f(X,4) :- 6 =< X. % Rule 3" }, { "code": null, "e": 6042, "s": 5994, "text": "Now if we ask for a question as f (1,Y), 2 < Y." }, { "code": null, "e": 6251, "s": 6042, "text": "The first goal f(1,Y) instantiated Y to 0. The second goal becomes 2 < 0 which fails. Prolog tries through backtracking two unfruitful alternatives (Rule 2 and Rule 3). If we see closer, we can observe that −" }, { "code": null, "e": 6328, "s": 6251, "text": "The three rules are mutually exclusive and one of them at most will succeed." }, { "code": null, "e": 6405, "s": 6328, "text": "The three rules are mutually exclusive and one of them at most will succeed." }, { "code": null, "e": 6510, "s": 6405, "text": "As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail." }, { "code": null, "e": 6615, "s": 6510, "text": "As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail." }, { "code": null, "e": 6735, "s": 6615, "text": "So we can use cut to resolve this. The cut can be expressed using Exclamation symbol. The prolog syntax is as follows −" }, { "code": null, "e": 6776, "s": 6735, "text": "f (X,0) :- X < 3, !. % Rule 1" }, { "code": null, "e": 6817, "s": 6776, "text": "f (X,0) :- X < 3, !. % Rule 1" }, { "code": null, "e": 6855, "s": 6817, "text": "f (X,2) :- 3 =< X, X < 6, !. % Rule 2" }, { "code": null, "e": 6893, "s": 6855, "text": "f (X,2) :- 3 =< X, X < 6, !. % Rule 2" }, { "code": null, "e": 6934, "s": 6893, "text": "f (X,4) :- 6 =< X. % Rule 3" }, { "code": null, "e": 6975, "s": 6934, "text": "f (X,4) :- 6 =< X. % Rule 3" }, { "code": null, "e": 7213, "s": 6975, "text": "Now if we use the same question, ?- f (1,Y), 2 < Y. Prolog choose rule 1 since 1 < 3 and fails the goal 2 < Y fails. Prolog will try to backtrack, but not beyond the point marked ! In the program, rule 2 and rule 3 will not be generated." }, { "code": null, "e": 7250, "s": 7213, "text": "Let us see this in below execution −" }, { "code": null, "e": 7364, "s": 7250, "text": "f(X,0) :- X < 3. % Rule 1\nf(X,2) :- 3 =< X, X < 6. % Rule 2\nf(X,4) :- 6 =< X. % Rule 3" }, { "code": null, "e": 7947, "s": 7364, "text": "| ?- [backtrack].\ncompiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...\nD:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1224 bytes written, 17 ms\n\nyes\n| ?- f(1,Y), 2<Y.\n\nno\n| ?- trace\n.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- f(1,Y), 2<Y.\n 1 1 Call: f(1,_23) ?\n 2 2 Call: 1<3 ?\n 2 2 Exit: 1<3 ?\n 1 1 Exit: f(1,0) ?\n 3 1 Call: 2<0 ?\n 3 1 Fail: 2<0 ?\n 1 1 Redo: f(1,0) ?\n 2 2 Call: 3=<1 ?\n 2 2 Fail: 3=<1 ?\n 2 2 Call: 6=<1 ?\n 2 2 Fail: 6=<1 ?\n 1 1 Fail: f(1,_23) ?\n \n(46 ms) no\n{trace}\n| ?-\n" }, { "code": null, "e": 7978, "s": 7947, "text": "Let us see the same using cut." }, { "code": null, "e": 8092, "s": 7978, "text": "f(X,0) :- X < 3,!. % Rule 1\nf(X,2) :- 3 =< X, X < 6,!. % Rule 2\nf(X,4) :- 6 =< X. % Rule 3" }, { "code": null, "e": 8498, "s": 8092, "text": "| ?- [backtrack].\n 1 1 Call: [backtrack] ?\ncompiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...\nD:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1373 bytes written, 15 ms\n 1 1 Exit: [backtrack] ?\n(16 ms) yes\n{trace}\n| ?- f(1,Y), 2<Y.\n 1 1 Call: f(1,_23) ?\n 2 2 Call: 1<3 ?\n 2 2 Exit: 1<3 ?\n 1 1 Exit: f(1,0) ?\n 3 1 Call: 2<0 ?\n 3 1 Fail: 2<0 ?\nno\n{trace}\n| ?-\n" }, { "code": null, "e": 8658, "s": 8498, "text": "Here we will perform failure when condition does not satisfy. Suppose we have a statement, “Mary likes all animals but snakes”, we will express this in Prolog." }, { "code": null, "e": 8883, "s": 8658, "text": "It would be very easy and straight forward, if the statement is “Mary likes all animals”. In that case we can write “Mary likes X if X is an animal”. And in prolog we can write this statement as, likes(mary, X) := animal(X)." }, { "code": null, "e": 8926, "s": 8883, "text": "Our actual statement can be expressed as −" }, { "code": null, "e": 8973, "s": 8926, "text": "If X is snake, then “Mary likes X” is not true" }, { "code": null, "e": 9020, "s": 8973, "text": "If X is snake, then “Mary likes X” is not true" }, { "code": null, "e": 9068, "s": 9020, "text": "Otherwise if X is an animal, then Mary likes X." }, { "code": null, "e": 9116, "s": 9068, "text": "Otherwise if X is an animal, then Mary likes X." }, { "code": null, "e": 9149, "s": 9116, "text": "In prolog we can write this as −" }, { "code": null, "e": 9185, "s": 9149, "text": "likes(mary,X) :- snake(X), !, fail." }, { "code": null, "e": 9221, "s": 9185, "text": "likes(mary,X) :- snake(X), !, fail." }, { "code": null, "e": 9250, "s": 9221, "text": "likes(mary, X) :- animal(X)." }, { "code": null, "e": 9279, "s": 9250, "text": "likes(mary, X) :- animal(X)." }, { "code": null, "e": 9359, "s": 9279, "text": "The ‘fail’ statement causes the failure. Now let us see how it works in Prolog." }, { "code": null, "e": 9546, "s": 9359, "text": "animal(dog).\nanimal(cat).\nanimal(elephant).\nanimal(tiger).\nanimal(cobra).\nanimal(python).\n\nsnake(cobra).\nsnake(python).\n\nlikes(mary, X) :- snake(X), !, fail.\nlikes(mary, X) :- animal(X)." } ]
Sum of upper triangle and lower triangle
08 Jun, 2022 Given a matrix print the sum of upper and lower triangular elements (i.e elements on diagonal and the upper and lower elements).Examples : Input : {6, 5, 4} {1, 2, 5} {7, 9, 7} Output : Upper sum is 29 Lower sum is 32 The solution is quite simple, we just need to traverse the matrix and calculate the sum for upper and lower triangles accordingly. C++ Java Python3 C# PHP Javascript // C++ program to calculate the sum// of upper and lower triangle#include <bits/stdc++.h>using namespace std; /*function to calculate sum*/void sum(int mat[3][3], int r, int c){ int i, j; int upper_sum = 0; int lower_sum = 0; /*to calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i][j]; } } printf("Upper sum is %d\n", upper_sum); /*to calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i][j]; } } printf("Lower sum is %d", lower_sum);} /*driver function*/int main(){ int r = 3; int c = 3; /*giving the matrix*/ int mat[3][3] = {{ 6, 5, 4 }, { 1, 2, 5 }, { 7, 9, 7 }}; /*calling the function*/ sum(mat, r, c); return 0;} // Java program to calculate the sum// of upper and lower triangle class GFG{ /*function to calculate sum*/ static void sum(int mat[][], int r, int c) { int i, j; int upper_sum = 0; int lower_sum = 0; /*calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i][j]; } } System.out.println("Upper sum is " + upper_sum); /*calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i][j]; } } System.out.print("Lower sum is " + lower_sum); } // Driver code public static void main (String[] args) { int r = 3; int c = 3; /*giving the matrix*/ int mat[][] = {{ 6, 5, 4 }, { 1, 2, 5 }, { 7, 9, 7 }}; /*calling the function*/ sum(mat, r, c); }} // This code is contributed by Anant Agarwal. # Python3 program to calculate the sum# of upper and lower triangle # function to calculate sumdef Sum(mat, r, c): i, j = 0, 0; upper_sum = 0; lower_sum = 0; # to calculate sum of upper triangle for i in range(r): for j in range(c): if (i <= j): upper_sum += mat[i][j]; print("Upper sum is ", upper_sum); # to calculate sum of lower for i in range(r): for j in range(c): if (j <= i): lower_sum += mat[i][j]; print("Lower sum is ", lower_sum); # Driver Coder = 3;c = 3; # giving the matrixmat = [[ 6, 5, 4 ], [ 1, 2, 5 ], [ 7, 9, 7 ]]; # calling the functionSum(mat, r, c); # This code is contributed by 29AjayKumar // C# program to calculate the sum// of upper and lower triangleusing System; class GFG{ /*function to calculate sum*/ static void sum(int [,]mat, int r, int c) { int i, j; int upper_sum = 0; int lower_sum = 0; /*calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i,j]; } } Console.WriteLine("Upper sum is " + upper_sum); /*calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i,j]; } } Console.Write("Lower sum is " + lower_sum); } // Driver code public static void Main () { int r = 3; int c = 3; /*giving the matrix*/ int [,]mat = {{6, 5, 4}, {1, 2, 5}, {7, 9, 7}}; /*calling the function*/ sum(mat, r, c); }} // This code is contributed by nitin mittal. <?php// PHP program to calculate the sum// of upper and lower triangle // function to calculate sumfunction sum($mat, $r, $c){ $upper_sum = 0; $lower_sum = 0; /* to calculate sum of upper triangle */ for ($i = 0; $i < $r; $i++) for ($j = 0; $j < $c; $j++) { if ($i <= $j) { $upper_sum += $mat[$i][$j]; } } echo "Upper sum is ". $upper_sum."\n"; /* to calculate sum of lower */ for ($i = 0; $i < $r; $i++) for ($j = 0; $j < $c; $j++) { if ($j <= $i) { $lower_sum += $mat[$i][$j]; } } echo "Lower sum is ". $lower_sum;} // Driver Code $r = 3; $c = 3; /*giving the matrix*/ $mat = array(array(6, 5, 4), array(1, 2, 5), array(7, 9, 7)); /*calling the function*/ sum($mat, $r, $c); // This code is contributed by Sam007?> <script> // Javascript program to calculate the sum// of upper and lower triangle /*function to calculate sum*/function sum(mat,r,c){ let i, j; let upper_sum = 0; let lower_sum = 0; /*to calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i][j]; } } document.write("Upper sum is "+ upper_sum+"<br/>"); /*to calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i][j]; } } document.write("Lower sum is "+lower_sum);} /*driver function*/ let r = 3; let c = 3; /*giving the matrix*/ let mat = [[ 6, 5, 4 ], [ 1, 2, 5 ], [ 7, 9, 7 ]]; /*calling the function*/ sum(mat, r, c); // This code contributed by Rajput-Ji </script> Output : Upper sum is 29 Lower sum is 32 Time Complexity: O(r * c), where r and c represents the number of rows and columns of the given matrix.Auxiliary Space: O(1), no extra space is required, so it is a constant. This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Sam007 29AjayKumar Rajput-Ji tamanna17122007 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. The Celebrity Problem Maximum size rectangle binary sub-matrix with all 1s 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 Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jun, 2022" }, { "code": null, "e": 193, "s": 52, "text": "Given a matrix print the sum of upper and lower triangular elements (i.e elements on diagonal and the upper and lower elements).Examples : " }, { "code": null, "e": 288, "s": 193, "text": "Input : {6, 5, 4}\n {1, 2, 5}\n {7, 9, 7}\nOutput :\nUpper sum is 29\nLower sum is 32" }, { "code": null, "e": 423, "s": 290, "text": "The solution is quite simple, we just need to traverse the matrix and calculate the sum for upper and lower triangles accordingly. " }, { "code": null, "e": 427, "s": 423, "text": "C++" }, { "code": null, "e": 432, "s": 427, "text": "Java" }, { "code": null, "e": 440, "s": 432, "text": "Python3" }, { "code": null, "e": 443, "s": 440, "text": "C#" }, { "code": null, "e": 447, "s": 443, "text": "PHP" }, { "code": null, "e": 458, "s": 447, "text": "Javascript" }, { "code": "// C++ program to calculate the sum// of upper and lower triangle#include <bits/stdc++.h>using namespace std; /*function to calculate sum*/void sum(int mat[3][3], int r, int c){ int i, j; int upper_sum = 0; int lower_sum = 0; /*to calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i][j]; } } printf(\"Upper sum is %d\\n\", upper_sum); /*to calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i][j]; } } printf(\"Lower sum is %d\", lower_sum);} /*driver function*/int main(){ int r = 3; int c = 3; /*giving the matrix*/ int mat[3][3] = {{ 6, 5, 4 }, { 1, 2, 5 }, { 7, 9, 7 }}; /*calling the function*/ sum(mat, r, c); return 0;}", "e": 1425, "s": 458, "text": null }, { "code": "// Java program to calculate the sum// of upper and lower triangle class GFG{ /*function to calculate sum*/ static void sum(int mat[][], int r, int c) { int i, j; int upper_sum = 0; int lower_sum = 0; /*calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i][j]; } } System.out.println(\"Upper sum is \" + upper_sum); /*calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i][j]; } } System.out.print(\"Lower sum is \" + lower_sum); } // Driver code public static void main (String[] args) { int r = 3; int c = 3; /*giving the matrix*/ int mat[][] = {{ 6, 5, 4 }, { 1, 2, 5 }, { 7, 9, 7 }}; /*calling the function*/ sum(mat, r, c); }} // This code is contributed by Anant Agarwal.", "e": 2653, "s": 1425, "text": null }, { "code": "# Python3 program to calculate the sum# of upper and lower triangle # function to calculate sumdef Sum(mat, r, c): i, j = 0, 0; upper_sum = 0; lower_sum = 0; # to calculate sum of upper triangle for i in range(r): for j in range(c): if (i <= j): upper_sum += mat[i][j]; print(\"Upper sum is \", upper_sum); # to calculate sum of lower for i in range(r): for j in range(c): if (j <= i): lower_sum += mat[i][j]; print(\"Lower sum is \", lower_sum); # Driver Coder = 3;c = 3; # giving the matrixmat = [[ 6, 5, 4 ], [ 1, 2, 5 ], [ 7, 9, 7 ]]; # calling the functionSum(mat, r, c); # This code is contributed by 29AjayKumar", "e": 3386, "s": 2653, "text": null }, { "code": "// C# program to calculate the sum// of upper and lower triangleusing System; class GFG{ /*function to calculate sum*/ static void sum(int [,]mat, int r, int c) { int i, j; int upper_sum = 0; int lower_sum = 0; /*calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i,j]; } } Console.WriteLine(\"Upper sum is \" + upper_sum); /*calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i,j]; } } Console.Write(\"Lower sum is \" + lower_sum); } // Driver code public static void Main () { int r = 3; int c = 3; /*giving the matrix*/ int [,]mat = {{6, 5, 4}, {1, 2, 5}, {7, 9, 7}}; /*calling the function*/ sum(mat, r, c); }} // This code is contributed by nitin mittal.", "e": 4649, "s": 3386, "text": null }, { "code": "<?php// PHP program to calculate the sum// of upper and lower triangle // function to calculate sumfunction sum($mat, $r, $c){ $upper_sum = 0; $lower_sum = 0; /* to calculate sum of upper triangle */ for ($i = 0; $i < $r; $i++) for ($j = 0; $j < $c; $j++) { if ($i <= $j) { $upper_sum += $mat[$i][$j]; } } echo \"Upper sum is \". $upper_sum.\"\\n\"; /* to calculate sum of lower */ for ($i = 0; $i < $r; $i++) for ($j = 0; $j < $c; $j++) { if ($j <= $i) { $lower_sum += $mat[$i][$j]; } } echo \"Lower sum is \". $lower_sum;} // Driver Code $r = 3; $c = 3; /*giving the matrix*/ $mat = array(array(6, 5, 4), array(1, 2, 5), array(7, 9, 7)); /*calling the function*/ sum($mat, $r, $c); // This code is contributed by Sam007?>", "e": 5627, "s": 4649, "text": null }, { "code": "<script> // Javascript program to calculate the sum// of upper and lower triangle /*function to calculate sum*/function sum(mat,r,c){ let i, j; let upper_sum = 0; let lower_sum = 0; /*to calculate sum of upper triangle*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (i <= j) { upper_sum += mat[i][j]; } } document.write(\"Upper sum is \"+ upper_sum+\"<br/>\"); /*to calculate sum of lower*/ for (i = 0; i < r; i++) for (j = 0; j < c; j++) { if (j <= i) { lower_sum += mat[i][j]; } } document.write(\"Lower sum is \"+lower_sum);} /*driver function*/ let r = 3; let c = 3; /*giving the matrix*/ let mat = [[ 6, 5, 4 ], [ 1, 2, 5 ], [ 7, 9, 7 ]]; /*calling the function*/ sum(mat, r, c); // This code contributed by Rajput-Ji </script>", "e": 6588, "s": 5627, "text": null }, { "code": null, "e": 6598, "s": 6588, "text": "Output : " }, { "code": null, "e": 6630, "s": 6598, "text": "Upper sum is 29\nLower sum is 32" }, { "code": null, "e": 6805, "s": 6630, "text": "Time Complexity: O(r * c), where r and c represents the number of rows and columns of the given matrix.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 7220, "s": 6805, "text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7233, "s": 7220, "text": "nitin mittal" }, { "code": null, "e": 7240, "s": 7233, "text": "Sam007" }, { "code": null, "e": 7252, "s": 7240, "text": "29AjayKumar" }, { "code": null, "e": 7262, "s": 7252, "text": "Rajput-Ji" }, { "code": null, "e": 7278, "s": 7262, "text": "tamanna17122007" }, { "code": null, "e": 7285, "s": 7278, "text": "Matrix" }, { "code": null, "e": 7304, "s": 7285, "text": "School Programming" }, { "code": null, "e": 7311, "s": 7304, "text": "Matrix" }, { "code": null, "e": 7409, "s": 7311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7431, "s": 7409, "text": "The Celebrity Problem" }, { "code": null, "e": 7484, "s": 7431, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 7522, "s": 7484, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 7593, "s": 7522, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 7635, "s": 7593, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 7653, "s": 7635, "text": "Python Dictionary" }, { "code": null, "e": 7678, "s": 7653, "text": "Reverse a string in Java" }, { "code": null, "e": 7694, "s": 7678, "text": "Arrays in C/C++" }, { "code": null, "e": 7717, "s": 7694, "text": "Introduction To PYTHON" } ]
Python Easy-Login Module
04 Jul, 2021 Easy-Login module is that library of Python which helps you to login in your social accounts like Facebook, Instagram, Twitter, Linkedin, Reddit etc through Python without opening the sites manually . Installation This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install easy-login It will automatically login your account in a separate window using chrome webdriver and will take you over the home page of that website Web Drivers Selenium requires a web driver to interface with the chosen browser. Web drivers is a package to interact with a web browser. It interacts with the web browser or a remote web server through a wire protocol which is common to all. You can check out and install the web drivers of your browser choice. Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads Firefox: https://github.com/mozilla/geckodriver/releases Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/ Username and password must be of same account which you have to login and must be in string format. Address must be in string format with forward slash(/) like C:/Users/user1/chromedriver_win32/chromedriver . Here is the demonstration for this module : python3 # importing the modulefrom easy_login import login # initializing the username and passwordusername = ""password = "" # initializing the address of chrome web driveraddress = "" # creating an object of loginobj = login(username, password, addresses) # calling the account in which we want to loginobj.Facebook()obj.Instagram()obj.Twitter()obj.Linkedin()obj.Reddit() anikaseth98 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2021" }, { "code": null, "e": 256, "s": 54, "text": "Easy-Login module is that library of Python which helps you to login in your social accounts like Facebook, Instagram, Twitter, Linkedin, Reddit etc through Python without opening the sites manually . " }, { "code": null, "e": 269, "s": 256, "text": "Installation" }, { "code": null, "e": 415, "s": 269, "text": "This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal." }, { "code": null, "e": 438, "s": 415, "text": "pip install easy-login" }, { "code": null, "e": 577, "s": 438, "text": "It will automatically login your account in a separate window using chrome webdriver and will take you over the home page of that website" }, { "code": null, "e": 891, "s": 577, "text": "Web Drivers Selenium requires a web driver to interface with the chosen browser. Web drivers is a package to interact with a web browser. It interacts with the web browser or a remote web server through a wire protocol which is common to all. You can check out and install the web drivers of your browser choice. " }, { "code": null, "e": 1094, "s": 891, "text": "Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads\nFirefox: https://github.com/mozilla/geckodriver/releases\nSafari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/" }, { "code": null, "e": 1304, "s": 1094, "text": "Username and password must be of same account which you have to login and must be in string format. Address must be in string format with forward slash(/) like C:/Users/user1/chromedriver_win32/chromedriver ." }, { "code": null, "e": 1350, "s": 1304, "text": "Here is the demonstration for this module : " }, { "code": null, "e": 1358, "s": 1350, "text": "python3" }, { "code": "# importing the modulefrom easy_login import login # initializing the username and passwordusername = \"\"password = \"\" # initializing the address of chrome web driveraddress = \"\" # creating an object of loginobj = login(username, password, addresses) # calling the account in which we want to loginobj.Facebook()obj.Instagram()obj.Twitter()obj.Linkedin()obj.Reddit()", "e": 1724, "s": 1358, "text": null }, { "code": null, "e": 1736, "s": 1724, "text": "anikaseth98" }, { "code": null, "e": 1751, "s": 1736, "text": "python-modules" }, { "code": null, "e": 1758, "s": 1751, "text": "Python" }, { "code": null, "e": 1856, "s": 1758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1888, "s": 1856, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1915, "s": 1888, "text": "Python Classes and Objects" }, { "code": null, "e": 1936, "s": 1915, "text": "Python OOPs Concepts" }, { "code": null, "e": 1959, "s": 1936, "text": "Introduction To PYTHON" }, { "code": null, "e": 2015, "s": 1959, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2046, "s": 2015, "text": "Python | os.path.join() method" }, { "code": null, "e": 2088, "s": 2046, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2130, "s": 2088, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2169, "s": 2130, "text": "Python | Get unique values from a list" } ]
Search element in a Spirally sorted Matrix
11 Aug, 2021 Given a spirally sorted matrix with N × N elements and an integer X, the task is to find the position of this given integer in the matrix if it exists, else print -1. Note that all the matrix elements are distinct. Examples: Input: arr[] = { {1, 2, 3, 4}, {12, 13, 14, 5}, {11, 16, 15, 6}, {10, 9, 8, 7}}, X = 9 Output: 3 1 9 appears in row number 3 and column number 1 (0-based indexing) Thus, output is (3, 1). Input: arr[] = { {1, 2, 3}, {8, 9, 4}, {7, 6, 5}}, X = 9 Output: 1 1 A simple solution is to search through all the elements in the array. The worst-case time complexity of this approach will be O(n2). A better solution is to use binary search. We apply binary search in two phases. But before jumping to that, let’s define what a ring means here. A ring is defined as a set of all the cells in the array such that their minimum of the distances from all four sides is equal. First, we try to determine the ring the number ‘X’ will belong to. We will do this using binary search. For that, observe the diagonal elements of the matrix. The first ceil(N/2) of the diagonal matrix is guaranteed to be sorted in increasing order. So, each one of the ceil(N/2) diagonal elements can represent a ring. By, applying binary on the first ceil(N/2) diagonal elements, we determine the ring the number ‘X’ belongs to in O(log(n)) time. After that, we apply a binary search on the elements of the ring. Before that we determine the side of the ring, the number ‘X’ will belong to. Then, we apply the binary search correspondingly.So, the total time complexity becomes O(log(n)). Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach #include <iostream>#define n 4using namespace std; // Function to return the ring, the number x// belongs to.int findRing(int arr[][n], int x){ // Returns -1 if number x is smaller than // least element of arr if (arr[0][0] > x) return -1; // l and r represent the diagonal // elements to search in int l = 0, r = (n + 1) / 2 - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r][r] < x) return -1; if (n % 2 == 0 && arr[r + 1][r] < x) return -1; while (l < r) { int mid = (l + r) / 2; if (arr[mid][mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1][mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedint binarySearchRowInc(int arr[][n], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsint binarySearchColumnInc(int arr[][n], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderint binarySearchRowDec(int arr[][n], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arrayint binarySearchColumnDec(int arr[][n], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xvoid spiralBinary(int arr[][n], int x){ // Finding the ring int f1 = findRing(arr, x); // To store row and column int r, c; if (f1 == -1) { cout << "-1"; return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { cout << f1 << " " << f1 << endl; return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1][n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1][n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1][f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) cout << "-1"; else cout << r << " " << c; return;} // Driver codeint main(){ int arr[][n] = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; spiralBinary(arr, 7); return 0;} // Java implementation of the above approachclass GFG{ final static int n =4; // Function to return the ring,// the number x belongs to.static int findRing(int arr[][], int x){ // Returns -1 if number x is // smaller than least element of arr if (arr[0][0] > x) return -1; // l and r represent the diagonal // elements to search in int l = 0, r = (n + 1) / 2 - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r][r] < x) return -1; if (n % 2 == 0 && arr[r + 1][r] < x) return -1; while (l < r) { int mid = (l + r) / 2; if (arr[mid][mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1][mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedstatic int binarySearchRowInc(int arr[][], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsstatic int binarySearchColumnInc(int arr[][], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderstatic int binarySearchRowDec(int arr[][], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arraystatic int binarySearchColumnDec(int arr[][], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xstatic void spiralBinary(int arr[][], int x){ // Finding the ring int f1 = findRing(arr, x); // To store row and column int r, c; if (f1 == -1) { System.out.print("-1"); return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { System.out.println(f1+" "+f1); return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1][n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1][n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1][f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) System.out.print("-1"); else System.out.print(r+" "+c); return;} // Driver codepublic static void main(String[] args){ int arr[][] = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; spiralBinary(arr, 7);}} // This code is contributed by 29AjayKumar # Python3 implementation of the above approach # Function to return the ring,# the number x belongs to.def findRing(arr, x): # Returns -1 if number x is smaller # than least element of arr if arr[0][0] > x: return -1 # l and r represent the diagonal # elements to search in l, r = 0, (n + 1) // 2 - 1 # Returns -1 if number x is greater # than the largest element of arr if n % 2 == 1 and arr[r][r] < x: return -1 if n % 2 == 0 and arr[r + 1][r] < x: return -1 while l < r: mid = (l + r) // 2 if arr[mid][mid] <= x: if (mid == (n + 1) // 2 - 1 or arr[mid + 1][mid + 1] > x): return mid else: l = mid + 1 else: r = mid - 1 return r # Function to perform binary search# on an array sorted in increasing order# l and r represent the left and right# index of the row to be searcheddef binarySearchRowInc(arr, row, l, r, x): while l <= r: mid = (l + r) // 2 if arr[row][mid] == x: return mid elif arr[row][mid] < x: l = mid + 1 else: r = mid - 1 return -1 # Function to perform binary search on# a particular column of the 2D array# t and b represent top and# bottom rowsdef binarySearchColumnInc(arr, col, t, b, x): while t <= b: mid = (t + b) // 2 if arr[mid][col] == x: return mid elif arr[mid][col] < x: t = mid + 1 else: b = mid - 1 return -1 # Function to perform binary search on# an array sorted in decreasing orderdef binarySearchRowDec(arr, row, l, r, x): while l <= r: mid = (l + r) // 2 if arr[row][mid] == x: return mid elif arr[row][mid] < x: r = mid - 1 else: l = mid + 1 return -1 # Function to perform binary search on a# particular column of the 2D arraydef binarySearchColumnDec(arr, col, t, b, x): while t <= b: mid = (t + b) // 2 if arr[mid][col] == x: return mid elif arr[mid][col] < x: b = mid - 1 else: t = mid + 1 return -1 # Function to find the position of the number xdef spiralBinary(arr, x): # Finding the ring f1 = findRing(arr, x) # To store row and column r, c = None, None if f1 == -1: print("-1") return # Edge case if n is odd if n % 2 == 1 and f1 == (n + 1) // 2 - 1: print(f1, f1) return # Check which of the 4 sides, # the number x lies in if x < arr[f1][n - f1 - 1]: c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x) r = f1 elif x < arr[n - f1 - 1][n - f1 - 1]: c = n - f1 - 1 r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x) elif x < arr[n - f1 - 1][f1]: c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x) r = n - f1 - 1 else: r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x) c = f1 # Printing the position if c == -1 or r == -1: print("-1") else: print("{0} {1}".format(r, c)) # Driver codeif __name__ == "__main__": n = 4 arr = [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]] spiralBinary(arr, 7) # This code is contributed by Rituraj Jain // C# implementation of the above approachusing System;class GFG{ static int n =4; // Function to return the ring,// the number x belongs to.static int findRing(int [,]arr, int x){ // Returns -1 if number x is // smaller than least element of arr if (arr[0,0] > x) return -1; // l and r represent the diagonal // elements to search in int l = 0, r = (n + 1) / 2 - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r,r] < x) return -1; if (n % 2 == 0 && arr[r + 1,r] < x) return -1; while (l < r) { int mid = (l + r) / 2; if (arr[mid,mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1,mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedstatic int binarySearchRowInc(int [,]arr, int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row,mid] == x) return mid; if (arr[row,mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsstatic int binarySearchColumnInc(int [,]arr, int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid,col] == x) return mid; if (arr[mid,col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderstatic int binarySearchRowDec(int [,]arr, int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row,mid] == x) return mid; if (arr[row,mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arraystatic int binarySearchColumnDec(int [,]arr, int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid,col] == x) return mid; if (arr[mid,col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xstatic void spiralBinary(int [,]arr, int x){ // Finding the ring int f1 = findRing(arr, x); // To store row and column int r, c; if (f1 == -1) { Console.Write("-1"); return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { Console.WriteLine(f1+" "+f1); return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1,n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1,n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1,f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) Console.Write("-1"); else Console.Write(r+" "+c); return;} // Driver codepublic static void Main(String []args){ int [,]arr = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; spiralBinary(arr, 7);}} // This code is contributed by Arnab Kundu <?php// PHP implementation of the above approach$n = 4; // Function to return the ring, the number x// belongs to.function findRing($arr, $x){ global $n; // Returns -1 if number x is smaller than // least element of arr if ($arr[0][0] > $x) return -1; // l and r represent the diagonal // elements to search in $l = 0; $r = (int)(($n + 1) / 2 - 1); // Returns -1 if number x is greater // than the largest element of arr if ($n % 2 == 1 && $arr[$r][$r] < $x) return -1; if ($n % 2 == 0 && $arr[$r + 1][$r] < $x) return -1; while ($l < $r) { $mid = (int)(($l + $r) / 2); if ($arr[$mid][$mid] <= $x) if ($mid == (int)(($n + 1) / 2 - 1) || $arr[$mid + 1][$mid + 1] > $x) return $mid; else $l = $mid + 1; else $r = $mid - 1; } return $r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedfunction binarySearchRowInc($arr, $row, $l, $r, $x){ while ($l <= $r) { $mid = (int)(($l + $r) / 2); if ($arr[$row][$mid] == $x) return $mid; if ($arr[$row][$mid] < $x) $l = $mid + 1; else $r = $mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsfunction binarySearchColumnInc($arr, $col, $t, $b, $x){ while ($t <= $b) { $mid = (int)(($t + b) / 2); if ($arr[$mid][$col] == $x) return $mid; if ($arr[$mid][$col] < $x) $t = $mid + 1; else $b = $mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderfunction binarySearchRowDec($arr, $row, $l, $r, $x){ while ($l <= $r) { $mid = (int)(($l + $r) / 2); if ($arr[$row][$mid] == $x) return $mid; if ($arr[$row][$mid] < $x) $r = $mid - 1; else $l = $mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arrayfunction binarySearchColumnDec($arr, $col, $t, $b, $x){ while ($t <= $b) { $mid = (int)(($t + $b) / 2); if ($arr[$mid][$col] == $x) return $mid; if ($arr[$mid][$col] < $x) $b = $mid - 1; else $t = $mid + 1; } return -1;} // Function to find the position of the number xfunction spiralBinary($arr, $x){ global $n; // Finding the ring $f1 = findRing($arr, $x); // To store row and column $r = -1; $c = -1; if ($f1 == -1) { echo "-1"; return; } // Edge case if n is odd if ($n % 2 == 1 && $f1 == (int)(($n + 1) / 2 - 1)) { echo $f1 . " " . $f1 . "\n"; return; } // Check which of the 4 sides, the number x // lies in if ($x < $arr[$f1][$n - $f1 - 1]) { $c = binarySearchRowInc($arr, $f1, $f1, $n - $f1 - 2, $x); $r = $f1; } else if ($x < $arr[$n - $f1 - 1][$n - $f1 - 1]) { $c = $n - $f1 - 1; $r = binarySearchColumnInc($arr, $n - $f1 - 1, $f1, $n - $f1 - 2, $x); } else if ($x < $arr[$n - $f1 - 1][$f1]) { $c = binarySearchRowDec($arr, $n - $f1 - 1, $f1 + 1, $n - $f1 - 1, $x); $r = $n - $f1 - 1; } else { $r = binarySearchColumnDec($arr, $f1, $f1 + 1, $n - $f1 - 1, $x); $c = $f1; } // Printing the position if ($c == -1 || $r == -1) echo "-1"; else echo $r . " " . $c; return;} // Driver code$arr = array(array( 1, 2, 3, 4 ), array( 12, 13, 14, 5 ), array( 11, 16, 15, 6 ), array( 10, 9, 8, 7 )); spiralBinary($arr, 7); // This code is contributed by mits?> <script> // Javascript implementation of the above approachvar n = 4; // Function to return the ring, the number x// belongs to.function findRing(arr, x){ // Returns -1 if number x is smaller than // least element of arr if (arr[0][0] > x) return -1; // l and r represent the diagonal // elements to search in var l = 0, r = parseInt((n + 1) / 2) - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r][r] < x) return -1; if (n % 2 == 0 && arr[r + 1][r] < x) return -1; while (l < r) { var mid = parseInt((l + r) / 2); if (arr[mid][mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1][mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedfunction binarySearchRowInc(arr, row, l, r, x){ while (l <= r) { var mid = parseInt((l + r) / 2); if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsfunction binarySearchColumnInc(arr, col, t, b, x){ while (t <= b) { var mid = parseInt((t + b) / 2); if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderfunction binarySearchRowDec(arr, row, l, r, x){ while (l <= r) { var mid = parseInt((l + r) / 2); if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arrayfunction binarySearchColumnDec(arr, col, t, b, x){ while (t <= b) { var mid = parseInt((t + b) / 2); if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xfunction spiralBinary(arr, x){ // Finding the ring var f1 = findRing(arr, x); // To store row and column var r, c; if (f1 == -1) { document.write( "-1"); return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { document.write( f1 + " " + f1 + "<br>"); return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1][n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1][n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1][f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) document.write( "-1"); else document.write( r + " " + c); return;} // Driver codevar arr = [ [ 1, 2, 3, 4 ], [ 12, 13, 14, 5 ], [ 11, 16, 15, 6 ], [ 10, 9, 8, 7 ] ];spiralBinary(arr, 7); </script> 3 3 Time Complexity: O(logN)Auxiliary Space: O(logN) 29AjayKumar andrew1234 rituraj_jain Mithun Kumar nidhi_biet itsok singghakshay pankajsharmagfg Binary Search Algorithms Arrays Divide and Conquer Matrix Searching Arrays Searching Divide and Conquer Matrix Binary Search 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 CPU Scheduling in Operating Systems Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Arrays in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2021" }, { "code": null, "e": 267, "s": 52, "text": "Given a spirally sorted matrix with N × N elements and an integer X, the task is to find the position of this given integer in the matrix if it exists, else print -1. Note that all the matrix elements are distinct." }, { "code": null, "e": 279, "s": 267, "text": "Examples: " }, { "code": null, "e": 467, "s": 279, "text": "Input: arr[] = { {1, 2, 3, 4}, {12, 13, 14, 5}, {11, 16, 15, 6}, {10, 9, 8, 7}}, X = 9 Output: 3 1 9 appears in row number 3 and column number 1 (0-based indexing) Thus, output is (3, 1)." }, { "code": null, "e": 538, "s": 467, "text": "Input: arr[] = { {1, 2, 3}, {8, 9, 4}, {7, 6, 5}}, X = 9 Output: 1 1 " }, { "code": null, "e": 671, "s": 538, "text": "A simple solution is to search through all the elements in the array. The worst-case time complexity of this approach will be O(n2)." }, { "code": null, "e": 1636, "s": 671, "text": "A better solution is to use binary search. We apply binary search in two phases. But before jumping to that, let’s define what a ring means here. A ring is defined as a set of all the cells in the array such that their minimum of the distances from all four sides is equal. First, we try to determine the ring the number ‘X’ will belong to. We will do this using binary search. For that, observe the diagonal elements of the matrix. The first ceil(N/2) of the diagonal matrix is guaranteed to be sorted in increasing order. So, each one of the ceil(N/2) diagonal elements can represent a ring. By, applying binary on the first ceil(N/2) diagonal elements, we determine the ring the number ‘X’ belongs to in O(log(n)) time. After that, we apply a binary search on the elements of the ring. Before that we determine the side of the ring, the number ‘X’ will belong to. Then, we apply the binary search correspondingly.So, the total time complexity becomes O(log(n))." }, { "code": null, "e": 1688, "s": 1636, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1692, "s": 1688, "text": "C++" }, { "code": null, "e": 1697, "s": 1692, "text": "Java" }, { "code": null, "e": 1705, "s": 1697, "text": "Python3" }, { "code": null, "e": 1708, "s": 1705, "text": "C#" }, { "code": null, "e": 1712, "s": 1708, "text": "PHP" }, { "code": null, "e": 1723, "s": 1712, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include <iostream>#define n 4using namespace std; // Function to return the ring, the number x// belongs to.int findRing(int arr[][n], int x){ // Returns -1 if number x is smaller than // least element of arr if (arr[0][0] > x) return -1; // l and r represent the diagonal // elements to search in int l = 0, r = (n + 1) / 2 - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r][r] < x) return -1; if (n % 2 == 0 && arr[r + 1][r] < x) return -1; while (l < r) { int mid = (l + r) / 2; if (arr[mid][mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1][mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedint binarySearchRowInc(int arr[][n], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsint binarySearchColumnInc(int arr[][n], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderint binarySearchRowDec(int arr[][n], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arrayint binarySearchColumnDec(int arr[][n], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xvoid spiralBinary(int arr[][n], int x){ // Finding the ring int f1 = findRing(arr, x); // To store row and column int r, c; if (f1 == -1) { cout << \"-1\"; return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { cout << f1 << \" \" << f1 << endl; return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1][n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1][n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1][f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) cout << \"-1\"; else cout << r << \" \" << c; return;} // Driver codeint main(){ int arr[][n] = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; spiralBinary(arr, 7); return 0;}", "e": 5789, "s": 1723, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ final static int n =4; // Function to return the ring,// the number x belongs to.static int findRing(int arr[][], int x){ // Returns -1 if number x is // smaller than least element of arr if (arr[0][0] > x) return -1; // l and r represent the diagonal // elements to search in int l = 0, r = (n + 1) / 2 - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r][r] < x) return -1; if (n % 2 == 0 && arr[r + 1][r] < x) return -1; while (l < r) { int mid = (l + r) / 2; if (arr[mid][mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1][mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedstatic int binarySearchRowInc(int arr[][], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsstatic int binarySearchColumnInc(int arr[][], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderstatic int binarySearchRowDec(int arr[][], int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arraystatic int binarySearchColumnDec(int arr[][], int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xstatic void spiralBinary(int arr[][], int x){ // Finding the ring int f1 = findRing(arr, x); // To store row and column int r, c; if (f1 == -1) { System.out.print(\"-1\"); return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { System.out.println(f1+\" \"+f1); return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1][n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1][n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1][f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) System.out.print(\"-1\"); else System.out.print(r+\" \"+c); return;} // Driver codepublic static void main(String[] args){ int arr[][] = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; spiralBinary(arr, 7);}} // This code is contributed by 29AjayKumar", "e": 9948, "s": 5789, "text": null }, { "code": "# Python3 implementation of the above approach # Function to return the ring,# the number x belongs to.def findRing(arr, x): # Returns -1 if number x is smaller # than least element of arr if arr[0][0] > x: return -1 # l and r represent the diagonal # elements to search in l, r = 0, (n + 1) // 2 - 1 # Returns -1 if number x is greater # than the largest element of arr if n % 2 == 1 and arr[r][r] < x: return -1 if n % 2 == 0 and arr[r + 1][r] < x: return -1 while l < r: mid = (l + r) // 2 if arr[mid][mid] <= x: if (mid == (n + 1) // 2 - 1 or arr[mid + 1][mid + 1] > x): return mid else: l = mid + 1 else: r = mid - 1 return r # Function to perform binary search# on an array sorted in increasing order# l and r represent the left and right# index of the row to be searcheddef binarySearchRowInc(arr, row, l, r, x): while l <= r: mid = (l + r) // 2 if arr[row][mid] == x: return mid elif arr[row][mid] < x: l = mid + 1 else: r = mid - 1 return -1 # Function to perform binary search on# a particular column of the 2D array# t and b represent top and# bottom rowsdef binarySearchColumnInc(arr, col, t, b, x): while t <= b: mid = (t + b) // 2 if arr[mid][col] == x: return mid elif arr[mid][col] < x: t = mid + 1 else: b = mid - 1 return -1 # Function to perform binary search on# an array sorted in decreasing orderdef binarySearchRowDec(arr, row, l, r, x): while l <= r: mid = (l + r) // 2 if arr[row][mid] == x: return mid elif arr[row][mid] < x: r = mid - 1 else: l = mid + 1 return -1 # Function to perform binary search on a# particular column of the 2D arraydef binarySearchColumnDec(arr, col, t, b, x): while t <= b: mid = (t + b) // 2 if arr[mid][col] == x: return mid elif arr[mid][col] < x: b = mid - 1 else: t = mid + 1 return -1 # Function to find the position of the number xdef spiralBinary(arr, x): # Finding the ring f1 = findRing(arr, x) # To store row and column r, c = None, None if f1 == -1: print(\"-1\") return # Edge case if n is odd if n % 2 == 1 and f1 == (n + 1) // 2 - 1: print(f1, f1) return # Check which of the 4 sides, # the number x lies in if x < arr[f1][n - f1 - 1]: c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x) r = f1 elif x < arr[n - f1 - 1][n - f1 - 1]: c = n - f1 - 1 r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x) elif x < arr[n - f1 - 1][f1]: c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x) r = n - f1 - 1 else: r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x) c = f1 # Printing the position if c == -1 or r == -1: print(\"-1\") else: print(\"{0} {1}\".format(r, c)) # Driver codeif __name__ == \"__main__\": n = 4 arr = [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]] spiralBinary(arr, 7) # This code is contributed by Rituraj Jain", "e": 13560, "s": 9948, "text": null }, { "code": "// C# implementation of the above approachusing System;class GFG{ static int n =4; // Function to return the ring,// the number x belongs to.static int findRing(int [,]arr, int x){ // Returns -1 if number x is // smaller than least element of arr if (arr[0,0] > x) return -1; // l and r represent the diagonal // elements to search in int l = 0, r = (n + 1) / 2 - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r,r] < x) return -1; if (n % 2 == 0 && arr[r + 1,r] < x) return -1; while (l < r) { int mid = (l + r) / 2; if (arr[mid,mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1,mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedstatic int binarySearchRowInc(int [,]arr, int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row,mid] == x) return mid; if (arr[row,mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsstatic int binarySearchColumnInc(int [,]arr, int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid,col] == x) return mid; if (arr[mid,col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderstatic int binarySearchRowDec(int [,]arr, int row, int l, int r, int x){ while (l <= r) { int mid = (l + r) / 2; if (arr[row,mid] == x) return mid; if (arr[row,mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arraystatic int binarySearchColumnDec(int [,]arr, int col, int t, int b, int x){ while (t <= b) { int mid = (t + b) / 2; if (arr[mid,col] == x) return mid; if (arr[mid,col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xstatic void spiralBinary(int [,]arr, int x){ // Finding the ring int f1 = findRing(arr, x); // To store row and column int r, c; if (f1 == -1) { Console.Write(\"-1\"); return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { Console.WriteLine(f1+\" \"+f1); return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1,n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1,n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1,f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) Console.Write(\"-1\"); else Console.Write(r+\" \"+c); return;} // Driver codepublic static void Main(String []args){ int [,]arr = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; spiralBinary(arr, 7);}} // This code is contributed by Arnab Kundu", "e": 17691, "s": 13560, "text": null }, { "code": "<?php// PHP implementation of the above approach$n = 4; // Function to return the ring, the number x// belongs to.function findRing($arr, $x){ global $n; // Returns -1 if number x is smaller than // least element of arr if ($arr[0][0] > $x) return -1; // l and r represent the diagonal // elements to search in $l = 0; $r = (int)(($n + 1) / 2 - 1); // Returns -1 if number x is greater // than the largest element of arr if ($n % 2 == 1 && $arr[$r][$r] < $x) return -1; if ($n % 2 == 0 && $arr[$r + 1][$r] < $x) return -1; while ($l < $r) { $mid = (int)(($l + $r) / 2); if ($arr[$mid][$mid] <= $x) if ($mid == (int)(($n + 1) / 2 - 1) || $arr[$mid + 1][$mid + 1] > $x) return $mid; else $l = $mid + 1; else $r = $mid - 1; } return $r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedfunction binarySearchRowInc($arr, $row, $l, $r, $x){ while ($l <= $r) { $mid = (int)(($l + $r) / 2); if ($arr[$row][$mid] == $x) return $mid; if ($arr[$row][$mid] < $x) $l = $mid + 1; else $r = $mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsfunction binarySearchColumnInc($arr, $col, $t, $b, $x){ while ($t <= $b) { $mid = (int)(($t + b) / 2); if ($arr[$mid][$col] == $x) return $mid; if ($arr[$mid][$col] < $x) $t = $mid + 1; else $b = $mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderfunction binarySearchRowDec($arr, $row, $l, $r, $x){ while ($l <= $r) { $mid = (int)(($l + $r) / 2); if ($arr[$row][$mid] == $x) return $mid; if ($arr[$row][$mid] < $x) $r = $mid - 1; else $l = $mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arrayfunction binarySearchColumnDec($arr, $col, $t, $b, $x){ while ($t <= $b) { $mid = (int)(($t + $b) / 2); if ($arr[$mid][$col] == $x) return $mid; if ($arr[$mid][$col] < $x) $b = $mid - 1; else $t = $mid + 1; } return -1;} // Function to find the position of the number xfunction spiralBinary($arr, $x){ global $n; // Finding the ring $f1 = findRing($arr, $x); // To store row and column $r = -1; $c = -1; if ($f1 == -1) { echo \"-1\"; return; } // Edge case if n is odd if ($n % 2 == 1 && $f1 == (int)(($n + 1) / 2 - 1)) { echo $f1 . \" \" . $f1 . \"\\n\"; return; } // Check which of the 4 sides, the number x // lies in if ($x < $arr[$f1][$n - $f1 - 1]) { $c = binarySearchRowInc($arr, $f1, $f1, $n - $f1 - 2, $x); $r = $f1; } else if ($x < $arr[$n - $f1 - 1][$n - $f1 - 1]) { $c = $n - $f1 - 1; $r = binarySearchColumnInc($arr, $n - $f1 - 1, $f1, $n - $f1 - 2, $x); } else if ($x < $arr[$n - $f1 - 1][$f1]) { $c = binarySearchRowDec($arr, $n - $f1 - 1, $f1 + 1, $n - $f1 - 1, $x); $r = $n - $f1 - 1; } else { $r = binarySearchColumnDec($arr, $f1, $f1 + 1, $n - $f1 - 1, $x); $c = $f1; } // Printing the position if ($c == -1 || $r == -1) echo \"-1\"; else echo $r . \" \" . $c; return;} // Driver code$arr = array(array( 1, 2, 3, 4 ), array( 12, 13, 14, 5 ), array( 11, 16, 15, 6 ), array( 10, 9, 8, 7 )); spiralBinary($arr, 7); // This code is contributed by mits?>", "e": 21921, "s": 17691, "text": null }, { "code": "<script> // Javascript implementation of the above approachvar n = 4; // Function to return the ring, the number x// belongs to.function findRing(arr, x){ // Returns -1 if number x is smaller than // least element of arr if (arr[0][0] > x) return -1; // l and r represent the diagonal // elements to search in var l = 0, r = parseInt((n + 1) / 2) - 1; // Returns -1 if number x is greater // than the largest element of arr if (n % 2 == 1 && arr[r][r] < x) return -1; if (n % 2 == 0 && arr[r + 1][r] < x) return -1; while (l < r) { var mid = parseInt((l + r) / 2); if (arr[mid][mid] <= x) if (mid == (n + 1) / 2 - 1 || arr[mid + 1][mid + 1] > x) return mid; else l = mid + 1; else r = mid - 1; } return r;} // Function to perform binary search// on an array sorted in increasing order// l and r represent the left and right// index of the row to be searchedfunction binarySearchRowInc(arr, row, l, r, x){ while (l <= r) { var mid = parseInt((l + r) / 2); if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) l = mid + 1; else r = mid - 1; } return -1;} // Function to perform binary search on// a particular column of the 2D array// t and b represent top and// bottom rowsfunction binarySearchColumnInc(arr, col, t, b, x){ while (t <= b) { var mid = parseInt((t + b) / 2); if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) t = mid + 1; else b = mid - 1; } return -1;} // Function to perform binary search on// an array sorted in decreasing orderfunction binarySearchRowDec(arr, row, l, r, x){ while (l <= r) { var mid = parseInt((l + r) / 2); if (arr[row][mid] == x) return mid; if (arr[row][mid] < x) r = mid - 1; else l = mid + 1; } return -1;} // Function to perform binary search on a// particular column of the 2D arrayfunction binarySearchColumnDec(arr, col, t, b, x){ while (t <= b) { var mid = parseInt((t + b) / 2); if (arr[mid][col] == x) return mid; if (arr[mid][col] < x) b = mid - 1; else t = mid + 1; } return -1;} // Function to find the position of the number xfunction spiralBinary(arr, x){ // Finding the ring var f1 = findRing(arr, x); // To store row and column var r, c; if (f1 == -1) { document.write( \"-1\"); return; } // Edge case if n is odd if (n % 2 == 1 && f1 == (n + 1) / 2 - 1) { document.write( f1 + \" \" + f1 + \"<br>\"); return; } // Check which of the 4 sides, the number x // lies in if (x < arr[f1][n - f1 - 1]) { c = binarySearchRowInc(arr, f1, f1, n - f1 - 2, x); r = f1; } else if (x < arr[n - f1 - 1][n - f1 - 1]) { c = n - f1 - 1; r = binarySearchColumnInc(arr, n - f1 - 1, f1, n - f1 - 2, x); } else if (x < arr[n - f1 - 1][f1]) { c = binarySearchRowDec(arr, n - f1 - 1, f1 + 1, n - f1 - 1, x); r = n - f1 - 1; } else { r = binarySearchColumnDec(arr, f1, f1 + 1, n - f1 - 1, x); c = f1; } // Printing the position if (c == -1 || r == -1) document.write( \"-1\"); else document.write( r + \" \" + c); return;} // Driver codevar arr = [ [ 1, 2, 3, 4 ], [ 12, 13, 14, 5 ], [ 11, 16, 15, 6 ], [ 10, 9, 8, 7 ] ];spiralBinary(arr, 7); </script>", "e": 25832, "s": 21921, "text": null }, { "code": null, "e": 25836, "s": 25832, "text": "3 3" }, { "code": null, "e": 25887, "s": 25838, "text": "Time Complexity: O(logN)Auxiliary Space: O(logN)" }, { "code": null, "e": 25899, "s": 25887, "text": "29AjayKumar" }, { "code": null, "e": 25910, "s": 25899, "text": "andrew1234" }, { "code": null, "e": 25923, "s": 25910, "text": "rituraj_jain" }, { "code": null, "e": 25936, "s": 25923, "text": "Mithun Kumar" }, { "code": null, "e": 25947, "s": 25936, "text": "nidhi_biet" }, { "code": null, "e": 25953, "s": 25947, "text": "itsok" }, { "code": null, "e": 25966, "s": 25953, "text": "singghakshay" }, { "code": null, "e": 25982, "s": 25966, "text": "pankajsharmagfg" }, { "code": null, "e": 25996, "s": 25982, "text": "Binary Search" }, { "code": null, "e": 26007, "s": 25996, "text": "Algorithms" }, { "code": null, "e": 26014, "s": 26007, "text": "Arrays" }, { "code": null, "e": 26033, "s": 26014, "text": "Divide and Conquer" }, { "code": null, "e": 26040, "s": 26033, "text": "Matrix" }, { "code": null, "e": 26050, "s": 26040, "text": "Searching" }, { "code": null, "e": 26057, "s": 26050, "text": "Arrays" }, { "code": null, "e": 26067, "s": 26057, "text": "Searching" }, { "code": null, "e": 26086, "s": 26067, "text": "Divide and Conquer" }, { "code": null, "e": 26093, "s": 26086, "text": "Matrix" }, { "code": null, "e": 26107, "s": 26093, "text": "Binary Search" }, { "code": null, "e": 26118, "s": 26107, "text": "Algorithms" }, { "code": null, "e": 26216, "s": 26118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26241, "s": 26216, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 26290, "s": 26241, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 26328, "s": 26290, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 26379, "s": 26328, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 26415, "s": 26379, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 26430, "s": 26415, "text": "Arrays in Java" }, { "code": null, "e": 26476, "s": 26430, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 26544, "s": 26476, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 26576, "s": 26544, "text": "Largest Sum Contiguous Subarray" } ]
Output of C programs | Set 51
24 May, 2019 1. What will be the output of the below program? #include <stdio.h>int main(){ printf("%d", printf("%d", printf("%d", printf("%s", "Welcome to geeksforgeeks")))); return (0);} Options:1. Welcome to geeksforgeeks25312. Welcome to geeksforgeeks24213. Welcome to geeksforgeeks21244. Welcome to geeksforgeeks3125 The answer is option(2). Explanation : As we all know that the printf function returns the numbers of character that is going to print and scanf function returns the number of input given. 2. What will be the output of the following program? #include <stdio.h>int main(){ int x = 30, y = 25, z = 20, w = 10; printf("%d ", x * y / z - w); printf("%d", x * y / (z - w)); return (0);} Options:1. 27 852. 82 273. 27 754. No output The output is option(3). Explanation : In the above program, precedence takes the advantage. Therefore In the statement compiler first calculate x*y then / and after that subtraction.Refer : https://www.geeksforgeeks.org/c-operator-precedence-associativity/ 3. Guess the output? #include <stdio.h>int main(){ int a = 15, b; b = (a++) + (a++); a = (b++) + (b++); printf("a=%d b=%d", a, b); return (0);} Options:1. a=63 b=332. a=33 b=633. a=66 b=334. a=33 b=33 The answer is option(1). Explanation:Here, a = 15 and b = (a++)+(a++) i.e. b = 15+16 = 31 and a =3 2. Now a = (b++) + (b++) = 31 + 32 = 63 and b = 33. Therefore the result is a = 63 and b = 33. Refer: https://www.geeksforgeeks.org/operators-in-c-set-1-arithmetic-operators/ 4. What will be the output? #include <stdio.h>int main(){ main(); return (0);} Options:1. compile time error2. abnormal termination3. run time error4. No output The answer is option(1). Explanation:Here stack overflow occurs that’s result in run-time error.Refer: https://www.geeksforgeeks.org/print-geeksforgeeks-empty-main-c/ 5. What will be the output of following program? #include <stdio.h>int main(){ int c = 4; c = c++ + ~++c; printf("%d", c); return (0);} Options:1. 32. -33. 314. compile time error The answer is option(2). Explanation:Because here c++ is post increment and so it takes value as 4 then it will increment. ++c is pre-increment so it increment first and value 6 is assigned to c, .~ means -6-1=-7 then c=(4-7)=-3. This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ManasChhabra2 C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2019" }, { "code": null, "e": 103, "s": 54, "text": "1. What will be the output of the below program?" }, { "code": "#include <stdio.h>int main(){ printf(\"%d\", printf(\"%d\", printf(\"%d\", printf(\"%s\", \"Welcome to geeksforgeeks\")))); return (0);}", "e": 236, "s": 103, "text": null }, { "code": null, "e": 369, "s": 236, "text": "Options:1. Welcome to geeksforgeeks25312. Welcome to geeksforgeeks24213. Welcome to geeksforgeeks21244. Welcome to geeksforgeeks3125" }, { "code": null, "e": 394, "s": 369, "text": "The answer is option(2)." }, { "code": null, "e": 558, "s": 394, "text": "Explanation : As we all know that the printf function returns the numbers of character that is going to print and scanf function returns the number of input given." }, { "code": null, "e": 611, "s": 558, "text": "2. What will be the output of the following program?" }, { "code": "#include <stdio.h>int main(){ int x = 30, y = 25, z = 20, w = 10; printf(\"%d \", x * y / z - w); printf(\"%d\", x * y / (z - w)); return (0);}", "e": 763, "s": 611, "text": null }, { "code": null, "e": 808, "s": 763, "text": "Options:1. 27 852. 82 273. 27 754. No output" }, { "code": null, "e": 834, "s": 808, "text": " The output is option(3)." }, { "code": null, "e": 1067, "s": 834, "text": "Explanation : In the above program, precedence takes the advantage. Therefore In the statement compiler first calculate x*y then / and after that subtraction.Refer : https://www.geeksforgeeks.org/c-operator-precedence-associativity/" }, { "code": null, "e": 1088, "s": 1067, "text": "3. Guess the output?" }, { "code": "#include <stdio.h>int main(){ int a = 15, b; b = (a++) + (a++); a = (b++) + (b++); printf(\"a=%d b=%d\", a, b); return (0);}", "e": 1226, "s": 1088, "text": null }, { "code": null, "e": 1283, "s": 1226, "text": "Options:1. a=63 b=332. a=33 b=633. a=66 b=334. a=33 b=33" }, { "code": null, "e": 1308, "s": 1283, "text": "The answer is option(1)." }, { "code": null, "e": 1326, "s": 1308, "text": "Explanation:Here," }, { "code": null, "e": 1477, "s": 1326, "text": "a = 15 and b = (a++)+(a++) i.e. b = 15+16 = 31 and a =3 2.\nNow a = (b++) + (b++) = 31 + 32 = 63 and b = 33.\nTherefore the result is a = 63 and b = 33." }, { "code": null, "e": 1557, "s": 1477, "text": "Refer: https://www.geeksforgeeks.org/operators-in-c-set-1-arithmetic-operators/" }, { "code": null, "e": 1585, "s": 1557, "text": "4. What will be the output?" }, { "code": "#include <stdio.h>int main(){ main(); return (0);}", "e": 1642, "s": 1585, "text": null }, { "code": null, "e": 1724, "s": 1642, "text": "Options:1. compile time error2. abnormal termination3. run time error4. No output" }, { "code": null, "e": 1749, "s": 1724, "text": "The answer is option(1)." }, { "code": null, "e": 1891, "s": 1749, "text": "Explanation:Here stack overflow occurs that’s result in run-time error.Refer: https://www.geeksforgeeks.org/print-geeksforgeeks-empty-main-c/" }, { "code": null, "e": 1940, "s": 1891, "text": "5. What will be the output of following program?" }, { "code": "#include <stdio.h>int main(){ int c = 4; c = c++ + ~++c; printf(\"%d\", c); return (0);}", "e": 2039, "s": 1940, "text": null }, { "code": null, "e": 2083, "s": 2039, "text": "Options:1. 32. -33. 314. compile time error" }, { "code": null, "e": 2109, "s": 2083, "text": " The answer is option(2)." }, { "code": null, "e": 2314, "s": 2109, "text": "Explanation:Because here c++ is post increment and so it takes value as 4 then it will increment. ++c is pre-increment so it increment first and value 6 is assigned to c, .~ means -6-1=-7 then c=(4-7)=-3." }, { "code": null, "e": 2620, "s": 2314, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2745, "s": 2620, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2759, "s": 2745, "text": "ManasChhabra2" }, { "code": null, "e": 2768, "s": 2759, "text": "C-Output" }, { "code": null, "e": 2783, "s": 2768, "text": "Program Output" } ]
Find number of times every day occurs in a Year
12 Jul, 2021 Given a year .Your task is to find the number of every day in a year ie.number of Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday in that given year.Examples: Input: 2019 Output: Monday-52 Tuesday-53 Wednesday-52 Thursday-52 Friday-52 Saturday-52 Sunday-52 Input: 2024 Output: Monday-53 Tuesday-53 Wednesday-52 Thursday-52 Friday-52 Saturday-52 Sunday-52 Observations: We have to make some key observations. The first one will be that there are at least 52 weeks in a year, so every day will occur at least 52 times in a year. As 52*7 is 364 so the day occurring on the 1st January of any year will occur 53 times and if the year is a leap year then the day on the 2nd January will also occur 53 times.Approach: Create a list with size 7 and having an initial value of 52 as the minimum number of occurrences will be 52. Find the index of the first day. Calculate the number of days whose occurrence will be 53.Below is the implementation. Python3 # python program Find number of# times every day occurs in a Year import datetimeimport calendar def day_occur_time(year): # stores days in a week days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] # Initialize all counts as 52 L = [52 for i in range(7)] # Find the index of the first day # of the year pos = -1 day = datetime.datetime(year, month = 1, day = 1).strftime("%A") for i in range(7): if day == days[i]: pos = i # mark the occurrence to be 53 of 1st day # and 2nd day if the year is leap year if calendar.isleap(year): L[pos] += 1 L[(pos+1)%7] += 1 else: L[pos] += 1 # Print the days for i in range(7): print(days[i], L[i]) # Driver Codeyear = 2019day_occur_time(year) Output: Monday 52 Tuesday 52 Wednesday 52 Thursday 52 Friday 53 Saturday 53 Sunday 52 sweetyty Python datetime-program Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jul, 2021" }, { "code": null, "e": 230, "s": 54, "text": "Given a year .Your task is to find the number of every day in a year ie.number of Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday in that given year.Examples: " }, { "code": null, "e": 523, "s": 230, "text": "Input: 2019\nOutput: Monday-52\n Tuesday-53\n Wednesday-52\n Thursday-52\n Friday-52\n Saturday-52\n Sunday-52\n\nInput: 2024\nOutput: Monday-53\n Tuesday-53\n Wednesday-52\n Thursday-52\n Friday-52\n Saturday-52\n Sunday-52" }, { "code": null, "e": 1109, "s": 523, "text": "Observations: We have to make some key observations. The first one will be that there are at least 52 weeks in a year, so every day will occur at least 52 times in a year. As 52*7 is 364 so the day occurring on the 1st January of any year will occur 53 times and if the year is a leap year then the day on the 2nd January will also occur 53 times.Approach: Create a list with size 7 and having an initial value of 52 as the minimum number of occurrences will be 52. Find the index of the first day. Calculate the number of days whose occurrence will be 53.Below is the implementation. " }, { "code": null, "e": 1117, "s": 1109, "text": "Python3" }, { "code": "# python program Find number of# times every day occurs in a Year import datetimeimport calendar def day_occur_time(year): # stores days in a week days = [ \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\" ] # Initialize all counts as 52 L = [52 for i in range(7)] # Find the index of the first day # of the year pos = -1 day = datetime.datetime(year, month = 1, day = 1).strftime(\"%A\") for i in range(7): if day == days[i]: pos = i # mark the occurrence to be 53 of 1st day # and 2nd day if the year is leap year if calendar.isleap(year): L[pos] += 1 L[(pos+1)%7] += 1 else: L[pos] += 1 # Print the days for i in range(7): print(days[i], L[i]) # Driver Codeyear = 2019day_occur_time(year)", "e": 2008, "s": 1117, "text": null }, { "code": null, "e": 2017, "s": 2008, "text": "Output: " }, { "code": null, "e": 2095, "s": 2017, "text": "Monday 52\nTuesday 52\nWednesday 52\nThursday 52\nFriday 53\nSaturday 53\nSunday 52" }, { "code": null, "e": 2106, "s": 2097, "text": "sweetyty" }, { "code": null, "e": 2130, "s": 2106, "text": "Python datetime-program" }, { "code": null, "e": 2146, "s": 2130, "text": "Python-datetime" }, { "code": null, "e": 2153, "s": 2146, "text": "Python" } ]
std::find_first_of in C++
04 Oct, 2017 std::find_first_of is used to compare elements between two containers. It compares all the elements in a range [first1,last1) with the elements in the range [first2,last2), and if any of the elements present in the second range is found in the first one , then it returns an iterator to that element. If there are more than one element common in both the ranges, then an iterator to the first common element present in the first container is returned. In case there is no match, then iterator pointing to last1 is returned. It can be used in two ways as shown below: Comparing elements using ==:Syntax:Template ForwardIterator1 find_first_of(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); first1: Forward iterator to the first element in the first range. last1: Forward iterator to the last element in the first range. first2: Forward iterator to the first element in the second range. last2: Forward iterator to the last element in the second range. Return Value: It returns an iterator to the first element in [first1,last1) that is part of [first2,last2). If no matches are found or [first2, last2) is empty, the function returns last1. // C++ program to demonstrate // the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){ // Defining first container vector<int>v = {1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8} , i; // Defining second container vector<int>v1 = {1, 3, 10}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end()); // Displaying the first common element found cout << *ip << "\n"; // Finding the second common element ip = std::find_first_of(ip + 1, v.end(), v1.begin(), v1.end()); // Displaying the second common element found cout << *ip << "\n"; return 0;}Output:1 3 Here, in both the vectors, the first common element is 1 and to find the second common element, we have passed the beginning of the first range as the element next to the first common element already found.By comparing using a pre-defined function:Syntax:Template ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); Here, first1, last1, first2 and last2 are the same as previous case. Pred: Binary function that accepts two elements as arguments (one of each of the two sequences, in the same order), and returns a value convertible to bool. The value returned indicates whether the elements are considered to match in the context of this function. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: It returns an iterator to the first element in [first1,last1) that is part of [first2,last2). If no matches are found or [first2,last2) is empty, the function returns last1.// C++ program to demonstrate// the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the BinaryFunctionbool Pred (int a, int b){ if ( a % b == 0) { return 1; } else { return 0; }}int main(){ // Defining first container vector<int>v = {1, 5, 7, 11, 13, 15, 30, 30, 7} , i; // Defining second container vector<int>v1 = {2, 3, 4}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end(), Pred); // Displaying the first element satisfying Pred() cout << *ip << "\n"; return 0;}Output:15 Here, we have manipulated the binary function in such a way that we are trying to find the first number in the first container which is a multiple of any of the number in the second container. And in this case, 15 comes out to be the first one, as it is divisible by 3. Comparing elements using ==:Syntax:Template ForwardIterator1 find_first_of(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); first1: Forward iterator to the first element in the first range. last1: Forward iterator to the last element in the first range. first2: Forward iterator to the first element in the second range. last2: Forward iterator to the last element in the second range. Return Value: It returns an iterator to the first element in [first1,last1) that is part of [first2,last2). If no matches are found or [first2, last2) is empty, the function returns last1. // C++ program to demonstrate // the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){ // Defining first container vector<int>v = {1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8} , i; // Defining second container vector<int>v1 = {1, 3, 10}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end()); // Displaying the first common element found cout << *ip << "\n"; // Finding the second common element ip = std::find_first_of(ip + 1, v.end(), v1.begin(), v1.end()); // Displaying the second common element found cout << *ip << "\n"; return 0;}Output:1 3 Here, in both the vectors, the first common element is 1 and to find the second common element, we have passed the beginning of the first range as the element next to the first common element already found. Syntax: Template ForwardIterator1 find_first_of(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); first1: Forward iterator to the first element in the first range. last1: Forward iterator to the last element in the first range. first2: Forward iterator to the first element in the second range. last2: Forward iterator to the last element in the second range. Return Value: It returns an iterator to the first element in [first1,last1) that is part of [first2,last2). If no matches are found or [first2, last2) is empty, the function returns last1. // C++ program to demonstrate // the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){ // Defining first container vector<int>v = {1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8} , i; // Defining second container vector<int>v1 = {1, 3, 10}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end()); // Displaying the first common element found cout << *ip << "\n"; // Finding the second common element ip = std::find_first_of(ip + 1, v.end(), v1.begin(), v1.end()); // Displaying the second common element found cout << *ip << "\n"; return 0;} Output: 1 3 Here, in both the vectors, the first common element is 1 and to find the second common element, we have passed the beginning of the first range as the element next to the first common element already found. By comparing using a pre-defined function:Syntax:Template ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); Here, first1, last1, first2 and last2 are the same as previous case. Pred: Binary function that accepts two elements as arguments (one of each of the two sequences, in the same order), and returns a value convertible to bool. The value returned indicates whether the elements are considered to match in the context of this function. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: It returns an iterator to the first element in [first1,last1) that is part of [first2,last2). If no matches are found or [first2,last2) is empty, the function returns last1.// C++ program to demonstrate// the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the BinaryFunctionbool Pred (int a, int b){ if ( a % b == 0) { return 1; } else { return 0; }}int main(){ // Defining first container vector<int>v = {1, 5, 7, 11, 13, 15, 30, 30, 7} , i; // Defining second container vector<int>v1 = {2, 3, 4}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end(), Pred); // Displaying the first element satisfying Pred() cout << *ip << "\n"; return 0;}Output:15 Here, we have manipulated the binary function in such a way that we are trying to find the first number in the first container which is a multiple of any of the number in the second container. And in this case, 15 comes out to be the first one, as it is divisible by 3. Syntax: Template ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); Here, first1, last1, first2 and last2 are the same as previous case. Pred: Binary function that accepts two elements as arguments (one of each of the two sequences, in the same order), and returns a value convertible to bool. The value returned indicates whether the elements are considered to match in the context of this function. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: It returns an iterator to the first element in [first1,last1) that is part of [first2,last2). If no matches are found or [first2,last2) is empty, the function returns last1. // C++ program to demonstrate// the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the BinaryFunctionbool Pred (int a, int b){ if ( a % b == 0) { return 1; } else { return 0; }}int main(){ // Defining first container vector<int>v = {1, 5, 7, 11, 13, 15, 30, 30, 7} , i; // Defining second container vector<int>v1 = {2, 3, 4}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end(), Pred); // Displaying the first element satisfying Pred() cout << *ip << "\n"; return 0;} Output: 15 Here, we have manipulated the binary function in such a way that we are trying to find the first number in the first container which is a multiple of any of the number in the second container. And in this case, 15 comes out to be the first one, as it is divisible by 3. Possible Application: std::find_first_of can be used to find the first occurrence of any of the elements present in another container. One possible application of this is to find the first vowel in a sentence.// C++ program to demonstrate the use of std::find_first_of#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;int main(){ // Defining first container string s1 = "You are reading about std::find_first_of"; // Defining second container containing list of vowels string s2 = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}; // Using std::find_first_of to find first occurrence of // a vowel auto ip = std::find_first_of(s1.begin(),s1.end(), s2.begin(), s2.end()); // Displaying the first vowel found cout << "First vowel found at index "<< (ip - s1.begin()) << "\n"; return 0;}Output:First vowel found at index 1 Explanation: std::find_first_of searches for the first occurrence of any of the elements from the second container in the first one, and in this way , first vowel present in the sentence was found out.It can also be used to find the first odd and even numbers present in list.// C++ program to find the first occurrence of an odd// and even number#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the Predicate Function to find first occurrence// of an odd numberbool pred( int a, int b){ if (a % b != 0) { return 1; } else { return 0; }} // Defining the Predicate Function to find first occurrence// of an even numberbool pred1( int a, int b){ if (a % b == 0) { return 1; } else { return 0; }} int main(){ // Defining a vector vector<int>v1 = {1, 3, 4, 5, 6, 7, 8, 10}; // Declaring a sub-sequence vector<int>v2 = {2}; // Using std::find_first_of to find the first // occurrence of an odd number vector<int>::iterator ip; ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred); // Displaying the index where the first odd number // occurred cout << "First odd no. occurs at index " << (ip - v1.begin()); // Using std::find_first_of to find the last occurrence // of an even number ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred1); // Displaying the index where the first even number // occurred cout << "\nFirst even no. occurs at index " << (ip - v1.begin()); return 0;}Output:First odd no. occurs at index 0 First even no. occurs at index 2 Explanation: Here, we have stored 2 in one container and with the help of predicate function, we are looking for the first number in the first container which is not divisible by 2 (for odd number) and which is divisible by 2 (for even number). One possible application of this is to find the first vowel in a sentence.// C++ program to demonstrate the use of std::find_first_of#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;int main(){ // Defining first container string s1 = "You are reading about std::find_first_of"; // Defining second container containing list of vowels string s2 = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}; // Using std::find_first_of to find first occurrence of // a vowel auto ip = std::find_first_of(s1.begin(),s1.end(), s2.begin(), s2.end()); // Displaying the first vowel found cout << "First vowel found at index "<< (ip - s1.begin()) << "\n"; return 0;}Output:First vowel found at index 1 Explanation: std::find_first_of searches for the first occurrence of any of the elements from the second container in the first one, and in this way , first vowel present in the sentence was found out. // C++ program to demonstrate the use of std::find_first_of#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;int main(){ // Defining first container string s1 = "You are reading about std::find_first_of"; // Defining second container containing list of vowels string s2 = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}; // Using std::find_first_of to find first occurrence of // a vowel auto ip = std::find_first_of(s1.begin(),s1.end(), s2.begin(), s2.end()); // Displaying the first vowel found cout << "First vowel found at index "<< (ip - s1.begin()) << "\n"; return 0;} Output: First vowel found at index 1 Explanation: std::find_first_of searches for the first occurrence of any of the elements from the second container in the first one, and in this way , first vowel present in the sentence was found out. It can also be used to find the first odd and even numbers present in list.// C++ program to find the first occurrence of an odd// and even number#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the Predicate Function to find first occurrence// of an odd numberbool pred( int a, int b){ if (a % b != 0) { return 1; } else { return 0; }} // Defining the Predicate Function to find first occurrence// of an even numberbool pred1( int a, int b){ if (a % b == 0) { return 1; } else { return 0; }} int main(){ // Defining a vector vector<int>v1 = {1, 3, 4, 5, 6, 7, 8, 10}; // Declaring a sub-sequence vector<int>v2 = {2}; // Using std::find_first_of to find the first // occurrence of an odd number vector<int>::iterator ip; ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred); // Displaying the index where the first odd number // occurred cout << "First odd no. occurs at index " << (ip - v1.begin()); // Using std::find_first_of to find the last occurrence // of an even number ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred1); // Displaying the index where the first even number // occurred cout << "\nFirst even no. occurs at index " << (ip - v1.begin()); return 0;}Output:First odd no. occurs at index 0 First even no. occurs at index 2 Explanation: Here, we have stored 2 in one container and with the help of predicate function, we are looking for the first number in the first container which is not divisible by 2 (for odd number) and which is divisible by 2 (for even number). // C++ program to find the first occurrence of an odd// and even number#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the Predicate Function to find first occurrence// of an odd numberbool pred( int a, int b){ if (a % b != 0) { return 1; } else { return 0; }} // Defining the Predicate Function to find first occurrence// of an even numberbool pred1( int a, int b){ if (a % b == 0) { return 1; } else { return 0; }} int main(){ // Defining a vector vector<int>v1 = {1, 3, 4, 5, 6, 7, 8, 10}; // Declaring a sub-sequence vector<int>v2 = {2}; // Using std::find_first_of to find the first // occurrence of an odd number vector<int>::iterator ip; ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred); // Displaying the index where the first odd number // occurred cout << "First odd no. occurs at index " << (ip - v1.begin()); // Using std::find_first_of to find the last occurrence // of an even number ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred1); // Displaying the index where the first even number // occurred cout << "\nFirst even no. occurs at index " << (ip - v1.begin()); return 0;} Output: First odd no. occurs at index 0 First even no. occurs at index 2 Explanation: Here, we have stored 2 in one container and with the help of predicate function, we are looking for the first number in the first container which is not divisible by 2 (for odd number) and which is divisible by 2 (for even number). Time Complexity: O(n1 * n2), where, n1 is the number of elements in the first range and n2 is the number of elements in the second range. This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-algorithm-library cpp-strings-library STL vowel-consonant C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Oct, 2017" }, { "code": null, "e": 353, "s": 52, "text": "std::find_first_of is used to compare elements between two containers. It compares all the elements in a range [first1,last1) with the elements in the range [first2,last2), and if any of the elements present in the second range is found in the first one , then it returns an iterator to that element." }, { "code": null, "e": 576, "s": 353, "text": "If there are more than one element common in both the ranges, then an iterator to the first common element present in the first container is returned. In case there is no match, then iterator pointing to last1 is returned." }, { "code": null, "e": 619, "s": 576, "text": "It can be used in two ways as shown below:" }, { "code": null, "e": 4375, "s": 619, "text": "Comparing elements using ==:Syntax:Template\nForwardIterator1 find_first_of(ForwardIterator1 first1,\n ForwardIterator1 last1,\n ForwardIterator2 first2, \n ForwardIterator2 last2);\n\nfirst1: Forward iterator to the first element \n in the first range.\nlast1: Forward iterator to the last element \n in the first range.\nfirst2: Forward iterator to the first element\n in the second range.\nlast2: Forward iterator to the last element \n in the second range.\n\nReturn Value: It returns an iterator to the \n first element in [first1,last1) that is part of \n [first2,last2). If no matches are found or [first2,\n last2) is empty, the function returns last1.\n// C++ program to demonstrate // the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){ // Defining first container vector<int>v = {1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8} , i; // Defining second container vector<int>v1 = {1, 3, 10}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end()); // Displaying the first common element found cout << *ip << \"\\n\"; // Finding the second common element ip = std::find_first_of(ip + 1, v.end(), v1.begin(), v1.end()); // Displaying the second common element found cout << *ip << \"\\n\"; return 0;}Output:1 \n3\nHere, in both the vectors, the first common element is 1 and to find the second common element, we have passed the beginning of the first range as the element next to the first common element already found.By comparing using a pre-defined function:Syntax:Template\n ForwardIterator1 find_first_of (ForwardIterator1 first1, \n ForwardIterator1 last1,\n ForwardIterator2 first2, \n ForwardIterator2 last2,\n BinaryPredicate pred);\n\nHere, first1, last1, first2 and last2 are the same as\nprevious case.\n\nPred: Binary function that accepts two \nelements as arguments (one of each of the two sequences, \nin the same order), and returns a value convertible to \nbool. The value returned indicates whether the elements \nare considered to match in the context of this function.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\n\nReturn Value: It returns an iterator to \nthe first element in [first1,last1) that is part of \n[first2,last2). If no matches are found or [first2,last2) \nis empty, the function returns last1.// C++ program to demonstrate// the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the BinaryFunctionbool Pred (int a, int b){ if ( a % b == 0) { return 1; } else { return 0; }}int main(){ // Defining first container vector<int>v = {1, 5, 7, 11, 13, 15, 30, 30, 7} , i; // Defining second container vector<int>v1 = {2, 3, 4}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end(), Pred); // Displaying the first element satisfying Pred() cout << *ip << \"\\n\"; return 0;}Output:15\nHere, we have manipulated the binary function in such a way that we are trying to find the first number in the first container which is a multiple of any of the number in the second container. And in this case, 15 comes out to be the first one, as it is divisible by 3." }, { "code": null, "e": 6160, "s": 4375, "text": "Comparing elements using ==:Syntax:Template\nForwardIterator1 find_first_of(ForwardIterator1 first1,\n ForwardIterator1 last1,\n ForwardIterator2 first2, \n ForwardIterator2 last2);\n\nfirst1: Forward iterator to the first element \n in the first range.\nlast1: Forward iterator to the last element \n in the first range.\nfirst2: Forward iterator to the first element\n in the second range.\nlast2: Forward iterator to the last element \n in the second range.\n\nReturn Value: It returns an iterator to the \n first element in [first1,last1) that is part of \n [first2,last2). If no matches are found or [first2,\n last2) is empty, the function returns last1.\n// C++ program to demonstrate // the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){ // Defining first container vector<int>v = {1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8} , i; // Defining second container vector<int>v1 = {1, 3, 10}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end()); // Displaying the first common element found cout << *ip << \"\\n\"; // Finding the second common element ip = std::find_first_of(ip + 1, v.end(), v1.begin(), v1.end()); // Displaying the second common element found cout << *ip << \"\\n\"; return 0;}Output:1 \n3\nHere, in both the vectors, the first common element is 1 and to find the second common element, we have passed the beginning of the first range as the element next to the first common element already found." }, { "code": null, "e": 6168, "s": 6160, "text": "Syntax:" }, { "code": null, "e": 6930, "s": 6168, "text": "Template\nForwardIterator1 find_first_of(ForwardIterator1 first1,\n ForwardIterator1 last1,\n ForwardIterator2 first2, \n ForwardIterator2 last2);\n\nfirst1: Forward iterator to the first element \n in the first range.\nlast1: Forward iterator to the last element \n in the first range.\nfirst2: Forward iterator to the first element\n in the second range.\nlast2: Forward iterator to the last element \n in the second range.\n\nReturn Value: It returns an iterator to the \n first element in [first1,last1) that is part of \n [first2,last2). If no matches are found or [first2,\n last2) is empty, the function returns last1.\n" }, { "code": "// C++ program to demonstrate // the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){ // Defining first container vector<int>v = {1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8} , i; // Defining second container vector<int>v1 = {1, 3, 10}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end()); // Displaying the first common element found cout << *ip << \"\\n\"; // Finding the second common element ip = std::find_first_of(ip + 1, v.end(), v1.begin(), v1.end()); // Displaying the second common element found cout << *ip << \"\\n\"; return 0;}", "e": 7701, "s": 6930, "text": null }, { "code": null, "e": 7709, "s": 7701, "text": "Output:" }, { "code": null, "e": 7715, "s": 7709, "text": "1 \n3\n" }, { "code": null, "e": 7922, "s": 7715, "text": "Here, in both the vectors, the first common element is 1 and to find the second common element, we have passed the beginning of the first range as the element next to the first common element already found." }, { "code": null, "e": 9894, "s": 7922, "text": "By comparing using a pre-defined function:Syntax:Template\n ForwardIterator1 find_first_of (ForwardIterator1 first1, \n ForwardIterator1 last1,\n ForwardIterator2 first2, \n ForwardIterator2 last2,\n BinaryPredicate pred);\n\nHere, first1, last1, first2 and last2 are the same as\nprevious case.\n\nPred: Binary function that accepts two \nelements as arguments (one of each of the two sequences, \nin the same order), and returns a value convertible to \nbool. The value returned indicates whether the elements \nare considered to match in the context of this function.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\n\nReturn Value: It returns an iterator to \nthe first element in [first1,last1) that is part of \n[first2,last2). If no matches are found or [first2,last2) \nis empty, the function returns last1.// C++ program to demonstrate// the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the BinaryFunctionbool Pred (int a, int b){ if ( a % b == 0) { return 1; } else { return 0; }}int main(){ // Defining first container vector<int>v = {1, 5, 7, 11, 13, 15, 30, 30, 7} , i; // Defining second container vector<int>v1 = {2, 3, 4}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end(), Pred); // Displaying the first element satisfying Pred() cout << *ip << \"\\n\"; return 0;}Output:15\nHere, we have manipulated the binary function in such a way that we are trying to find the first number in the first container which is a multiple of any of the number in the second container. And in this case, 15 comes out to be the first one, as it is divisible by 3." }, { "code": null, "e": 9902, "s": 9894, "text": "Syntax:" }, { "code": null, "e": 10853, "s": 9902, "text": "Template\n ForwardIterator1 find_first_of (ForwardIterator1 first1, \n ForwardIterator1 last1,\n ForwardIterator2 first2, \n ForwardIterator2 last2,\n BinaryPredicate pred);\n\nHere, first1, last1, first2 and last2 are the same as\nprevious case.\n\nPred: Binary function that accepts two \nelements as arguments (one of each of the two sequences, \nin the same order), and returns a value convertible to \nbool. The value returned indicates whether the elements \nare considered to match in the context of this function.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\n\nReturn Value: It returns an iterator to \nthe first element in [first1,last1) that is part of \n[first2,last2). If no matches are found or [first2,last2) \nis empty, the function returns last1." }, { "code": "// C++ program to demonstrate// the use of std::find_first_of#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the BinaryFunctionbool Pred (int a, int b){ if ( a % b == 0) { return 1; } else { return 0; }}int main(){ // Defining first container vector<int>v = {1, 5, 7, 11, 13, 15, 30, 30, 7} , i; // Defining second container vector<int>v1 = {2, 3, 4}; vector<int>::iterator ip; // Using std::find_first_of ip = std::find_first_of(v.begin(), v.end(), v1.begin(), v1.end(), Pred); // Displaying the first element satisfying Pred() cout << *ip << \"\\n\"; return 0;}", "e": 11547, "s": 10853, "text": null }, { "code": null, "e": 11555, "s": 11547, "text": "Output:" }, { "code": null, "e": 11559, "s": 11555, "text": "15\n" }, { "code": null, "e": 11829, "s": 11559, "text": "Here, we have manipulated the binary function in such a way that we are trying to find the first number in the first container which is a multiple of any of the number in the second container. And in this case, 15 comes out to be the first one, as it is divisible by 3." }, { "code": null, "e": 11964, "s": 11829, "text": "Possible Application: std::find_first_of can be used to find the first occurrence of any of the elements present in another container." }, { "code": null, "e": 14757, "s": 11964, "text": "One possible application of this is to find the first vowel in a sentence.// C++ program to demonstrate the use of std::find_first_of#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;int main(){ // Defining first container string s1 = \"You are reading about std::find_first_of\"; // Defining second container containing list of vowels string s2 = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}; // Using std::find_first_of to find first occurrence of // a vowel auto ip = std::find_first_of(s1.begin(),s1.end(), s2.begin(), s2.end()); // Displaying the first vowel found cout << \"First vowel found at index \"<< (ip - s1.begin()) << \"\\n\"; return 0;}Output:First vowel found at index 1\nExplanation: std::find_first_of searches for the first occurrence of any of the elements from the second container in the first one, and in this way , first vowel present in the sentence was found out.It can also be used to find the first odd and even numbers present in list.// C++ program to find the first occurrence of an odd// and even number#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the Predicate Function to find first occurrence// of an odd numberbool pred( int a, int b){ if (a % b != 0) { return 1; } else { return 0; }} // Defining the Predicate Function to find first occurrence// of an even numberbool pred1( int a, int b){ if (a % b == 0) { return 1; } else { return 0; }} int main(){ // Defining a vector vector<int>v1 = {1, 3, 4, 5, 6, 7, 8, 10}; // Declaring a sub-sequence vector<int>v2 = {2}; // Using std::find_first_of to find the first // occurrence of an odd number vector<int>::iterator ip; ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred); // Displaying the index where the first odd number // occurred cout << \"First odd no. occurs at index \" << (ip - v1.begin()); // Using std::find_first_of to find the last occurrence // of an even number ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred1); // Displaying the index where the first even number // occurred cout << \"\\nFirst even no. occurs at index \" << (ip - v1.begin()); return 0;}Output:First odd no. occurs at index 0\nFirst even no. occurs at index 2\nExplanation: Here, we have stored 2 in one container and with the help of predicate function, we are looking for the first number in the first container which is not divisible by 2 (for odd number) and which is divisible by 2 (for even number)." }, { "code": null, "e": 15782, "s": 14757, "text": "One possible application of this is to find the first vowel in a sentence.// C++ program to demonstrate the use of std::find_first_of#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;int main(){ // Defining first container string s1 = \"You are reading about std::find_first_of\"; // Defining second container containing list of vowels string s2 = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}; // Using std::find_first_of to find first occurrence of // a vowel auto ip = std::find_first_of(s1.begin(),s1.end(), s2.begin(), s2.end()); // Displaying the first vowel found cout << \"First vowel found at index \"<< (ip - s1.begin()) << \"\\n\"; return 0;}Output:First vowel found at index 1\nExplanation: std::find_first_of searches for the first occurrence of any of the elements from the second container in the first one, and in this way , first vowel present in the sentence was found out." }, { "code": "// C++ program to demonstrate the use of std::find_first_of#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;int main(){ // Defining first container string s1 = \"You are reading about std::find_first_of\"; // Defining second container containing list of vowels string s2 = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}; // Using std::find_first_of to find first occurrence of // a vowel auto ip = std::find_first_of(s1.begin(),s1.end(), s2.begin(), s2.end()); // Displaying the first vowel found cout << \"First vowel found at index \"<< (ip - s1.begin()) << \"\\n\"; return 0;}", "e": 16496, "s": 15782, "text": null }, { "code": null, "e": 16504, "s": 16496, "text": "Output:" }, { "code": null, "e": 16534, "s": 16504, "text": "First vowel found at index 1\n" }, { "code": null, "e": 16736, "s": 16534, "text": "Explanation: std::find_first_of searches for the first occurrence of any of the elements from the second container in the first one, and in this way , first vowel present in the sentence was found out." }, { "code": null, "e": 18505, "s": 16736, "text": "It can also be used to find the first odd and even numbers present in list.// C++ program to find the first occurrence of an odd// and even number#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the Predicate Function to find first occurrence// of an odd numberbool pred( int a, int b){ if (a % b != 0) { return 1; } else { return 0; }} // Defining the Predicate Function to find first occurrence// of an even numberbool pred1( int a, int b){ if (a % b == 0) { return 1; } else { return 0; }} int main(){ // Defining a vector vector<int>v1 = {1, 3, 4, 5, 6, 7, 8, 10}; // Declaring a sub-sequence vector<int>v2 = {2}; // Using std::find_first_of to find the first // occurrence of an odd number vector<int>::iterator ip; ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred); // Displaying the index where the first odd number // occurred cout << \"First odd no. occurs at index \" << (ip - v1.begin()); // Using std::find_first_of to find the last occurrence // of an even number ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred1); // Displaying the index where the first even number // occurred cout << \"\\nFirst even no. occurs at index \" << (ip - v1.begin()); return 0;}Output:First odd no. occurs at index 0\nFirst even no. occurs at index 2\nExplanation: Here, we have stored 2 in one container and with the help of predicate function, we are looking for the first number in the first container which is not divisible by 2 (for odd number) and which is divisible by 2 (for even number)." }, { "code": "// C++ program to find the first occurrence of an odd// and even number#include<iostream>#include<vector>#include<algorithm>using namespace std; // Defining the Predicate Function to find first occurrence// of an odd numberbool pred( int a, int b){ if (a % b != 0) { return 1; } else { return 0; }} // Defining the Predicate Function to find first occurrence// of an even numberbool pred1( int a, int b){ if (a % b == 0) { return 1; } else { return 0; }} int main(){ // Defining a vector vector<int>v1 = {1, 3, 4, 5, 6, 7, 8, 10}; // Declaring a sub-sequence vector<int>v2 = {2}; // Using std::find_first_of to find the first // occurrence of an odd number vector<int>::iterator ip; ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred); // Displaying the index where the first odd number // occurred cout << \"First odd no. occurs at index \" << (ip - v1.begin()); // Using std::find_first_of to find the last occurrence // of an even number ip = std::find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), pred1); // Displaying the index where the first even number // occurred cout << \"\\nFirst even no. occurs at index \" << (ip - v1.begin()); return 0;}", "e": 19883, "s": 18505, "text": null }, { "code": null, "e": 19891, "s": 19883, "text": "Output:" }, { "code": null, "e": 19957, "s": 19891, "text": "First odd no. occurs at index 0\nFirst even no. occurs at index 2\n" }, { "code": null, "e": 20202, "s": 19957, "text": "Explanation: Here, we have stored 2 in one container and with the help of predicate function, we are looking for the first number in the first container which is not divisible by 2 (for odd number) and which is divisible by 2 (for even number)." }, { "code": null, "e": 20340, "s": 20202, "text": "Time Complexity: O(n1 * n2), where, n1 is the number of elements in the first range and n2 is the number of elements in the second range." }, { "code": null, "e": 20643, "s": 20340, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 20768, "s": 20643, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 20790, "s": 20768, "text": "cpp-algorithm-library" }, { "code": null, "e": 20810, "s": 20790, "text": "cpp-strings-library" }, { "code": null, "e": 20814, "s": 20810, "text": "STL" }, { "code": null, "e": 20830, "s": 20814, "text": "vowel-consonant" }, { "code": null, "e": 20834, "s": 20830, "text": "C++" }, { "code": null, "e": 20838, "s": 20834, "text": "STL" }, { "code": null, "e": 20842, "s": 20838, "text": "CPP" }, { "code": null, "e": 20940, "s": 20842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20964, "s": 20940, "text": "Sorting a vector in C++" }, { "code": null, "e": 20984, "s": 20964, "text": "Polymorphism in C++" }, { "code": null, "e": 21017, "s": 20984, "text": "Friend class and function in C++" }, { "code": null, "e": 21061, "s": 21017, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 21086, "s": 21061, "text": "std::string class in C++" }, { "code": null, "e": 21131, "s": 21086, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 21179, "s": 21131, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 21196, "s": 21179, "text": "std::find in C++" }, { "code": null, "e": 21240, "s": 21196, "text": "List in C++ Standard Template Library (STL)" } ]
Introduction to C#
17 Dec, 2019 C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team within the .Net initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# is among the languages for Common Language Infrastructure and the current version of C# is version 7.2. C# is a lot similar to Java syntactically and is easy for the users who have knowledge of C, C++ or Java. A bit about .Net Framework.Net applications are multi-platform applications and framework can be used from languages like C++, C#, Visual Basic, COBOL etc. It is designed in a manner so that other languages can use it.know more about .Net Framework Why C#? C# has many other reasons for being popular and in demand. Few of the reasons are mentioned below: Easy to start: C# is a high-level language so it is closer to other popular programming languages like C, C++, and Java and thus becomes easy to learn for anyone.Widely used for developing Desktop and Web Application: C# is widely used for developing web applications and Desktop applications. It is one of the most popular languages that is used in professional desktop. If anyone wants to create Microsoft apps, C# is their first choice.Community:The larger the community the better it is as new tools and software will be developing to make it better. C# has a large community so the developments are done to make it exist in the system and not become extinct.Game Development: C# is widely used in game development and will continue to dominate. C# integrates with Microsoft and thus has a large target audience. The C# features such as Automatic Garbage Collection, interfaces, object-oriented, etc. make C# a popular game developing language. Easy to start: C# is a high-level language so it is closer to other popular programming languages like C, C++, and Java and thus becomes easy to learn for anyone. Widely used for developing Desktop and Web Application: C# is widely used for developing web applications and Desktop applications. It is one of the most popular languages that is used in professional desktop. If anyone wants to create Microsoft apps, C# is their first choice. Community:The larger the community the better it is as new tools and software will be developing to make it better. C# has a large community so the developments are done to make it exist in the system and not become extinct. Game Development: C# is widely used in game development and will continue to dominate. C# integrates with Microsoft and thus has a large target audience. The C# features such as Automatic Garbage Collection, interfaces, object-oriented, etc. make C# a popular game developing language. Beginning with C# programming:Finding a Compiler:There are various online IDEs such as GeeksforGeeks ide, CodeChef ide etc. which can be used to run C# programs without installing. Windows: Since the C# is developed within .Net framework initiative by Microsoft, it provide various IDEs to run C# programs: Microsoft Visual Studio, Visual Studio Express, Visual Web Developer Linux: Mono can be used to run C# programs on Linux. Programming in C#:Since the C# is a lot similar to other widely used languages syntactically, it is easier to code and learn in C#.Programs can be written in C# in any of the widely used text editors like Notepad++, gedit, etc. or on any of the compilers. After writing the program save the file with the extension .cs. Example: A simple program to print Hello Geeks // C# program to print Hello Geeksusing System; namespace HelloGeeksApp{ class HelloGeeks { // Main function static void Main(string[] args) { // Printing Hello Geeks Console.WriteLine("Hello Geeks"); Console.ReadKey(); } }} Output: Hello Geeks Explanation:1. Comments: Comments are used for explaining code and are used in similar manner as in Java or C or C++. Compilers ignore the comment entries and does not execute them. Comments can be of single line or multiple lines.Single line Comments:Syntax: // Single line comment Multi line comments:Syntax: /* Multi line comments*/ 2. using System: using keyword is used to include the System namespace in the program.namespace declaration: A namespace is a collection of classes. The HelloGeeksApp namespace contains the class HelloGeeks.3. class: The class contains the data and methods to be used in the program. Methods define the behavior of the class. Class HelloGeeks has only one method Main similar to JAVA. 4. static void Main(): static keyword tells us that this method is accessible without instantiating the class. 5. void keywords tells that this method will not return anything. Main() method is the entry-point of our application. In our program, Main() method specifies its behavior with the statement Console.WriteLine(“Hello Geeks”); . 6. Console.WriteLine(): WriteLine() is a method of the Console class defined in the System namespace.7. Console.ReadKey(): This is for the VS.NET Users. This makes the program wait for a key press and prevents the screen from running and closing quickly.Note: C# is case sensitive and all statements and expressions must end with semicolon (;). Advantages of C#: C# is very efficient in managing the system. All the garbage is automatically collected in C#. There is no problem of memory leak in C# because of its high memory backup. Cost of maintenance is less and is safer to run as compared to other languages. C# code is compiled to a intermediate language (Common (.Net) Intermediate Language) which is a standard language, independently irrespective of the target operating system and architecture. Disadvantages of C#: C# is less flexible as it depends alot on .Net framework. C# runs slowly and program needs to be compiled each time when any changes are made. Applications: C# is widely used for developing desktop applications, web applications and web services. It is used in creating applications of Microsoft at a large scale. C# is also used in game development in Unity. CSharp-Basics 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# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Replace() Method C# | Arrays Difference between Ref and Out keywords in C#
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Dec, 2019" }, { "code": null, "e": 582, "s": 54, "text": "C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team within the .Net initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# is among the languages for Common Language Infrastructure and the current version of C# is version 7.2. C# is a lot similar to Java syntactically and is easy for the users who have knowledge of C, C++ or Java." }, { "code": null, "e": 831, "s": 582, "text": "A bit about .Net Framework.Net applications are multi-platform applications and framework can be used from languages like C++, C#, Visual Basic, COBOL etc. It is designed in a manner so that other languages can use it.know more about .Net Framework" }, { "code": null, "e": 839, "s": 831, "text": "Why C#?" }, { "code": null, "e": 938, "s": 839, "text": "C# has many other reasons for being popular and in demand. Few of the reasons are mentioned below:" }, { "code": null, "e": 1887, "s": 938, "text": "Easy to start: C# is a high-level language so it is closer to other popular programming languages like C, C++, and Java and thus becomes easy to learn for anyone.Widely used for developing Desktop and Web Application: C# is widely used for developing web applications and Desktop applications. It is one of the most popular languages that is used in professional desktop. If anyone wants to create Microsoft apps, C# is their first choice.Community:The larger the community the better it is as new tools and software will be developing to make it better. C# has a large community so the developments are done to make it exist in the system and not become extinct.Game Development: C# is widely used in game development and will continue to dominate. C# integrates with Microsoft and thus has a large target audience. The C# features such as Automatic Garbage Collection, interfaces, object-oriented, etc. make C# a popular game developing language." }, { "code": null, "e": 2050, "s": 1887, "text": "Easy to start: C# is a high-level language so it is closer to other popular programming languages like C, C++, and Java and thus becomes easy to learn for anyone." }, { "code": null, "e": 2328, "s": 2050, "text": "Widely used for developing Desktop and Web Application: C# is widely used for developing web applications and Desktop applications. It is one of the most popular languages that is used in professional desktop. If anyone wants to create Microsoft apps, C# is their first choice." }, { "code": null, "e": 2553, "s": 2328, "text": "Community:The larger the community the better it is as new tools and software will be developing to make it better. C# has a large community so the developments are done to make it exist in the system and not become extinct." }, { "code": null, "e": 2839, "s": 2553, "text": "Game Development: C# is widely used in game development and will continue to dominate. C# integrates with Microsoft and thus has a large target audience. The C# features such as Automatic Garbage Collection, interfaces, object-oriented, etc. make C# a popular game developing language." }, { "code": null, "e": 3020, "s": 2839, "text": "Beginning with C# programming:Finding a Compiler:There are various online IDEs such as GeeksforGeeks ide, CodeChef ide etc. which can be used to run C# programs without installing." }, { "code": null, "e": 3215, "s": 3020, "text": "Windows: Since the C# is developed within .Net framework initiative by Microsoft, it provide various IDEs to run C# programs: Microsoft Visual Studio, Visual Studio Express, Visual Web Developer" }, { "code": null, "e": 3268, "s": 3215, "text": "Linux: Mono can be used to run C# programs on Linux." }, { "code": null, "e": 3588, "s": 3268, "text": "Programming in C#:Since the C# is a lot similar to other widely used languages syntactically, it is easier to code and learn in C#.Programs can be written in C# in any of the widely used text editors like Notepad++, gedit, etc. or on any of the compilers. After writing the program save the file with the extension .cs." }, { "code": null, "e": 3635, "s": 3588, "text": "Example: A simple program to print Hello Geeks" }, { "code": "// C# program to print Hello Geeksusing System; namespace HelloGeeksApp{ class HelloGeeks { // Main function static void Main(string[] args) { // Printing Hello Geeks Console.WriteLine(\"Hello Geeks\"); Console.ReadKey(); } }}", "e": 3941, "s": 3635, "text": null }, { "code": null, "e": 3949, "s": 3941, "text": "Output:" }, { "code": null, "e": 3961, "s": 3949, "text": "Hello Geeks" }, { "code": null, "e": 4221, "s": 3961, "text": "Explanation:1. Comments: Comments are used for explaining code and are used in similar manner as in Java or C or C++. Compilers ignore the comment entries and does not execute them. Comments can be of single line or multiple lines.Single line Comments:Syntax:" }, { "code": null, "e": 4244, "s": 4221, "text": "// Single line comment" }, { "code": null, "e": 4272, "s": 4244, "text": "Multi line comments:Syntax:" }, { "code": null, "e": 4297, "s": 4272, "text": "/* Multi line comments*/" }, { "code": null, "e": 4682, "s": 4297, "text": "2. using System: using keyword is used to include the System namespace in the program.namespace declaration: A namespace is a collection of classes. The HelloGeeksApp namespace contains the class HelloGeeks.3. class: The class contains the data and methods to be used in the program. Methods define the behavior of the class. Class HelloGeeks has only one method Main similar to JAVA." }, { "code": null, "e": 5020, "s": 4682, "text": "4. static void Main(): static keyword tells us that this method is accessible without instantiating the class. 5. void keywords tells that this method will not return anything. Main() method is the entry-point of our application. In our program, Main() method specifies its behavior with the statement Console.WriteLine(“Hello Geeks”); ." }, { "code": null, "e": 5365, "s": 5020, "text": "6. Console.WriteLine(): WriteLine() is a method of the Console class defined in the System namespace.7. Console.ReadKey(): This is for the VS.NET Users. This makes the program wait for a key press and prevents the screen from running and closing quickly.Note: C# is case sensitive and all statements and expressions must end with semicolon (;)." }, { "code": null, "e": 5383, "s": 5365, "text": "Advantages of C#:" }, { "code": null, "e": 5478, "s": 5383, "text": "C# is very efficient in managing the system. All the garbage is automatically collected in C#." }, { "code": null, "e": 5554, "s": 5478, "text": "There is no problem of memory leak in C# because of its high memory backup." }, { "code": null, "e": 5634, "s": 5554, "text": "Cost of maintenance is less and is safer to run as compared to other languages." }, { "code": null, "e": 5825, "s": 5634, "text": "C# code is compiled to a intermediate language (Common (.Net) Intermediate Language) which is a standard language, independently irrespective of the target operating system and architecture." }, { "code": null, "e": 5846, "s": 5825, "text": "Disadvantages of C#:" }, { "code": null, "e": 5904, "s": 5846, "text": "C# is less flexible as it depends alot on .Net framework." }, { "code": null, "e": 5989, "s": 5904, "text": "C# runs slowly and program needs to be compiled each time when any changes are made." }, { "code": null, "e": 6003, "s": 5989, "text": "Applications:" }, { "code": null, "e": 6093, "s": 6003, "text": "C# is widely used for developing desktop applications, web applications and web services." }, { "code": null, "e": 6160, "s": 6093, "text": "It is used in creating applications of Microsoft at a large scale." }, { "code": null, "e": 6206, "s": 6160, "text": "C# is also used in game development in Unity." }, { "code": null, "e": 6220, "s": 6206, "text": "CSharp-Basics" }, { "code": null, "e": 6223, "s": 6220, "text": "C#" }, { "code": null, "e": 6321, "s": 6223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6349, "s": 6321, "text": "C# Dictionary with examples" }, { "code": null, "e": 6392, "s": 6349, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 6423, "s": 6392, "text": "Introduction to .NET Framework" }, { "code": null, "e": 6438, "s": 6423, "text": "C# | Delegates" }, { "code": null, "e": 6487, "s": 6438, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 6527, "s": 6487, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 6550, "s": 6527, "text": "Extension Method in C#" }, { "code": null, "e": 6572, "s": 6550, "text": "C# | Replace() Method" }, { "code": null, "e": 6584, "s": 6572, "text": "C# | Arrays" } ]
TypeScript - Modules
A module is designed with the idea to organize code written in TypeScript. Modules are broadly divided into − Internal Modules External Modules Internal modules came in earlier version of Typescript. This was used to logically group classes, interfaces, functions into one unit and can be exported in another module. This logical grouping is named namespace in latest version of TypeScript. So internal modules are obsolete instead we can use namespace. Internal modules are still supported, but its recommended to use namespace over internal modules. module TutorialPoint { export function add(x, y) { console.log(x+y); } } namespace TutorialPoint { export function add(x, y) { console.log(x + y);} } var TutorialPoint; (function (TutorialPoint) { function add(x, y) { console.log(x + y); } TutorialPoint.add = add; })(TutorialPoint || (TutorialPoint = {})); External modules in TypeScript exists to specify and load dependencies between multiple external js files. If there is only one js file used, then external modules are not relevant. Traditionally dependency management between JavaScript files was done using browser script tags (<script></script>). But that’s not extendable, as its very linear while loading modules. That means instead of loading files one after other there is no asynchronous option to load modules. When you are programming js for the server for example NodeJs you don’t even have script tags. There are two scenarios for loading dependents js files from a single main JavaScript file. Client Side - RequireJs Server Side - NodeJs To support loading external JavaScript files, we need a module loader. This will be another js library. For browser the most common library used is RequieJS. This is an implementation of AMD (Asynchronous Module Definition) specification. Instead of loading files one after the other, AMD can load them all separately, even when they are dependent on each other. When defining external module in TypeScript targeting CommonJS or AMD, each file is considered as a module. So it’s optional to use internal module with in external module. If you are migrating TypeScript from AMD to CommonJs module systems, then there is no additional work needed. The only thing you need to change is just the compiler flag Unlike in JavaScript there is an overhead in migrating from CommonJs to AMD or vice versa. The syntax for declaring an external module is using keyword ‘export’ and ‘import’. //FileName : SomeInterface.ts export interface SomeInterface { //code declarations } To use the declared module in another file, an import keyword is used as given below. The file name is only specified no extension used. import someInterfaceRef = require(“./SomeInterface”); Let’s understand this using an example. // IShape.ts export interface IShape { draw(); } // Circle.ts import shape = require("./IShape"); export class Circle implements shape.IShape { public draw() { console.log("Cirlce is drawn (external module)"); } } // Triangle.ts import shape = require("./IShape"); export class Triangle implements shape.IShape { public draw() { console.log("Triangle is drawn (external module)"); } } // TestShape.ts import shape = require("./IShape"); import circle = require("./Circle"); import triangle = require("./Triangle"); function drawAllShapes(shapeToDraw: shape.IShape) { shapeToDraw.draw(); } drawAllShapes(new circle.Circle()); drawAllShapes(new triangle.Triangle()); The command to compile the main TypeScript file for AMD systems is − tsc --module amd TestShape.ts On compiling, it will generate following JavaScript code for AMD. //Generated by typescript 1.8.10 define(["require", "exports"], function (require, exports) { }); //Generated by typescript 1.8.10 define(["require", "exports"], function (require, exports) { var Circle = (function () { function Circle() { } Circle.prototype.draw = function () { console.log("Cirlce is drawn (external module)"); }; return Circle; })(); exports.Circle = Circle; }); //Generated by typescript 1.8.10 define(["require", "exports"], function (require, exports) { var Triangle = (function () { function Triangle() { } Triangle.prototype.draw = function () { console.log("Triangle is drawn (external module)"); }; return Triangle; })(); exports.Triangle = Triangle; }); //Generated by typescript 1.8.10 define(["require", "exports", "./Circle", "./Triangle"], function (require, exports, circle, triangle) { function drawAllShapes(shapeToDraw) { shapeToDraw.draw(); } drawAllShapes(new circle.Circle()); drawAllShapes(new triangle.Triangle()); }); The command to compile the main TypeScript file for Commonjs systems is tsc --module commonjs TestShape.ts On compiling, it will generate following JavaScript code for Commonjs. //Generated by typescript 1.8.10 var Circle = (function () { function Circle() { } Circle.prototype.draw = function () { console.log("Cirlce is drawn"); }; return Circle; })(); exports.Circle = Circle; //Generated by typescript 1.8.10 var Triangle = (function () { function Triangle() { } Triangle.prototype.draw = function () { console.log("Triangle is drawn (external module)"); }; return Triangle; })(); exports.Triangle = Triangle; //Generated by typescript 1.8.10 var circle = require("./Circle"); var triangle = require("./Triangle"); function drawAllShapes(shapeToDraw) { shapeToDraw.draw(); } drawAllShapes(new circle.Circle()); drawAllShapes(new triangle.Triangle()); Cirlce is drawn (external module) Triangle is drawn (external module)
[ { "code": null, "e": 2292, "s": 2182, "text": "A module is designed with the idea to organize code written in TypeScript. Modules are broadly divided into −" }, { "code": null, "e": 2309, "s": 2292, "text": "Internal Modules" }, { "code": null, "e": 2326, "s": 2309, "text": "External Modules" }, { "code": null, "e": 2734, "s": 2326, "text": "Internal modules came in earlier version of Typescript. This was used to logically group classes, interfaces, functions into one unit and can be exported in another module. This logical grouping is named namespace in latest version of TypeScript. So internal modules are obsolete instead we can use namespace. Internal modules are still supported, but its recommended to use namespace over internal modules." }, { "code": null, "e": 2825, "s": 2734, "text": "module TutorialPoint { \n export function add(x, y) { \n console.log(x+y); \n } \n}\n" }, { "code": null, "e": 2908, "s": 2825, "text": "namespace TutorialPoint { \n export function add(x, y) { console.log(x + y);} \n}\n" }, { "code": null, "e": 3088, "s": 2908, "text": "var TutorialPoint; \n(function (TutorialPoint) { \n function add(x, y) { \n console.log(x + y); \n } \n TutorialPoint.add = add; \n})(TutorialPoint || (TutorialPoint = {}));\n" }, { "code": null, "e": 3652, "s": 3088, "text": "External modules in TypeScript exists to specify and load dependencies between multiple external js files. If there is only one js file used, then external modules are not relevant. Traditionally dependency management between JavaScript files was done using browser script tags (<script></script>). But that’s not extendable, as its very linear while loading modules. That means instead of loading files one after other there is no asynchronous option to load modules. When you are programming js for the server for example NodeJs you don’t even have script tags." }, { "code": null, "e": 3744, "s": 3652, "text": "There are two scenarios for loading dependents js files from a single main JavaScript file." }, { "code": null, "e": 3768, "s": 3744, "text": "Client Side - RequireJs" }, { "code": null, "e": 3789, "s": 3768, "text": "Server Side - NodeJs" }, { "code": null, "e": 4152, "s": 3789, "text": "To support loading external JavaScript files, we need a module loader. This will be another js library. For browser the most common library used is RequieJS. This is an implementation of AMD (Asynchronous Module Definition) specification. Instead of loading files one after the other, AMD can load them all separately, even when they are dependent on each other." }, { "code": null, "e": 4325, "s": 4152, "text": "When defining external module in TypeScript targeting CommonJS or AMD, each file is considered as a module. So it’s optional to use internal module with in external module." }, { "code": null, "e": 4586, "s": 4325, "text": "If you are migrating TypeScript from AMD to CommonJs module systems, then there is no additional work needed. The only thing you need to change is just the compiler flag Unlike in JavaScript there is an overhead in migrating from CommonJs to AMD or vice versa." }, { "code": null, "e": 4670, "s": 4586, "text": "The syntax for declaring an external module is using keyword ‘export’ and ‘import’." }, { "code": null, "e": 4762, "s": 4670, "text": "//FileName : SomeInterface.ts \nexport interface SomeInterface { \n //code declarations \n}\n" }, { "code": null, "e": 4899, "s": 4762, "text": "To use the declared module in another file, an import keyword is used as given below. The file name is only specified no extension used." }, { "code": null, "e": 4954, "s": 4899, "text": "import someInterfaceRef = require(“./SomeInterface”);\n" }, { "code": null, "e": 4994, "s": 4954, "text": "Let’s understand this using an example." }, { "code": null, "e": 5723, "s": 4994, "text": "// IShape.ts \nexport interface IShape { \n draw(); \n}\n\n// Circle.ts \nimport shape = require(\"./IShape\"); \nexport class Circle implements shape.IShape { \n public draw() { \n console.log(\"Cirlce is drawn (external module)\"); \n } \n} \n\n// Triangle.ts \nimport shape = require(\"./IShape\"); \nexport class Triangle implements shape.IShape { \n public draw() { \n console.log(\"Triangle is drawn (external module)\"); \n } \n}\n \n// TestShape.ts \nimport shape = require(\"./IShape\"); \nimport circle = require(\"./Circle\"); \nimport triangle = require(\"./Triangle\"); \n\nfunction drawAllShapes(shapeToDraw: shape.IShape) {\n shapeToDraw.draw(); \n} \n\ndrawAllShapes(new circle.Circle()); \ndrawAllShapes(new triangle.Triangle()); \n" }, { "code": null, "e": 5792, "s": 5723, "text": "The command to compile the main TypeScript file for AMD systems is −" }, { "code": null, "e": 5823, "s": 5792, "text": "tsc --module amd TestShape.ts\n" }, { "code": null, "e": 5889, "s": 5823, "text": "On compiling, it will generate following JavaScript code for AMD." }, { "code": null, "e": 5988, "s": 5889, "text": "//Generated by typescript 1.8.10\ndefine([\"require\", \"exports\"], function (require, exports) {\n});\n" }, { "code": null, "e": 6322, "s": 5988, "text": "//Generated by typescript 1.8.10\ndefine([\"require\", \"exports\"], function (require, exports) {\n var Circle = (function () {\n function Circle() {\n }\n Circle.prototype.draw = function () {\n console.log(\"Cirlce is drawn (external module)\");\n };\n return Circle;\n })();\n exports.Circle = Circle;\n});\n" }, { "code": null, "e": 6670, "s": 6322, "text": "//Generated by typescript 1.8.10\ndefine([\"require\", \"exports\"], function (require, exports) {\n var Triangle = (function () {\n function Triangle() {\n }\n Triangle.prototype.draw = function () {\n console.log(\"Triangle is drawn (external module)\");\n };\n return Triangle;\n })();\n exports.Triangle = Triangle;\n});\n" }, { "code": null, "e": 6975, "s": 6670, "text": "//Generated by typescript 1.8.10\ndefine([\"require\", \"exports\", \"./Circle\", \"./Triangle\"], \n function (require, exports, circle, triangle) {\n \n function drawAllShapes(shapeToDraw) {\n shapeToDraw.draw();\n }\n drawAllShapes(new circle.Circle());\n drawAllShapes(new triangle.Triangle());\n});\n" }, { "code": null, "e": 7047, "s": 6975, "text": "The command to compile the main TypeScript file for Commonjs systems is" }, { "code": null, "e": 7083, "s": 7047, "text": "tsc --module commonjs TestShape.ts\n" }, { "code": null, "e": 7154, "s": 7083, "text": "On compiling, it will generate following JavaScript code for Commonjs." }, { "code": null, "e": 7379, "s": 7154, "text": "//Generated by typescript 1.8.10\nvar Circle = (function () {\n function Circle() {\n }\n Circle.prototype.draw = function () {\n console.log(\"Cirlce is drawn\");\n };\n return Circle;\n})();\n\nexports.Circle = Circle;\n" }, { "code": null, "e": 7635, "s": 7379, "text": "//Generated by typescript 1.8.10\nvar Triangle = (function () {\n function Triangle() {\n }\n Triangle.prototype.draw = function () {\n console.log(\"Triangle is drawn (external module)\");\n };\n return Triangle;\n})();\nexports.Triangle = Triangle;\n" }, { "code": null, "e": 7881, "s": 7635, "text": "//Generated by typescript 1.8.10\nvar circle = require(\"./Circle\");\nvar triangle = require(\"./Triangle\");\n\nfunction drawAllShapes(shapeToDraw) {\n shapeToDraw.draw();\n}\ndrawAllShapes(new circle.Circle());\ndrawAllShapes(new triangle.Triangle());\n" } ]
Longest Palindromic Substring in Linear Time | Practice | GeeksforGeeks
Given a string, find the longest substring which is palindrome in Linear time O(N). Input: The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The only line of each test case contains a string. Output: For each test case print the Longest Palindromic Substring. If there are multiple such substrings of same length, print the one which appears first in the input string. Constraints: 1 <= T <= 100 1 <= N <= 50 Example: Input: 2 babcbabcbaccba forgeeksskeegfor Output: abcbabcba geeksskeeg Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. +1 wxyzpl5 months ago // java code static String LongestPalindromeSubString(String s) { int strLen = 2 * s.length() + 3; char[] sChars = new char[strLen]; /* * To ignore special cases at the beginning and end of the array * "abc" -> @ # a # b # c # $ * "" -> @#$ * "a" -> @ # a # $ */ sChars[0] = '@'; sChars[strLen - 1] = '$'; int t = 1; for (char c : s.toCharArray()) { sChars[t++] = '#'; sChars[t++] = c; } sChars[t] = '#'; int maxLen = 0; int start = 0; int maxRight = 0; int center = 0; int[] p = new int[strLen]; // i's radius, which not includes i for (int i = 1; i < strLen - 1; i++) { if (i < maxRight) { p[i] = Math.min(maxRight - i, p[2 * center - i]); } // expand center while (sChars[i + p[i] + 1] == sChars[i - p[i] - 1]) { p[i]++; } // update center and its bound if (i + p[i] > maxRight) { center = i; maxRight = i + p[i]; } // update ans if (p[i] > maxLen) { start = (i - p[i] - 1) / 2; maxLen = p[i]; } } return s.substring(start, start + maxLen); }} 0 tauruas08059 months ago string h="#"; for(int i=0;i<text.size();i++){ h.push_back(text[i]); h.push_back('#'); } int C=-1; int R=-1; int n=h.size(); vector<int>lps(n); int imirror; for(int i=0;i<n;i++){ imirror=2*C-i; if(R>i){ lps[i]=min(R-i,lps[imirror]); } else{ lps[i]=0; } while((i-lps[i]-1)>=0 && (i+lps[i]+1)<n && h[i-lps[i]-1]==h[i+1+lps[i]]){ lps[i]++; } if(i+lps[i]>R){ R=i+lps[i]; C=i; } } int mx=0; int s; for(int i=0;i<n;i++){ if(mx<lps[i]){ s=i; mx=lps[i]; } } int l=s-mx; int r=s+mx; string h2=h.substr(l,r-l+1); string ans=""; for(int i=0;i<h2.size();i++){ if(h2[i]!='#'){ ans.push_back(h2[i]); } } return ans; above code is submitted correctly but below code gives tle string text=s; if(text.size()==1)return text; string s1="@"; for(int i=0;i<text.size();i++) s1=s1+'#'+text[i]; s1+='#';s1+='*'; int c=0,r=0;int lps[s1.size()+1];memset(lps,0,sizeof(lps)); for(int i=1;i<s1.size()-1;i++){ int mi=c-(i-c); if(i<r)lps[i]=min(lps[mi],r-i); while(i+1+lps[i]<s1.size() and i-1-lps[i]>=0 and s1[i+1+lps[i]]==s1[i-1-lps[i]])lps[i]++; if(lps[i]+i>r){ c=i;r=lps[i]+i; } } int mx=0,st=0; for(int i=1;i<s1.size()-1;i++){ if(lps[i]>mx){mx=lps[i];st=i;} } int fi=st-mx+1; int aci=(fi-2)/2; return text.substr(aci,mx); } GFG LOOK INTO MATTER!!!!! -1 runtime_terror11 months agoAnyone can help me in my code it show TLE string helper(string& s, int l , int r){ int length = l==r ?-1:0; while(l >= 0 && r < s.length() && s[l] == s[r]){ l-=1; r+=1; length += 2; } return s.substr(1+l,length); } string LongestPalindromeSubString(string s){ string ans = "",temp; for(int i = 0 ; i < s.length() ; i++){ temp = helper(s,i,i); if(ans.length() < temp.length()){ ans = temp; } temp = helper(s,i,i+1); if(ans.length() < temp.length()){ ans = temp; } } return ans;}Reply Open ExternallyShow 1 RepliesLoading... runtime_terror Anyone can help me in my code it show TLE string helper(string& s, int l , int r){ int length = l==r ?-1:0; while(l >= 0 && r < s.length() && s[l] == s[r]){ l-=1; r+=1; length += 2; } return s.substr(1+l,length); } string LongestPalindromeSubString(string s){ string ans = "",temp; for(int i = 0 ; i < s.length() ; i++){ temp = helper(s,i,i); if(ans.length() < temp.length()){ ans = temp; } temp = helper(s,i,i+1); if(ans.length() < temp.length()){ ans = temp; } } return ans;} 0 Saarth Vikram Jhaveri1 year agoManacher's algorithm gg!Reply Open ExternallyShow 1 RepliesLoading... Saarth Vikram Jhaveri Manacher's algorithm gg! 0 Rishabbh2 years agoMy code is causing segmentation error can someone tell mistake in it.string LongestPalindromeSubString(string text){ int n = text.length(); if(n>0) { int max_len=-1; pair<int,int> p1; p1.first=0; p1.second=0; int dp1[n][n]; for(int i=0;i<n;i++) {="" dp1[i][i]="1;" }="" for(int="" inc="1;inc&lt;n;inc++)" {="" for(int="" i="0;i&lt;n-inc;i++)" {="" int="" j="i+inc;" int="" c1,c2,c3="0;" if(text[i]="=text[j])" {="" int="" remain="j-i-1;" if(dp1[i+1][j-1]="=remain||remain==0)" {="" c3="2+remain;" if(c3="">max_len) { max_len=c3; p1.first = i; p1.second = j; } } } c1=dp1[i][j-1]; c2=dp1[i+1][j]; dp1[i][j]=max(c3,max(c1,c2)); } } string ans; for(int i=p1.first;i<=p1.second;i++) ans=ans+text[i]; return ans; } return "";}Reply Open ExternallyShow 0 RepliesLoading... Rishabbh My code is causing segmentation error can someone tell mistake in it. string LongestPalindromeSubString(string text){ int n = text.length(); if(n>0) { int max_len=-1; pair<int,int> p1; p1.first=0; p1.second=0; int dp1[n][n]; for(int i=0;i<n;i++) {="" dp1[i][i]="1;" }="" for(int="" inc="1;inc&lt;n;inc++)" {="" for(int="" i="0;i&lt;n-inc;i++)" {="" int="" j="i+inc;" int="" c1,c2,c3="0;" if(text[i]="=text[j])" {="" int="" remain="j-i-1;" if(dp1[i+1][j-1]="=remain||remain==0)" {="" c3="2+remain;" if(c3="">max_len) { max_len=c3; p1.first = i; p1.second = j; } } } c1=dp1[i][j-1]; c2=dp1[i+1][j]; dp1[i][j]=max(c3,max(c1,c2)); } } string ans; for(int i=p1.first;i<=p1.second;i++) ans=ans+text[i]; return ans; } return "";} 0 Kunwar Sadanand2 years agohttps://ide.geeksforgeeks.o...I'm getting TLE on this code.. anyone help!Reply Open ExternallyShow 0 RepliesLoading... Kunwar Sadanand https://ide.geeksforgeeks.o... I'm getting TLE on this code.. anyone help! 0 joya2 years agosimple solution just submitted with execution time is 0.1sReply Open ExternallyShow 0 RepliesLoading... joya simple solution just submitted with execution time is 0.1s 0 Krishna Swaroop2 years agoWHAT IS THIS??? IT IS SHOWING THE CORRECT OUTPUT AS WRONG.Wrong Answer. !!!Wrong AnswerPossibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:Input:zIts Correct output is:zAnd Your Code's output is:zReply Open ExternallyShow 1 RepliesLoading... Krishna Swaroop WHAT IS THIS??? IT IS SHOWING THE CORRECT OUTPUT AS WRONG. Wrong Answer. !!!Wrong Answer Possibly your code doesn't work correctly for multiple test-cases (TCs). The first test case where your code failed: Input:z Its Correct output is:z And Your Code's output is:z 0 raman mishra2 years agohttps://ide.geeksforgeeks.o...can anyone tell why its showing segmentation faultReply Open ExternallyShow 1 RepliesLoading... raman mishra https://ide.geeksforgeeks.o...can anyone tell why its showing segmentation fault 0 GOWTHAM G2 years agocpp solution:knowledge is to share.....https://ide.geeksforgeeks.o...Reply Open ExternallyShow 0 RepliesLoading... GOWTHAM G cpp solution: knowledge is to share..... https://ide.geeksforgeeks.o... 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": 310, "s": 226, "text": "Given a string, find the longest substring which is palindrome in Linear time O(N)." }, { "code": null, "e": 472, "s": 310, "text": "Input:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The only line of each test case contains a string." }, { "code": null, "e": 649, "s": 472, "text": "Output:\nFor each test case print the Longest Palindromic Substring. If there are multiple such substrings of same length, print the one which appears first in the input string." }, { "code": null, "e": 689, "s": 649, "text": "Constraints:\n1 <= T <= 100\n1 <= N <= 50" }, { "code": null, "e": 739, "s": 689, "text": "Example:\nInput:\n2\nbabcbabcbaccba\nforgeeksskeegfor" }, { "code": null, "e": 768, "s": 739, "text": "Output:\nabcbabcba\ngeeksskeeg" }, { "code": null, "e": 1083, "s": 774, "text": "Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1086, "s": 1083, "text": "+1" }, { "code": null, "e": 1105, "s": 1086, "text": "wxyzpl5 months ago" }, { "code": null, "e": 1118, "s": 1105, "text": "// java code" }, { "code": null, "e": 1258, "s": 1118, "text": " static String LongestPalindromeSubString(String s) { int strLen = 2 * s.length() + 3; char[] sChars = new char[strLen];" }, { "code": null, "e": 1628, "s": 1258, "text": " /* * To ignore special cases at the beginning and end of the array * \"abc\" -> @ # a # b # c # $ * \"\" -> @#$ * \"a\" -> @ # a # $ */ sChars[0] = '@'; sChars[strLen - 1] = '$'; int t = 1; for (char c : s.toCharArray()) { sChars[t++] = '#'; sChars[t++] = c; } sChars[t] = '#';" }, { "code": null, "e": 1938, "s": 1628, "text": " int maxLen = 0; int start = 0; int maxRight = 0; int center = 0; int[] p = new int[strLen]; // i's radius, which not includes i for (int i = 1; i < strLen - 1; i++) { if (i < maxRight) { p[i] = Math.min(maxRight - i, p[2 * center - i]); }" }, { "code": null, "e": 2065, "s": 1938, "text": " // expand center while (sChars[i + p[i] + 1] == sChars[i - p[i] - 1]) { p[i]++; }" }, { "code": null, "e": 2217, "s": 2065, "text": " // update center and its bound if (i + p[i] > maxRight) { center = i; maxRight = i + p[i]; }" }, { "code": null, "e": 2364, "s": 2217, "text": " // update ans if (p[i] > maxLen) { start = (i - p[i] - 1) / 2; maxLen = p[i]; } }" }, { "code": null, "e": 2426, "s": 2364, "text": " return s.substring(start, start + maxLen); }} " }, { "code": null, "e": 2428, "s": 2426, "text": "0" }, { "code": null, "e": 2452, "s": 2428, "text": "tauruas08059 months ago" }, { "code": null, "e": 3279, "s": 2452, "text": "string h=\"#\"; for(int i=0;i<text.size();i++){ h.push_back(text[i]); h.push_back('#'); } int C=-1; int R=-1; int n=h.size(); vector<int>lps(n); int imirror; for(int i=0;i<n;i++){ imirror=2*C-i; if(R>i){ lps[i]=min(R-i,lps[imirror]); } else{ lps[i]=0; } while((i-lps[i]-1)>=0 && (i+lps[i]+1)<n && h[i-lps[i]-1]==h[i+1+lps[i]]){ lps[i]++; } if(i+lps[i]>R){ R=i+lps[i]; C=i; } } int mx=0; int s; for(int i=0;i<n;i++){ if(mx<lps[i]){ s=i; mx=lps[i]; } } int l=s-mx; int r=s+mx; string h2=h.substr(l,r-l+1); string ans=\"\"; for(int i=0;i<h2.size();i++){ if(h2[i]!='#'){ ans.push_back(h2[i]); } } return ans;" }, { "code": null, "e": 3338, "s": 3279, "text": "above code is submitted correctly but below code gives tle" }, { "code": null, "e": 3967, "s": 3340, "text": " string text=s; if(text.size()==1)return text; string s1=\"@\"; for(int i=0;i<text.size();i++) s1=s1+'#'+text[i]; s1+='#';s1+='*'; int c=0,r=0;int lps[s1.size()+1];memset(lps,0,sizeof(lps)); for(int i=1;i<s1.size()-1;i++){ int mi=c-(i-c); if(i<r)lps[i]=min(lps[mi],r-i); while(i+1+lps[i]<s1.size() and i-1-lps[i]>=0 and s1[i+1+lps[i]]==s1[i-1-lps[i]])lps[i]++; if(lps[i]+i>r){ c=i;r=lps[i]+i; } } int mx=0,st=0; for(int i=1;i<s1.size()-1;i++){ if(lps[i]>mx){mx=lps[i];st=i;} } int fi=st-mx+1; int aci=(fi-2)/2; return text.substr(aci,mx); } GFG LOOK INTO MATTER!!!!!" }, { "code": null, "e": 3972, "s": 3969, "text": "-1" }, { "code": null, "e": 4748, "s": 3972, "text": "runtime_terror11 months agoAnyone can help me in my code it show TLE string helper(string& s, int l , int r){ int length = l==r ?-1:0; while(l >= 0 && r < s.length() && s[l] == s[r]){ l-=1; r+=1; length += 2; } return s.substr(1+l,length); } string LongestPalindromeSubString(string s){ string ans = \"\",temp; for(int i = 0 ; i < s.length() ; i++){ temp = helper(s,i,i); if(ans.length() < temp.length()){ ans = temp; } temp = helper(s,i,i+1); if(ans.length() < temp.length()){ ans = temp; } } return ans;}Reply Open ExternallyShow 1 RepliesLoading..." }, { "code": null, "e": 4763, "s": 4748, "text": "runtime_terror" }, { "code": null, "e": 5467, "s": 4763, "text": "Anyone can help me in my code it show TLE string helper(string& s, int l , int r){ int length = l==r ?-1:0; while(l >= 0 && r < s.length() && s[l] == s[r]){ l-=1; r+=1; length += 2; } return s.substr(1+l,length); } string LongestPalindromeSubString(string s){ string ans = \"\",temp; for(int i = 0 ; i < s.length() ; i++){ temp = helper(s,i,i); if(ans.length() < temp.length()){ ans = temp; } temp = helper(s,i,i+1); if(ans.length() < temp.length()){ ans = temp; } } return ans;}" }, { "code": null, "e": 5469, "s": 5467, "text": "0" }, { "code": null, "e": 5570, "s": 5469, "text": "Saarth Vikram Jhaveri1 year agoManacher's algorithm gg!Reply Open ExternallyShow 1 RepliesLoading..." }, { "code": null, "e": 5592, "s": 5570, "text": "Saarth Vikram Jhaveri" }, { "code": null, "e": 5617, "s": 5592, "text": "Manacher's algorithm gg!" }, { "code": null, "e": 5619, "s": 5617, "text": "0" }, { "code": null, "e": 6722, "s": 5619, "text": "Rishabbh2 years agoMy code is causing segmentation error can someone tell mistake in it.string LongestPalindromeSubString(string text){ int n = text.length(); if(n>0) { int max_len=-1; pair<int,int> p1; p1.first=0; p1.second=0; int dp1[n][n]; for(int i=0;i<n;i++) {=\"\" dp1[i][i]=\"1;\" }=\"\" for(int=\"\" inc=\"1;inc&lt;n;inc++)\" {=\"\" for(int=\"\" i=\"0;i&lt;n-inc;i++)\" {=\"\" int=\"\" j=\"i+inc;\" int=\"\" c1,c2,c3=\"0;\" if(text[i]=\"=text[j])\" {=\"\" int=\"\" remain=\"j-i-1;\" if(dp1[i+1][j-1]=\"=remain||remain==0)\" {=\"\" c3=\"2+remain;\" if(c3=\"\">max_len) { max_len=c3; p1.first = i; p1.second = j; } } } c1=dp1[i][j-1]; c2=dp1[i+1][j]; dp1[i][j]=max(c3,max(c1,c2)); } } string ans; for(int i=p1.first;i<=p1.second;i++) ans=ans+text[i]; return ans; } return \"\";}Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 6731, "s": 6722, "text": "Rishabbh" }, { "code": null, "e": 6801, "s": 6731, "text": "My code is causing segmentation error can someone tell mistake in it." }, { "code": null, "e": 6849, "s": 6801, "text": "string LongestPalindromeSubString(string text){" }, { "code": null, "e": 7757, "s": 6849, "text": " int n = text.length(); if(n>0) { int max_len=-1; pair<int,int> p1; p1.first=0; p1.second=0; int dp1[n][n]; for(int i=0;i<n;i++) {=\"\" dp1[i][i]=\"1;\" }=\"\" for(int=\"\" inc=\"1;inc&lt;n;inc++)\" {=\"\" for(int=\"\" i=\"0;i&lt;n-inc;i++)\" {=\"\" int=\"\" j=\"i+inc;\" int=\"\" c1,c2,c3=\"0;\" if(text[i]=\"=text[j])\" {=\"\" int=\"\" remain=\"j-i-1;\" if(dp1[i+1][j-1]=\"=remain||remain==0)\" {=\"\" c3=\"2+remain;\" if(c3=\"\">max_len) { max_len=c3; p1.first = i; p1.second = j; } } } c1=dp1[i][j-1]; c2=dp1[i+1][j]; dp1[i][j]=max(c3,max(c1,c2)); } } string ans; for(int i=p1.first;i<=p1.second;i++) ans=ans+text[i]; return ans; }" }, { "code": null, "e": 7773, "s": 7757, "text": " return \"\";}" }, { "code": null, "e": 7775, "s": 7773, "text": "0" }, { "code": null, "e": 7920, "s": 7775, "text": "Kunwar Sadanand2 years agohttps://ide.geeksforgeeks.o...I'm getting TLE on this code.. anyone help!Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 7936, "s": 7920, "text": "Kunwar Sadanand" }, { "code": null, "e": 7967, "s": 7936, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 8011, "s": 7967, "text": "I'm getting TLE on this code.. anyone help!" }, { "code": null, "e": 8013, "s": 8011, "text": "0" }, { "code": null, "e": 8133, "s": 8013, "text": "joya2 years agosimple solution just submitted with execution time is 0.1sReply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 8138, "s": 8133, "text": "joya" }, { "code": null, "e": 8198, "s": 8138, "text": "simple solution just submitted with execution time is 0.1s" }, { "code": null, "e": 8200, "s": 8198, "text": "0" }, { "code": null, "e": 8531, "s": 8200, "text": "Krishna Swaroop2 years agoWHAT IS THIS??? IT IS SHOWING THE CORRECT OUTPUT AS WRONG.Wrong Answer. !!!Wrong AnswerPossibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:Input:zIts Correct output is:zAnd Your Code's output is:zReply Open ExternallyShow 1 RepliesLoading..." }, { "code": null, "e": 8547, "s": 8531, "text": "Krishna Swaroop" }, { "code": null, "e": 8606, "s": 8547, "text": "WHAT IS THIS??? IT IS SHOWING THE CORRECT OUTPUT AS WRONG." }, { "code": null, "e": 8636, "s": 8606, "text": "Wrong Answer. !!!Wrong Answer" }, { "code": null, "e": 8709, "s": 8636, "text": "Possibly your code doesn't work correctly for multiple test-cases (TCs)." }, { "code": null, "e": 8753, "s": 8709, "text": "The first test case where your code failed:" }, { "code": null, "e": 8761, "s": 8753, "text": "Input:z" }, { "code": null, "e": 8785, "s": 8761, "text": "Its Correct output is:z" }, { "code": null, "e": 8813, "s": 8785, "text": "And Your Code's output is:z" }, { "code": null, "e": 8815, "s": 8813, "text": "0" }, { "code": null, "e": 8964, "s": 8815, "text": "raman mishra2 years agohttps://ide.geeksforgeeks.o...can anyone tell why its showing segmentation faultReply Open ExternallyShow 1 RepliesLoading..." }, { "code": null, "e": 8977, "s": 8964, "text": "raman mishra" }, { "code": null, "e": 9058, "s": 8977, "text": "https://ide.geeksforgeeks.o...can anyone tell why its showing segmentation fault" }, { "code": null, "e": 9060, "s": 9058, "text": "0" }, { "code": null, "e": 9195, "s": 9060, "text": "GOWTHAM G2 years agocpp solution:knowledge is to share.....https://ide.geeksforgeeks.o...Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 9205, "s": 9195, "text": "GOWTHAM G" }, { "code": null, "e": 9219, "s": 9205, "text": "cpp solution:" }, { "code": null, "e": 9246, "s": 9219, "text": "knowledge is to share....." }, { "code": null, "e": 9277, "s": 9246, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 9423, "s": 9277, "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": 9459, "s": 9423, "text": " Login to access your submissions. " }, { "code": null, "e": 9469, "s": 9459, "text": "\nProblem\n" }, { "code": null, "e": 9479, "s": 9469, "text": "\nContest\n" }, { "code": null, "e": 9542, "s": 9479, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9727, "s": 9542, "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": 10011, "s": 9727, "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": 10157, "s": 10011, "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": 10234, "s": 10157, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 10275, "s": 10234, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 10303, "s": 10275, "text": "Disable browser extensions." }, { "code": null, "e": 10374, "s": 10303, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 10561, "s": 10374, "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." } ]
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
23 Aug, 2021 In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, “%d-%b-%Y-%H:%M:%S”) strftime() is used to convert DateTime into required timestamp format Syntax: datetime.strftime(“%Y-%m-%d-%H:%M:%S”) Here, &Y means year %m means month %d means day %H means hours %M means minutes %S means seconds. First the take DateTime timestamp as a String. Then, convert it into DateTime using strptime(). Now, convert into the necessary format of DateTime using strftime Example 1: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format Python3 # import datetime modulefrom datetime import datetime # consider date in string formatmy_date = "30-May-2020-15:59:02" # convert datetime string into date,month,day and# hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) Output '2020-05-30-15:59:02' Example 2: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format Python3 # import datetime modulefrom datetime import datetime # consider date in string formatmy_date = "30-May-2020-15:59:02" # convert datetime string into date,month,day # and hours:minutes:and seconds format using# strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) # consider date in string formatmy_date = "04-Jan-2021-02:45:12" # convert datetime string into date,month,day # and hours:minutes:and seconds format using # strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) # consider date in string formatmy_date = "23-May-2020-15:59:02" # convert datetime string into date,month,day and # hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) 2020-05-30-15:59:02 2021-01-04-02:45:12 2020-05-23-15:59:02 Picked Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 183, "s": 28, "text": "In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used." }, { "code": null, "e": 303, "s": 183, "text": "strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds" }, { "code": null, "e": 311, "s": 303, "text": "Syntax:" }, { "code": null, "e": 359, "s": 311, "text": "datetime.strptime(my_date, “%d-%b-%Y-%H:%M:%S”)" }, { "code": null, "e": 429, "s": 359, "text": "strftime() is used to convert DateTime into required timestamp format" }, { "code": null, "e": 437, "s": 429, "text": "Syntax:" }, { "code": null, "e": 476, "s": 437, "text": "datetime.strftime(“%Y-%m-%d-%H:%M:%S”)" }, { "code": null, "e": 482, "s": 476, "text": "Here," }, { "code": null, "e": 496, "s": 482, "text": "&Y means year" }, { "code": null, "e": 512, "s": 496, "text": "%m means month" }, { "code": null, "e": 525, "s": 512, "text": "%d means day" }, { "code": null, "e": 540, "s": 525, "text": "%H means hours" }, { "code": null, "e": 557, "s": 540, "text": "%M means minutes" }, { "code": null, "e": 575, "s": 557, "text": "%S means seconds." }, { "code": null, "e": 737, "s": 575, "text": "First the take DateTime timestamp as a String. Then, convert it into DateTime using strptime(). Now, convert into the necessary format of DateTime using strftime" }, { "code": null, "e": 820, "s": 737, "text": "Example 1: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format" }, { "code": null, "e": 828, "s": 820, "text": "Python3" }, { "code": "# import datetime modulefrom datetime import datetime # consider date in string formatmy_date = \"30-May-2020-15:59:02\" # convert datetime string into date,month,day and# hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\"))", "e": 1210, "s": 828, "text": null }, { "code": null, "e": 1217, "s": 1210, "text": "Output" }, { "code": null, "e": 1239, "s": 1217, "text": "'2020-05-30-15:59:02'" }, { "code": null, "e": 1322, "s": 1239, "text": "Example 2: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format" }, { "code": null, "e": 1330, "s": 1322, "text": "Python3" }, { "code": "# import datetime modulefrom datetime import datetime # consider date in string formatmy_date = \"30-May-2020-15:59:02\" # convert datetime string into date,month,day # and hours:minutes:and seconds format using# strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\")) # consider date in string formatmy_date = \"04-Jan-2021-02:45:12\" # convert datetime string into date,month,day # and hours:minutes:and seconds format using # strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\")) # consider date in string formatmy_date = \"23-May-2020-15:59:02\" # convert datetime string into date,month,day and # hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\"))", "e": 2376, "s": 1330, "text": null }, { "code": null, "e": 2437, "s": 2376, "text": "2020-05-30-15:59:02\n2021-01-04-02:45:12\n2020-05-23-15:59:02\n" }, { "code": null, "e": 2444, "s": 2437, "text": "Picked" }, { "code": null, "e": 2460, "s": 2444, "text": "Python-datetime" }, { "code": null, "e": 2467, "s": 2460, "text": "Python" } ]
p5.js | resizeCanvas() Function
17 Jan, 2020 The resizeCanvas() function is used to resize the canvas to the height and width given as parameters. The canvas is immediately redrawn after the resize takes place unless the optional ‘noRedraw’ parameter is set to true. Syntax: resizeCanvas(w, h, [noRedraw]) Parameters: This function accepts three parameters as mentioned above and described below: w: It is a number representing the width of the new canvas. h: It is a number representing the height of the new canvas. noRedraw: It is a boolean value which specifies if the canvas is immediately redrawn when resized. Below example illustrates the resizeCanvas() function in p5.js: Example 1: In this example, we fixed the increase size. function setup() { createCanvas(200, 200); textSize(16); rect(0, 0, height, width); background('green'); text("This is the canvas area", 20, 80); text("Canvas height: " + height, 25, 100); text("Canvas width: " + width, 25, 120);} function mouseClicked() { resizeCanvas(300, 300, true); rect(0, 0, height, width); background('green'); text("This is the canvas area", 50, 130); text("Canvas height: " + height, 50, 150); text("Canvas width: " + width, 50, 170);} Output:Example 2: In this example, size depends on the click position. function setup() { createCanvas(200, 200); textSize(16); rect(0, 0, height, width); background('green'); text("Press anywhere to resize", 10, 20); text("Canvas height: " + height, 10, 40); text("Canvas width: " + width, 10, 60);} function mouseClicked(event) { // resize canvas to the resizeCanvas(event.x, event.y); rect(0, 0, height, width); background('green'); text("Press anywhere to resize", 10, 20); text("Canvas height: " + height, 10, 40); text("Canvas width: " + width, 10, 60);} Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/resizeCanvas JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2020" }, { "code": null, "e": 250, "s": 28, "text": "The resizeCanvas() function is used to resize the canvas to the height and width given as parameters. The canvas is immediately redrawn after the resize takes place unless the optional ‘noRedraw’ parameter is set to true." }, { "code": null, "e": 258, "s": 250, "text": "Syntax:" }, { "code": null, "e": 289, "s": 258, "text": "resizeCanvas(w, h, [noRedraw])" }, { "code": null, "e": 380, "s": 289, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 440, "s": 380, "text": "w: It is a number representing the width of the new canvas." }, { "code": null, "e": 501, "s": 440, "text": "h: It is a number representing the height of the new canvas." }, { "code": null, "e": 600, "s": 501, "text": "noRedraw: It is a boolean value which specifies if the canvas is immediately redrawn when resized." }, { "code": null, "e": 664, "s": 600, "text": "Below example illustrates the resizeCanvas() function in p5.js:" }, { "code": null, "e": 720, "s": 664, "text": "Example 1: In this example, we fixed the increase size." }, { "code": "function setup() { createCanvas(200, 200); textSize(16); rect(0, 0, height, width); background('green'); text(\"This is the canvas area\", 20, 80); text(\"Canvas height: \" + height, 25, 100); text(\"Canvas width: \" + width, 25, 120);} function mouseClicked() { resizeCanvas(300, 300, true); rect(0, 0, height, width); background('green'); text(\"This is the canvas area\", 50, 130); text(\"Canvas height: \" + height, 50, 150); text(\"Canvas width: \" + width, 50, 170);}", "e": 1200, "s": 720, "text": null }, { "code": null, "e": 1271, "s": 1200, "text": "Output:Example 2: In this example, size depends on the click position." }, { "code": "function setup() { createCanvas(200, 200); textSize(16); rect(0, 0, height, width); background('green'); text(\"Press anywhere to resize\", 10, 20); text(\"Canvas height: \" + height, 10, 40); text(\"Canvas width: \" + width, 10, 60);} function mouseClicked(event) { // resize canvas to the resizeCanvas(event.x, event.y); rect(0, 0, height, width); background('green'); text(\"Press anywhere to resize\", 10, 20); text(\"Canvas height: \" + height, 10, 40); text(\"Canvas width: \" + width, 10, 60);}", "e": 1780, "s": 1271, "text": null }, { "code": null, "e": 1788, "s": 1780, "text": "Output:" }, { "code": null, "e": 1925, "s": 1788, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 1981, "s": 1925, "text": "Reference: https://p5js.org/reference/#/p5/resizeCanvas" }, { "code": null, "e": 1998, "s": 1981, "text": "JavaScript-p5.js" }, { "code": null, "e": 2009, "s": 1998, "text": "JavaScript" }, { "code": null, "e": 2026, "s": 2009, "text": "Web Technologies" } ]
numpy.vstack() in python
06 Jan, 2019 numpy.vstack() function is used to stack the sequence of input arrays vertically to make a single array. Syntax : numpy.vstack(tup) Parameters :tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the first axis. Return : [stacked ndarray] The stacked array of the input arrays. Code #1 : # Python program explaining# vstack() function import numpy as geek # input arrayin_arr1 = geek.array([ 1, 2, 3] )print ("1st Input array : \n", in_arr1) in_arr2 = geek.array([ 4, 5, 6] )print ("2nd Input array : \n", in_arr2) # Stacking the two arrays verticallyout_arr = geek.vstack((in_arr1, in_arr2))print ("Output vertically stacked array:\n ", out_arr) 1st Input array : [1 2 3] 2nd Input array : [4 5 6] Output vertically stacked array: [[1 2 3] [4 5 6]] Code #2 : # Python program explaining# vstack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print ("1st Input array : \n", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print ("2nd Input array : \n", in_arr2) # Stacking the two arrays verticallyout_arr = geek.vstack((in_arr1, in_arr2))print ("Output stacked array :\n ", out_arr) 1st Input array : [[ 1 2 3] [-1 -2 -3]] 2nd Input array : [[ 4 5 6] [-4 -5 -6]] Output stacked array : [[ 1 2 3] [-1 -2 -3] [ 4 5 6] [-4 -5 -6]] Python numpy-arrayManipulation Python-numpy 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 Enumerate() in Python 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": 52, "s": 24, "text": "\n06 Jan, 2019" }, { "code": null, "e": 157, "s": 52, "text": "numpy.vstack() function is used to stack the sequence of input arrays vertically to make a single array." }, { "code": null, "e": 184, "s": 157, "text": "Syntax : numpy.vstack(tup)" }, { "code": null, "e": 330, "s": 184, "text": "Parameters :tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the first axis." }, { "code": null, "e": 396, "s": 330, "text": "Return : [stacked ndarray] The stacked array of the input arrays." }, { "code": null, "e": 406, "s": 396, "text": "Code #1 :" }, { "code": "# Python program explaining# vstack() function import numpy as geek # input arrayin_arr1 = geek.array([ 1, 2, 3] )print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array([ 4, 5, 6] )print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays verticallyout_arr = geek.vstack((in_arr1, in_arr2))print (\"Output vertically stacked array:\\n \", out_arr)", "e": 771, "s": 406, "text": null }, { "code": null, "e": 882, "s": 771, "text": "1st Input array : \n [1 2 3]\n2nd Input array : \n [4 5 6]\nOutput vertically stacked array:\n [[1 2 3]\n [4 5 6]]\n" }, { "code": null, "e": 893, "s": 882, "text": " Code #2 :" }, { "code": "# Python program explaining# vstack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays verticallyout_arr = geek.vstack((in_arr1, in_arr2))print (\"Output stacked array :\\n \", out_arr)", "e": 1282, "s": 893, "text": null }, { "code": null, "e": 1447, "s": 1282, "text": "1st Input array : \n [[ 1 2 3]\n [-1 -2 -3]]\n2nd Input array : \n [[ 4 5 6]\n [-4 -5 -6]]\nOutput stacked array :\n [[ 1 2 3]\n [-1 -2 -3]\n [ 4 5 6]\n [-4 -5 -6]]\n" }, { "code": null, "e": 1478, "s": 1447, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 1491, "s": 1478, "text": "Python-numpy" }, { "code": null, "e": 1498, "s": 1491, "text": "Python" }, { "code": null, "e": 1596, "s": 1498, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1614, "s": 1596, "text": "Python Dictionary" }, { "code": null, "e": 1656, "s": 1614, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1678, "s": 1656, "text": "Enumerate() in Python" }, { "code": null, "e": 1710, "s": 1678, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1739, "s": 1710, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1766, "s": 1739, "text": "Python Classes and Objects" }, { "code": null, "e": 1787, "s": 1766, "text": "Python OOPs Concepts" }, { "code": null, "e": 1823, "s": 1787, "text": "Convert integer to string in Python" }, { "code": null, "e": 1846, "s": 1823, "text": "Introduction To PYTHON" } ]
Linux Kernel Module Programming: Hello World Program
30 Jan, 2019 Kernel modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system.Custom codes can be added to Linux kernels via two methods. The basic way is to add the code to the kernel source tree and recompile the kernel. A more efficient way is to do this is by adding code to the kernel while it is running. This process is called loading the module, where module refers to the code that we want to add to the kernel. Since we are loading these codes at runtime and they are not part of the official Linux kernel, these are called loadable kernel module(LKM), which is different from the “base kernel”. Base kernel is located in /boot directory and is always loaded when we boot our machine whereas LKMs are loaded after the base kernel is already loaded. Nonetheless, these LKM are very much part of our kernel and they communicate with base kernel to complete their functions. LKMs can perform a variety of task, but basically they come under three main categories, device driver, filesystem driver and System calls. So what advantage do LKMs offer?One major advantage they have is that we don’t need to keep rebuilding the kernel every time we add a new device or if we upgrade an old device. This saves time and also helps in keeping our base kernel error free. A useful rule of thumb is that we should not change our base kernel once we have a working base kernel.Also, it helps in diagnosing system problems. For example, assume we have added a module to the base kernel(i.e., we have modified our base kernel by recompiling it) and the module has a bug in it. This will cause error in system boot and we will never know which part of the kernel is causing problems. Whereas if we load the module at runtime and it causes problems, we will immediately know the issue and we can unload the module until we fix it.LKMs are very flexible, in the sense that they can be loaded and unloaded with a single line of command. This helps in saving memory as we load the LKM only when we need them. Moreover, they are not slower than base kernel because calling either one of them is simply loading code from a different part of memory. **Warning: LKMs are not user space programs. They are part of the kernel. They have free run of the system and can easily crash it. So now that we have established the use loadable kernel modules, we are going to write a hello world kernel module. That will print a message when we load the module and an exit message when we unload the module. Code: /** * @file hello.c * @author Akshat Sinha * @date 10 Sept 2016 * @version 0.1 * @brief An introductory "Hello World!" loadable kernel * module (LKM) that can display a message in the /var/log/kern.log * file when the module is loaded and removed. The module can accept * an argument when it is loaded -- the name, which appears in the * kernel log files.*/#include <linux/module.h> /* Needed by all modules */#include <linux/kernel.h> /* Needed for KERN_INFO */#include <linux/init.h> /* Needed for the macros */ ///< The license type -- this affects runtime behaviorMODULE_LICENSE("GPL"); ///< The author -- visible when you use modinfoMODULE_AUTHOR("Akshat Sinha"); ///< The description -- see modinfoMODULE_DESCRIPTION("A simple Hello world LKM!"); ///< The version of the moduleMODULE_VERSION("0.1"); static int __init hello_start(void){ printk(KERN_INFO "Loading hello module...\n"); printk(KERN_INFO "Hello world\n"); return 0;} static void __exit hello_end(void){ printk(KERN_INFO "Goodbye Mr.\n");} module_init(hello_start);module_exit(hello_end); Explanation for the above code:Kernel modules must have at least two functions: a “start” (initialization) function called init_module() which is called when the module is insmoded into the kernel, and an “end” (cleanup) function called cleanup_module() which is called just before it is rmmoded. Actually, things have changed starting with kernel 2.3.13. You can now use whatever name you like for the start and end functions of a module. In fact, the new method is the preferred method. However, many people still use init_module() and cleanup_module() for their start and end functions. In this code we have used hello_start() as init function and hello_end() as cleanup function.Another thing that you might have noticed is that instead of printf() function we have used printk(). This is because module will not print anything on the console but it will log the message in /var/log/kern.log. Hence it is used to debug kernel modules. Moreover, there are eight possible loglevel strings, defined in the header , that are required while using printk(). We have list them in order of decreasing severity: KERN_EMERG: Used for emergency messages, usually those that precede a crash. KERN_ALERT: A situation requiring immediate action. KERN_CRIT: Critical conditions, often related to serious hardware or software failures. KERN_ERR: Used to report error conditions; device drivers often use KERN_ERR to report hardware difficulties. KERN_WARNING: Warnings about problematic situations that do not, in themselves, create serious problems with the system. KERN_NOTICE: Situations that are normal, but still worthy of note. A number of security-related conditions are reported at this level. KERN_INFO: Informational messages. Many drivers print information about the hardware they find at startup time at this level. KERN_DEBUG: Used for debugging messages. We have used KERN_INFO to print the message. Preparing the system to run the code:The system must be prepared to build kernel code, and to do this you must have the Linux headers installed on your device. On a typical Linux desktop machine you can use your package manager to locate the correct package to install. For example, under 64-bit Debian you can use: akshat@gfg:~$ sudo apt-get install build-essential linux-headers-$(uname -r) Makefile to compile the source code: obj-m = hello.o all: make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean **Note: Don’t forget the tab spaces in Makefile Compiling and loading the module:Run the make command to compile the source code. Then use insmod to load the module. akshat@gfg:~$ make make -C /lib/modules/4.2.0-42-generic/build/ M=/home/akshat/Documents/hello-module modules make[1]: Entering directory `/usr/src/linux-headers-4.2.0-42-generic' CC [M] /home/akshat/Documents/hello-module/hello.o Building modules, stage 2. MODPOST 1 modules CC /home/akshat/Documents/hello-module/hello.mod.o LD [M] /home/akshat/Documents/hello-module/hello.ko make[1]: Leaving directory `/usr/src/linux-headers-4.2.0-42-generic' Now we will use insmod to load the hello.ko object. akshat@gfg:~$ sudo insmod hello.ko Testing the module:You can get information about the module using the modinfo command, which will identify the description, author and any module parameters that are defined: akshat@gfg:~$ modinfo hello.ko filename: /home/akshat/Documents/hello-module/hello.ko version: 0.1 description: A simple Hello world LKM author: Akshat Sinha license: GPL srcversion: 2F2B1B95DA1F08AC18B09BC depends: vermagic: 4.2.0-42-generic SMP mod_unload modversions To see the message, we need to read the kern.log in /var/log directory. akshat@gfg:~$ tail /var/log/kern.log ... ... Sep 10 17:43:39 akshat-gfg kernel: [26380.327886] Hello world To unload the module, we run rmmod: akshat@gfg:~$ sudo rmmod hello Now run the tail command to get the exit message. akshat@gfg:~$ tail /var/log/kern.log ... Sep 10 17:43:39 akshat-gfg kernel: [26380.327886] Hello world Sep 10 17:45:42 akshat-gfg kernel: [26503.773982] Goodbye Mr. This article is contributed by Akshat Sinha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples 'crontab' in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples TCP Server-Client implementation in C Docker - COPY Instruction UDP Server-Client implementation in C
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jan, 2019" }, { "code": null, "e": 291, "s": 54, "text": "Kernel modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system.Custom codes can be added to Linux kernels via two methods." }, { "code": null, "e": 376, "s": 291, "text": "The basic way is to add the code to the kernel source tree and recompile the kernel." }, { "code": null, "e": 574, "s": 376, "text": "A more efficient way is to do this is by adding code to the kernel while it is running. This process is called loading the module, where module refers to the code that we want to add to the kernel." }, { "code": null, "e": 1035, "s": 574, "text": "Since we are loading these codes at runtime and they are not part of the official Linux kernel, these are called loadable kernel module(LKM), which is different from the “base kernel”. Base kernel is located in /boot directory and is always loaded when we boot our machine whereas LKMs are loaded after the base kernel is already loaded. Nonetheless, these LKM are very much part of our kernel and they communicate with base kernel to complete their functions." }, { "code": null, "e": 1124, "s": 1035, "text": "LKMs can perform a variety of task, but basically they come under three main categories," }, { "code": null, "e": 1139, "s": 1124, "text": "device driver," }, { "code": null, "e": 1161, "s": 1139, "text": "filesystem driver and" }, { "code": null, "e": 1175, "s": 1161, "text": "System calls." }, { "code": null, "e": 2288, "s": 1175, "text": "So what advantage do LKMs offer?One major advantage they have is that we don’t need to keep rebuilding the kernel every time we add a new device or if we upgrade an old device. This saves time and also helps in keeping our base kernel error free. A useful rule of thumb is that we should not change our base kernel once we have a working base kernel.Also, it helps in diagnosing system problems. For example, assume we have added a module to the base kernel(i.e., we have modified our base kernel by recompiling it) and the module has a bug in it. This will cause error in system boot and we will never know which part of the kernel is causing problems. Whereas if we load the module at runtime and it causes problems, we will immediately know the issue and we can unload the module until we fix it.LKMs are very flexible, in the sense that they can be loaded and unloaded with a single line of command. This helps in saving memory as we load the LKM only when we need them. Moreover, they are not slower than base kernel because calling either one of them is simply loading code from a different part of memory." }, { "code": null, "e": 2420, "s": 2288, "text": "**Warning: LKMs are not user space programs. They are part of the kernel. They have free run of the system and can easily crash it." }, { "code": null, "e": 2633, "s": 2420, "text": "So now that we have established the use loadable kernel modules, we are going to write a hello world kernel module. That will print a message when we load the module and an exit message when we unload the module." }, { "code": null, "e": 2639, "s": 2633, "text": "Code:" }, { "code": "/** * @file hello.c * @author Akshat Sinha * @date 10 Sept 2016 * @version 0.1 * @brief An introductory \"Hello World!\" loadable kernel * module (LKM) that can display a message in the /var/log/kern.log * file when the module is loaded and removed. The module can accept * an argument when it is loaded -- the name, which appears in the * kernel log files.*/#include <linux/module.h> /* Needed by all modules */#include <linux/kernel.h> /* Needed for KERN_INFO */#include <linux/init.h> /* Needed for the macros */ ///< The license type -- this affects runtime behaviorMODULE_LICENSE(\"GPL\"); ///< The author -- visible when you use modinfoMODULE_AUTHOR(\"Akshat Sinha\"); ///< The description -- see modinfoMODULE_DESCRIPTION(\"A simple Hello world LKM!\"); ///< The version of the moduleMODULE_VERSION(\"0.1\"); static int __init hello_start(void){ printk(KERN_INFO \"Loading hello module...\\n\"); printk(KERN_INFO \"Hello world\\n\"); return 0;} static void __exit hello_end(void){ printk(KERN_INFO \"Goodbye Mr.\\n\");} module_init(hello_start);module_exit(hello_end);", "e": 3741, "s": 2639, "text": null }, { "code": null, "e": 4848, "s": 3741, "text": "Explanation for the above code:Kernel modules must have at least two functions: a “start” (initialization) function called init_module() which is called when the module is insmoded into the kernel, and an “end” (cleanup) function called cleanup_module() which is called just before it is rmmoded. Actually, things have changed starting with kernel 2.3.13. You can now use whatever name you like for the start and end functions of a module. In fact, the new method is the preferred method. However, many people still use init_module() and cleanup_module() for their start and end functions. In this code we have used hello_start() as init function and hello_end() as cleanup function.Another thing that you might have noticed is that instead of printf() function we have used printk(). This is because module will not print anything on the console but it will log the message in /var/log/kern.log. Hence it is used to debug kernel modules. Moreover, there are eight possible loglevel strings, defined in the header , that are required while using printk(). We have list them in order of decreasing severity:" }, { "code": null, "e": 4925, "s": 4848, "text": "KERN_EMERG: Used for emergency messages, usually those that precede a crash." }, { "code": null, "e": 4977, "s": 4925, "text": "KERN_ALERT: A situation requiring immediate action." }, { "code": null, "e": 5065, "s": 4977, "text": "KERN_CRIT: Critical conditions, often related to serious hardware or software failures." }, { "code": null, "e": 5175, "s": 5065, "text": "KERN_ERR: Used to report error conditions; device drivers often use KERN_ERR to report hardware difficulties." }, { "code": null, "e": 5296, "s": 5175, "text": "KERN_WARNING: Warnings about problematic situations that do not, in themselves, create serious problems with the system." }, { "code": null, "e": 5431, "s": 5296, "text": "KERN_NOTICE: Situations that are normal, but still worthy of note. A number of security-related conditions are reported at this level." }, { "code": null, "e": 5557, "s": 5431, "text": "KERN_INFO: Informational messages. Many drivers print information about the hardware they find at startup time at this level." }, { "code": null, "e": 5598, "s": 5557, "text": "KERN_DEBUG: Used for debugging messages." }, { "code": null, "e": 5643, "s": 5598, "text": "We have used KERN_INFO to print the message." }, { "code": null, "e": 5959, "s": 5643, "text": "Preparing the system to run the code:The system must be prepared to build kernel code, and to do this you must have the Linux headers installed on your device. On a typical Linux desktop machine you can use your package manager to locate the correct package to install. For example, under 64-bit Debian you can use:" }, { "code": null, "e": 6037, "s": 5959, "text": "akshat@gfg:~$ sudo apt-get install build-essential linux-headers-$(uname -r)\n" }, { "code": null, "e": 6074, "s": 6037, "text": "Makefile to compile the source code:" }, { "code": null, "e": 6242, "s": 6074, "text": "obj-m = hello.o\nall:\n make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules\nclean:\n make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean\n" }, { "code": null, "e": 6290, "s": 6242, "text": "**Note: Don’t forget the tab spaces in Makefile" }, { "code": null, "e": 6408, "s": 6290, "text": "Compiling and loading the module:Run the make command to compile the source code. Then use insmod to load the module." }, { "code": null, "e": 6874, "s": 6408, "text": "akshat@gfg:~$ make\nmake -C /lib/modules/4.2.0-42-generic/build/ M=/home/akshat/Documents/hello-module modules\nmake[1]: Entering directory `/usr/src/linux-headers-4.2.0-42-generic'\n CC [M] /home/akshat/Documents/hello-module/hello.o\n Building modules, stage 2.\n MODPOST 1 modules\n CC /home/akshat/Documents/hello-module/hello.mod.o\n LD [M] /home/akshat/Documents/hello-module/hello.ko\nmake[1]: Leaving directory `/usr/src/linux-headers-4.2.0-42-generic'\n" }, { "code": null, "e": 6926, "s": 6874, "text": "Now we will use insmod to load the hello.ko object." }, { "code": null, "e": 6962, "s": 6926, "text": "akshat@gfg:~$ sudo insmod hello.ko\n" }, { "code": null, "e": 7137, "s": 6962, "text": "Testing the module:You can get information about the module using the modinfo command, which will identify the description, author and any module parameters that are defined:" }, { "code": null, "e": 7457, "s": 7137, "text": "akshat@gfg:~$ modinfo hello.ko\nfilename: /home/akshat/Documents/hello-module/hello.ko\nversion: 0.1\ndescription: A simple Hello world LKM\nauthor: Akshat Sinha\nlicense: GPL\nsrcversion: 2F2B1B95DA1F08AC18B09BC\ndepends: \nvermagic: 4.2.0-42-generic SMP mod_unload modversions\n" }, { "code": null, "e": 7529, "s": 7457, "text": "To see the message, we need to read the kern.log in /var/log directory." }, { "code": null, "e": 7919, "s": 7529, "text": "akshat@gfg:~$ tail /var/log/kern.log\n...\n...\nSep 10 17:43:39 akshat-gfg kernel: [26380.327886] Hello world\nTo unload the module, we run rmmod:\nakshat@gfg:~$ sudo rmmod hello\nNow run the tail command to get the exit message.\nakshat@gfg:~$ tail /var/log/kern.log\n...\nSep 10 17:43:39 akshat-gfg kernel: [26380.327886] Hello world\nSep 10 17:45:42 akshat-gfg kernel: [26503.773982] Goodbye Mr.\n" }, { "code": null, "e": 8219, "s": 7919, "text": "This article is contributed by Akshat Sinha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8344, "s": 8219, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8355, "s": 8344, "text": "Linux-Unix" }, { "code": null, "e": 8453, "s": 8355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8488, "s": 8453, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 8523, "s": 8488, "text": "tar command in Linux with examples" }, { "code": null, "e": 8559, "s": 8523, "text": "curl command in Linux with Examples" }, { "code": null, "e": 8600, "s": 8559, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 8633, "s": 8600, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 8671, "s": 8633, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 8707, "s": 8671, "text": "Tail command in Linux with examples" }, { "code": null, "e": 8745, "s": 8707, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 8771, "s": 8745, "text": "Docker - COPY Instruction" } ]
HTML | <link> rel Attribute
06 Jun, 2022 The HTML rel attribute is used to specify the relationship between the current and the linked document. It is used only when href attribute present.Syntax: <link rel="value"> Attribute Values alternate: It specifies the alternative link of the document(i.e. print page, translated or mirror). author: It define author of the link dns-prefetch: It Specifies that the browser should preemptively perform DNS resolution for the target resource’s origin help: It specifies a link to a help document. Example: <link rel=”help” href=”/help/”> icon: It specifies import icon in a given document license: It specifies a link to copyright information for the document next: It provide the link of next document in series pingback: It specifies the address of the pingback serve preconnect: It specifies the target should be preemptively to the origin resource prefetch: It specifies that the target document should be cached. preload: It specifies that the browser must preemptively fetch and cache prerender: It specifies that the browser should load prev: It specifies the previous document in a selection search: It specifies the search tool for the document. stylesheet: It Imports a style sheet Example of HTML link rel Attribute html <!DOCTYPE html><html> <head> <link rel="stylesheet" type="text/css" href="index_screen.css"> <link rel="stylesheet" type="text/css" href="index_print.css"></head> <body> <center> <h1>GeeksforGeeks</h1> <p><a href="https://ide.geeksforgeeks.org/tryit.php" target="_blank"> Click here </a> </center></body> </html> Output: Supported Browsers: The browsers supported by HTML rel Attribute are listed below Google Chrome 1 Edge 12 Firefox 1.0 Apple Safari Opera Internet Explorer simmytarika5 kumargaurav97520 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2022" }, { "code": null, "e": 186, "s": 28, "text": "The HTML rel attribute is used to specify the relationship between the current and the linked document. It is used only when href attribute present.Syntax: " }, { "code": null, "e": 205, "s": 186, "text": "<link rel=\"value\">" }, { "code": null, "e": 224, "s": 205, "text": "Attribute Values " }, { "code": null, "e": 325, "s": 224, "text": "alternate: It specifies the alternative link of the document(i.e. print page, translated or mirror)." }, { "code": null, "e": 362, "s": 325, "text": "author: It define author of the link" }, { "code": null, "e": 482, "s": 362, "text": "dns-prefetch: It Specifies that the browser should preemptively perform DNS resolution for the target resource’s origin" }, { "code": null, "e": 569, "s": 482, "text": "help: It specifies a link to a help document. Example: <link rel=”help” href=”/help/”>" }, { "code": null, "e": 620, "s": 569, "text": "icon: It specifies import icon in a given document" }, { "code": null, "e": 691, "s": 620, "text": "license: It specifies a link to copyright information for the document" }, { "code": null, "e": 744, "s": 691, "text": "next: It provide the link of next document in series" }, { "code": null, "e": 801, "s": 744, "text": "pingback: It specifies the address of the pingback serve" }, { "code": null, "e": 883, "s": 801, "text": "preconnect: It specifies the target should be preemptively to the origin resource" }, { "code": null, "e": 949, "s": 883, "text": "prefetch: It specifies that the target document should be cached." }, { "code": null, "e": 1022, "s": 949, "text": "preload: It specifies that the browser must preemptively fetch and cache" }, { "code": null, "e": 1075, "s": 1022, "text": "prerender: It specifies that the browser should load" }, { "code": null, "e": 1131, "s": 1075, "text": "prev: It specifies the previous document in a selection" }, { "code": null, "e": 1186, "s": 1131, "text": "search: It specifies the search tool for the document." }, { "code": null, "e": 1223, "s": 1186, "text": "stylesheet: It Imports a style sheet" }, { "code": null, "e": 1260, "s": 1223, "text": "Example of HTML link rel Attribute " }, { "code": null, "e": 1265, "s": 1260, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" type=\"text/css\" href=\"index_screen.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"index_print.css\"></head> <body> <center> <h1>GeeksforGeeks</h1> <p><a href=\"https://ide.geeksforgeeks.org/tryit.php\" target=\"_blank\"> Click here </a> </center></body> </html> ", "e": 1667, "s": 1265, "text": null }, { "code": null, "e": 1677, "s": 1667, "text": "Output: " }, { "code": null, "e": 1761, "s": 1677, "text": "Supported Browsers: The browsers supported by HTML rel Attribute are listed below " }, { "code": null, "e": 1777, "s": 1761, "text": "Google Chrome 1" }, { "code": null, "e": 1785, "s": 1777, "text": "Edge 12" }, { "code": null, "e": 1797, "s": 1785, "text": "Firefox 1.0" }, { "code": null, "e": 1811, "s": 1797, "text": "Apple Safari " }, { "code": null, "e": 1818, "s": 1811, "text": "Opera " }, { "code": null, "e": 1836, "s": 1818, "text": "Internet Explorer" }, { "code": null, "e": 1851, "s": 1838, "text": "simmytarika5" }, { "code": null, "e": 1868, "s": 1851, "text": "kumargaurav97520" }, { "code": null, "e": 1884, "s": 1868, "text": "HTML-Attributes" }, { "code": null, "e": 1889, "s": 1884, "text": "HTML" }, { "code": null, "e": 1906, "s": 1889, "text": "Web Technologies" }, { "code": null, "e": 1911, "s": 1906, "text": "HTML" }, { "code": null, "e": 2009, "s": 1911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2033, "s": 2009, "text": "REST API (Introduction)" }, { "code": null, "e": 2072, "s": 2033, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2111, "s": 2072, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2131, "s": 2111, "text": "Angular File Upload" }, { "code": null, "e": 2160, "s": 2131, "text": "Form validation using jQuery" }, { "code": null, "e": 2193, "s": 2160, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2254, "s": 2193, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2297, "s": 2254, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2369, "s": 2297, "text": "Differences between Functional Components and Class Components in React" } ]
Private Constructors and Singleton Classes in Java
21 Jun, 2018 Let’s first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class. Do we need such ‘private constructors ‘ ? There are various scenarios where we can use private constructors. The major ones are Internal Constructor chainingSingleton class design pattern Internal Constructor chaining Singleton class design pattern What is a Singleton class? As the name implies, a class is said to be singleton if it limits the number of objects of that class to one. We can’t have more than a single object for such classes. Singleton classes are employed extensively in concepts like Networking and Database Connectivity. Design Pattern of Singleton classes: The constructor of singleton class would be private so there must be another way to get the instance of that class. This problem is resolved using a class member instance and a factory method to return the class member. Below is an example in java illustrating the same: // Java program to demonstrate implementation of Singleton // pattern using private constructors.import java.io.*; class MySingleton{ static MySingleton instance = null; public int x = 10; // private constructor can't be accessed outside the class private MySingleton() { } // Factory method to provide the users with instances static public MySingleton getInstance() { if (instance == null) instance = new MySingleton(); return instance; } } // Driver Classclass Main{ public static void main(String args[]) { MySingleton a = MySingleton.getInstance(); MySingleton b = MySingleton.getInstance(); a.x = a.x + 10; System.out.println("Value of a.x = " + a.x); System.out.println("Value of b.x = " + b.x); } } Output: Value of a.x = 20 Value of b.x = 20 We changed value of a.x, value of b.x also got updated because both ‘a’ and ‘b’ refer to same object, i.e., they are objects of a singleton class. This article is contributed by Ashutosh Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2018" }, { "code": null, "e": 98, "s": 54, "text": "Let’s first analyze the following question:" }, { "code": null, "e": 133, "s": 98, "text": "Can we have private constructors ?" }, { "code": null, "e": 295, "s": 133, "text": "As you can easily guess, like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class." }, { "code": null, "e": 337, "s": 295, "text": "Do we need such ‘private constructors ‘ ?" }, { "code": null, "e": 423, "s": 337, "text": "There are various scenarios where we can use private constructors. The major ones are" }, { "code": null, "e": 483, "s": 423, "text": "Internal Constructor chainingSingleton class design pattern" }, { "code": null, "e": 513, "s": 483, "text": "Internal Constructor chaining" }, { "code": null, "e": 544, "s": 513, "text": "Singleton class design pattern" }, { "code": null, "e": 571, "s": 544, "text": "What is a Singleton class?" }, { "code": null, "e": 681, "s": 571, "text": "As the name implies, a class is said to be singleton if it limits the number of objects of that class to one." }, { "code": null, "e": 739, "s": 681, "text": "We can’t have more than a single object for such classes." }, { "code": null, "e": 837, "s": 739, "text": "Singleton classes are employed extensively in concepts like Networking and Database Connectivity." }, { "code": null, "e": 874, "s": 837, "text": "Design Pattern of Singleton classes:" }, { "code": null, "e": 1094, "s": 874, "text": "The constructor of singleton class would be private so there must be another way to get the instance of that class. This problem is resolved using a class member instance and a factory method to return the class member." }, { "code": null, "e": 1145, "s": 1094, "text": "Below is an example in java illustrating the same:" }, { "code": "// Java program to demonstrate implementation of Singleton // pattern using private constructors.import java.io.*; class MySingleton{ static MySingleton instance = null; public int x = 10; // private constructor can't be accessed outside the class private MySingleton() { } // Factory method to provide the users with instances static public MySingleton getInstance() { if (instance == null) instance = new MySingleton(); return instance; } } // Driver Classclass Main{ public static void main(String args[]) { MySingleton a = MySingleton.getInstance(); MySingleton b = MySingleton.getInstance(); a.x = a.x + 10; System.out.println(\"Value of a.x = \" + a.x); System.out.println(\"Value of b.x = \" + b.x); } }", "e": 1966, "s": 1145, "text": null }, { "code": null, "e": 1974, "s": 1966, "text": "Output:" }, { "code": null, "e": 2010, "s": 1974, "text": "Value of a.x = 20\nValue of b.x = 20" }, { "code": null, "e": 2157, "s": 2010, "text": "We changed value of a.x, value of b.x also got updated because both ‘a’ and ‘b’ refer to same object, i.e., they are objects of a singleton class." }, { "code": null, "e": 2431, "s": 2157, "text": "This article is contributed by Ashutosh Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2555, "s": 2431, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 2560, "s": 2555, "text": "Java" }, { "code": null, "e": 2565, "s": 2560, "text": "Java" } ]
Matplotlib vs. Plotly: Let's Decide Once and for All | Towards Data Science
There is an annoying habit of soccer fans. Whenever a young but admittedly exceptional player emerges, they compare him to legends like Messi or Ronaldo. They choose to forget that the legends have been dominating the game since before the newbies had regrown teeth. Comparing Plotly to Matplotlib was, in a sense, similar to that in the beginning. Matplotlib had been in heavy use since 2003, and Plotly had just come out in 2014. Many were bored with Matplotlib by this time, so Plotly was warmly welcomed for its freshness and interactivity. Still, the library couldn’t hope to steal the top spot as the king of Python plotting packages from Matplotlib. In 2019, things changed dramatically when Plotly released its Express API in July. This fueled an explosion of interest in the library, and people started using it left and right. With another major version (5.0.0) released in June this year, I think Plotly matured more than enough to compare it to Matplotlib seriously. With that said, let’s get started: Let’s start by comparing the ease of use of their APIs. Both offer high-level and low-level interfaces to interact with the core functionality. On the one hand, Express excels in consistency. It only contains higher-level functions to access the built-in plots. It does not introduce new ways of performing existing functionality — it is a wrapper. All plot calls to Express return the core Figure object. On the other hand, Pyplot packages all plotting functions and customizations into a single, new API. Even though plot calls have the same signature, customization functions differ from those in the OOP API. This means you have to spend your time learning the differences if you want to switch interfaces. Besides, creating plots returns different objects under the hood. For example, plt.scatter returns a PathCollection object whereas plt.boxplot returns a dictionary. This is because Matplotlib implements different base classes for each plot type. It can be truly confusing for many. plot_scores(mpl=0, px=1) To switch from Pyplot to OOP API of MPL, you simply change the way you interact with the core data structures, such as figure and axes objects. Calls to plots have similar signatures, and the parameter names do not change. Switching from Express to Graph Objects requires a steep learning curve. The functions signatures to create all plots change, and GO adds much more parameters to each plot call. Even though this is done to introduce more customizations, I think plots end up unusually complex. Another disadvantage is that GO moves some of the core parameters outside the plot calls. For example, creating logarithmic axes can be achieved directly inside a plot in Express. In GO, you do this with update_layout or update_axes functions. This is not the case in Pyplot or OOP Matplotlib (parameters don't move or change names). plot_scores(mpl=1, px=1) Even though there is a separate section on customization, we have to talk about it in terms of API. All customizations in Matplotlib have separate functions. This allows you to make changes to the plot in chunks of code and using loops or other procedures. In contrast, Plotly uses dictionaries extensively. While this offers certain consistency to the way you interact with the plots and data, it comes at the heavy cost of code readability and length. As many people prefer the update_layout function, its arguments often end up with a jungle of nested dictionaries. You may pause and think about these differences between the APIs, but Matplotlib’s is more Pythonic and readable. plot_scores(2, 1) To see the true difference between speeds, we have to use bigger datasets. I will import the diamonds dataset from Seaborn and compare the time it takes to plot a simple scatterplot. I will be using the %%timeit magic command, which runs the same chunk of code several times to see the standard deviation error. Measuring MPL: Measuring Plotly: Matplotlib is almost 80 times faster than Plotly, with much lower SD errors. Maybe this is because Plotly renders interactive plots. Let’s check the speeds once again, this time turning off the interactivity: Unfortunately, turning off interactivity didn’t help much. Matplotlib crushes Plotly in terms of speed: plot_scores(3, 1) In this area, Plotly clearly takes the lead. From the Plotly API reference, I counted close to 50 unique traces. Especially, Plotly is absolutely superb when it comes to certain types of plots. For example, it has dedicated support for financial plotting, and it provides figure_factory subpackage to create specific complex charts. On the other hand, Matplotlib has a modest selection of plots. I don’t think if we have even added the plots from Seaborn, they would quite match the rich selection that Plotly offers: plot_scores(3, 2) Um, how can we compare interactivity if only Plotly has this feature? Well, not many know this, but outside Jupyter Notebooks, Matplotlib plots render in an interactivity mode by default. Unfortunately, this level of interactivity is nothing compared to Plotly’s. So, let’s raise Plotly’s score by one: plot_scores(3, 3) Now, for a tiebreaker — apart from general interactivity, Plotly also offers custom buttons: sliders: and many more features that take the whole user experience to the next level. This deserves another point: plot_scores(3, 4) For many data scientists, customizations are everything. You might want to create custom themes and use brand colors depending on your project's data (an excellent example can be seen here for visualizing Netflix data). With that said, let’s see the most important components you can tune and their differences between the packages. Both MPL and Plotly have dedicated sub-modules for colors and palettes. Matplotlib allows users to change the color of plot elements using color labels, hex codes, RGB and RGBA systems. Most notably, under mpl.colors.CSS4_COLORS, you can pass more than 100 CSS color labels. Plotly indeed implements the same features, but Matplotlib offers colors from other plotting software like Tableau. Besides, passing colors and palettes in Matplotlib make less of a mess. In Plotly, there are no less than 6 arguments that deal with different types of palettes. In comparison, MPL has only 2 flexible parameters color and cmap that can adapt to any color system or palette you pass. plot_scores(4, 4) While doing an analysis that isn’t meant for anyone other than yourself, there is no need to go beyond the default settings. These types of analyses can often last long, so these defaults must produce charts in as high quality as possible on the fly. I think all of us can agree that Matplotlib defaults, well, sucks. Look at this scatterplot of height vs. weight of Olympic athletes created in both libraries: Plotly looks better. Besides, I like how Plotly adheres to data visualization best practices. One of them is using colors when necessary. For example, when creating bar charts or boxplots, Plotly uses uniform colors rather than a palette. MPL does the opposite — it colors every bar or boxplot even though the color doesn’t add new information to the plot. plot_scores(4, 5) Plotly takes this section solely because it has the awesome ‘Dark Mode’ (call me subjective, I don’t care). It is easier on the eye and gives plots a feel of luxury (especially when used with red, my favorite): It looks so slick in Jupyter Lab! plot_scores(4, 6) The reason why it is taking me such a long time to work with Plotly more often is its lack of features to control the global settings. Matplotlib has the rcParams dictionary, which you can easily tweak to set plotting options globally. You would think that a library that heavily depends on dictionaries would have a similar dictionary, but no! Plotly really disappoints me in this regard. plot_scores(5, 6) The most important components of axes are tick marks and tick labels. Honestly, to this day, I don’t have a full grasp on controlling ticks in MPL. This is because MPL does not have a consistent API for controlling axes. You might blame me for not trying hard enough, but I figured out everything I need to learn about controlling ticks in Plotly by just looking at the documentation once. Plotly has a single way of working with ticks (through update_xaxes/update_yaxes or update_layout). These functions do not change when you switch between Express and GO, while in MPL, that is not the case. plot_scores(5, 7) We will have to give this one to Matplotlib. I am not doing this because Plotly is already in the lead, and I have to keep up the intrigue. The fact that Matplotlib implements individual components as separate classes makes its API very granular. More granular means more options to control the objects visible on the plot. Take boxplots as an example: Even though the plot looks blank, it allows unprecedented customization. For example, under the boxes key of the returned dictionary, you can access each of the boxplots as Patch objects: These objects open the doors to all the magic that happens under the hood of Matplotlib. They are not limited to boxplots either. You can access Patch objects from many other plots. plot_scores(6, 7) Scatterplots play a pivotal role in statistical analysis. They are used to understand correlation and causation, detect outliers and plot the line of best fit in linear regression. So, I decided to dedicate an entire section to compare the scatterplots of both libraries. For that, I will choose the height vs. weight scatterplot from the earlier section: I know, disgusting to look at. However, watch as I perform some customizations that turn the plot into a piece of (well, I won’t say art): Before applying the last step, we can see that the dots are grouped around distinct rows and columns. Let’s add jittering and see what happens: Now compare the initial plot to the last: We wouldn’t even have known the dots are grouped as rows and columns in Plotly. It does not allow changing the marker size any smaller than the default. This means we wouldn’t be able to jitter the distributions to account for the fact that weights and heights were rounded off at discrete values. plot_scores(7, 7) Wow! It has been neck-and-neck up to this point. As a final component and a tiebreaker, let’s compare the documentations. When I was a beginner, Matplotlib documentation was the last place I expected to find answers to my questions. First, you can’t read a single page of the documentation without opening several other linked pages. The documentation is a jumbled monstrosity. Second, its tutorials and example scripts seem like they are written for academic researchers. It is almost like MPL tries to intimidate beginner data scientists on purpose. In contrast, Plotly is much more organized. It has a full API reference and its tutorials are mostly stand-alone. It is not perfect, but at least it is nice to look at — it does not feel like you are reading a newspaper page from the 90s. plot_scores(7, 8) Truthfully, I went into writing this comparison completely sure that Matplotlib will end up winning. By the time I finished the half, I knew that the opposite would happen, and I was right. Plotly is truly a remarkable library. Even though I let my personal preferences and biases affect the scores, no one can deny that the package has already achieved many milestones and still rapidly developing. This post was not meant to convince you to ditch one package and use the other. Rather, I wanted to highlight the areas each package excels at and show what you can create if you add both libraries to your toolbelt. 6 Sklearn Mistakes That Silently Tell You Are a Rookie 19 Sklearn Features You Didn’t Know Existed | P(Guarantee) = 0.75 6 Things I Do to Consistently Improve My Machine Learning Models
[ { "code": null, "e": 200, "s": 46, "text": "There is an annoying habit of soccer fans. Whenever a young but admittedly exceptional player emerges, they compare him to legends like Messi or Ronaldo." }, { "code": null, "e": 313, "s": 200, "text": "They choose to forget that the legends have been dominating the game since before the newbies had regrown teeth." }, { "code": null, "e": 478, "s": 313, "text": "Comparing Plotly to Matplotlib was, in a sense, similar to that in the beginning. Matplotlib had been in heavy use since 2003, and Plotly had just come out in 2014." }, { "code": null, "e": 703, "s": 478, "text": "Many were bored with Matplotlib by this time, so Plotly was warmly welcomed for its freshness and interactivity. Still, the library couldn’t hope to steal the top spot as the king of Python plotting packages from Matplotlib." }, { "code": null, "e": 883, "s": 703, "text": "In 2019, things changed dramatically when Plotly released its Express API in July. This fueled an explosion of interest in the library, and people started using it left and right." }, { "code": null, "e": 1025, "s": 883, "text": "With another major version (5.0.0) released in June this year, I think Plotly matured more than enough to compare it to Matplotlib seriously." }, { "code": null, "e": 1060, "s": 1025, "text": "With that said, let’s get started:" }, { "code": null, "e": 1204, "s": 1060, "text": "Let’s start by comparing the ease of use of their APIs. Both offer high-level and low-level interfaces to interact with the core functionality." }, { "code": null, "e": 1466, "s": 1204, "text": "On the one hand, Express excels in consistency. It only contains higher-level functions to access the built-in plots. It does not introduce new ways of performing existing functionality — it is a wrapper. All plot calls to Express return the core Figure object." }, { "code": null, "e": 1673, "s": 1466, "text": "On the other hand, Pyplot packages all plotting functions and customizations into a single, new API. Even though plot calls have the same signature, customization functions differ from those in the OOP API." }, { "code": null, "e": 1771, "s": 1673, "text": "This means you have to spend your time learning the differences if you want to switch interfaces." }, { "code": null, "e": 2053, "s": 1771, "text": "Besides, creating plots returns different objects under the hood. For example, plt.scatter returns a PathCollection object whereas plt.boxplot returns a dictionary. This is because Matplotlib implements different base classes for each plot type. It can be truly confusing for many." }, { "code": null, "e": 2078, "s": 2053, "text": "plot_scores(mpl=0, px=1)" }, { "code": null, "e": 2301, "s": 2078, "text": "To switch from Pyplot to OOP API of MPL, you simply change the way you interact with the core data structures, such as figure and axes objects. Calls to plots have similar signatures, and the parameter names do not change." }, { "code": null, "e": 2578, "s": 2301, "text": "Switching from Express to Graph Objects requires a steep learning curve. The functions signatures to create all plots change, and GO adds much more parameters to each plot call. Even though this is done to introduce more customizations, I think plots end up unusually complex." }, { "code": null, "e": 2912, "s": 2578, "text": "Another disadvantage is that GO moves some of the core parameters outside the plot calls. For example, creating logarithmic axes can be achieved directly inside a plot in Express. In GO, you do this with update_layout or update_axes functions. This is not the case in Pyplot or OOP Matplotlib (parameters don't move or change names)." }, { "code": null, "e": 2937, "s": 2912, "text": "plot_scores(mpl=1, px=1)" }, { "code": null, "e": 3037, "s": 2937, "text": "Even though there is a separate section on customization, we have to talk about it in terms of API." }, { "code": null, "e": 3194, "s": 3037, "text": "All customizations in Matplotlib have separate functions. This allows you to make changes to the plot in chunks of code and using loops or other procedures." }, { "code": null, "e": 3506, "s": 3194, "text": "In contrast, Plotly uses dictionaries extensively. While this offers certain consistency to the way you interact with the plots and data, it comes at the heavy cost of code readability and length. As many people prefer the update_layout function, its arguments often end up with a jungle of nested dictionaries." }, { "code": null, "e": 3620, "s": 3506, "text": "You may pause and think about these differences between the APIs, but Matplotlib’s is more Pythonic and readable." }, { "code": null, "e": 3638, "s": 3620, "text": "plot_scores(2, 1)" }, { "code": null, "e": 3821, "s": 3638, "text": "To see the true difference between speeds, we have to use bigger datasets. I will import the diamonds dataset from Seaborn and compare the time it takes to plot a simple scatterplot." }, { "code": null, "e": 3950, "s": 3821, "text": "I will be using the %%timeit magic command, which runs the same chunk of code several times to see the standard deviation error." }, { "code": null, "e": 3965, "s": 3950, "text": "Measuring MPL:" }, { "code": null, "e": 3983, "s": 3965, "text": "Measuring Plotly:" }, { "code": null, "e": 4192, "s": 3983, "text": "Matplotlib is almost 80 times faster than Plotly, with much lower SD errors. Maybe this is because Plotly renders interactive plots. Let’s check the speeds once again, this time turning off the interactivity:" }, { "code": null, "e": 4296, "s": 4192, "text": "Unfortunately, turning off interactivity didn’t help much. Matplotlib crushes Plotly in terms of speed:" }, { "code": null, "e": 4314, "s": 4296, "text": "plot_scores(3, 1)" }, { "code": null, "e": 4508, "s": 4314, "text": "In this area, Plotly clearly takes the lead. From the Plotly API reference, I counted close to 50 unique traces. Especially, Plotly is absolutely superb when it comes to certain types of plots." }, { "code": null, "e": 4647, "s": 4508, "text": "For example, it has dedicated support for financial plotting, and it provides figure_factory subpackage to create specific complex charts." }, { "code": null, "e": 4832, "s": 4647, "text": "On the other hand, Matplotlib has a modest selection of plots. I don’t think if we have even added the plots from Seaborn, they would quite match the rich selection that Plotly offers:" }, { "code": null, "e": 4850, "s": 4832, "text": "plot_scores(3, 2)" }, { "code": null, "e": 4920, "s": 4850, "text": "Um, how can we compare interactivity if only Plotly has this feature?" }, { "code": null, "e": 5038, "s": 4920, "text": "Well, not many know this, but outside Jupyter Notebooks, Matplotlib plots render in an interactivity mode by default." }, { "code": null, "e": 5153, "s": 5038, "text": "Unfortunately, this level of interactivity is nothing compared to Plotly’s. So, let’s raise Plotly’s score by one:" }, { "code": null, "e": 5171, "s": 5153, "text": "plot_scores(3, 3)" }, { "code": null, "e": 5264, "s": 5171, "text": "Now, for a tiebreaker — apart from general interactivity, Plotly also offers custom buttons:" }, { "code": null, "e": 5273, "s": 5264, "text": "sliders:" }, { "code": null, "e": 5380, "s": 5273, "text": "and many more features that take the whole user experience to the next level. This deserves another point:" }, { "code": null, "e": 5398, "s": 5380, "text": "plot_scores(3, 4)" }, { "code": null, "e": 5618, "s": 5398, "text": "For many data scientists, customizations are everything. You might want to create custom themes and use brand colors depending on your project's data (an excellent example can be seen here for visualizing Netflix data)." }, { "code": null, "e": 5731, "s": 5618, "text": "With that said, let’s see the most important components you can tune and their differences between the packages." }, { "code": null, "e": 5803, "s": 5731, "text": "Both MPL and Plotly have dedicated sub-modules for colors and palettes." }, { "code": null, "e": 6006, "s": 5803, "text": "Matplotlib allows users to change the color of plot elements using color labels, hex codes, RGB and RGBA systems. Most notably, under mpl.colors.CSS4_COLORS, you can pass more than 100 CSS color labels." }, { "code": null, "e": 6194, "s": 6006, "text": "Plotly indeed implements the same features, but Matplotlib offers colors from other plotting software like Tableau. Besides, passing colors and palettes in Matplotlib make less of a mess." }, { "code": null, "e": 6405, "s": 6194, "text": "In Plotly, there are no less than 6 arguments that deal with different types of palettes. In comparison, MPL has only 2 flexible parameters color and cmap that can adapt to any color system or palette you pass." }, { "code": null, "e": 6423, "s": 6405, "text": "plot_scores(4, 4)" }, { "code": null, "e": 6674, "s": 6423, "text": "While doing an analysis that isn’t meant for anyone other than yourself, there is no need to go beyond the default settings. These types of analyses can often last long, so these defaults must produce charts in as high quality as possible on the fly." }, { "code": null, "e": 6834, "s": 6674, "text": "I think all of us can agree that Matplotlib defaults, well, sucks. Look at this scatterplot of height vs. weight of Olympic athletes created in both libraries:" }, { "code": null, "e": 6972, "s": 6834, "text": "Plotly looks better. Besides, I like how Plotly adheres to data visualization best practices. One of them is using colors when necessary." }, { "code": null, "e": 7191, "s": 6972, "text": "For example, when creating bar charts or boxplots, Plotly uses uniform colors rather than a palette. MPL does the opposite — it colors every bar or boxplot even though the color doesn’t add new information to the plot." }, { "code": null, "e": 7209, "s": 7191, "text": "plot_scores(4, 5)" }, { "code": null, "e": 7420, "s": 7209, "text": "Plotly takes this section solely because it has the awesome ‘Dark Mode’ (call me subjective, I don’t care). It is easier on the eye and gives plots a feel of luxury (especially when used with red, my favorite):" }, { "code": null, "e": 7454, "s": 7420, "text": "It looks so slick in Jupyter Lab!" }, { "code": null, "e": 7472, "s": 7454, "text": "plot_scores(4, 6)" }, { "code": null, "e": 7607, "s": 7472, "text": "The reason why it is taking me such a long time to work with Plotly more often is its lack of features to control the global settings." }, { "code": null, "e": 7817, "s": 7607, "text": "Matplotlib has the rcParams dictionary, which you can easily tweak to set plotting options globally. You would think that a library that heavily depends on dictionaries would have a similar dictionary, but no!" }, { "code": null, "e": 7862, "s": 7817, "text": "Plotly really disappoints me in this regard." }, { "code": null, "e": 7880, "s": 7862, "text": "plot_scores(5, 6)" }, { "code": null, "e": 7950, "s": 7880, "text": "The most important components of axes are tick marks and tick labels." }, { "code": null, "e": 8101, "s": 7950, "text": "Honestly, to this day, I don’t have a full grasp on controlling ticks in MPL. This is because MPL does not have a consistent API for controlling axes." }, { "code": null, "e": 8270, "s": 8101, "text": "You might blame me for not trying hard enough, but I figured out everything I need to learn about controlling ticks in Plotly by just looking at the documentation once." }, { "code": null, "e": 8476, "s": 8270, "text": "Plotly has a single way of working with ticks (through update_xaxes/update_yaxes or update_layout). These functions do not change when you switch between Express and GO, while in MPL, that is not the case." }, { "code": null, "e": 8494, "s": 8476, "text": "plot_scores(5, 7)" }, { "code": null, "e": 8634, "s": 8494, "text": "We will have to give this one to Matplotlib. I am not doing this because Plotly is already in the lead, and I have to keep up the intrigue." }, { "code": null, "e": 8818, "s": 8634, "text": "The fact that Matplotlib implements individual components as separate classes makes its API very granular. More granular means more options to control the objects visible on the plot." }, { "code": null, "e": 8847, "s": 8818, "text": "Take boxplots as an example:" }, { "code": null, "e": 9035, "s": 8847, "text": "Even though the plot looks blank, it allows unprecedented customization. For example, under the boxes key of the returned dictionary, you can access each of the boxplots as Patch objects:" }, { "code": null, "e": 9217, "s": 9035, "text": "These objects open the doors to all the magic that happens under the hood of Matplotlib. They are not limited to boxplots either. You can access Patch objects from many other plots." }, { "code": null, "e": 9235, "s": 9217, "text": "plot_scores(6, 7)" }, { "code": null, "e": 9293, "s": 9235, "text": "Scatterplots play a pivotal role in statistical analysis." }, { "code": null, "e": 9507, "s": 9293, "text": "They are used to understand correlation and causation, detect outliers and plot the line of best fit in linear regression. So, I decided to dedicate an entire section to compare the scatterplots of both libraries." }, { "code": null, "e": 9591, "s": 9507, "text": "For that, I will choose the height vs. weight scatterplot from the earlier section:" }, { "code": null, "e": 9730, "s": 9591, "text": "I know, disgusting to look at. However, watch as I perform some customizations that turn the plot into a piece of (well, I won’t say art):" }, { "code": null, "e": 9874, "s": 9730, "text": "Before applying the last step, we can see that the dots are grouped around distinct rows and columns. Let’s add jittering and see what happens:" }, { "code": null, "e": 9916, "s": 9874, "text": "Now compare the initial plot to the last:" }, { "code": null, "e": 10069, "s": 9916, "text": "We wouldn’t even have known the dots are grouped as rows and columns in Plotly. It does not allow changing the marker size any smaller than the default." }, { "code": null, "e": 10214, "s": 10069, "text": "This means we wouldn’t be able to jitter the distributions to account for the fact that weights and heights were rounded off at discrete values." }, { "code": null, "e": 10232, "s": 10214, "text": "plot_scores(7, 7)" }, { "code": null, "e": 10281, "s": 10232, "text": "Wow! It has been neck-and-neck up to this point." }, { "code": null, "e": 10354, "s": 10281, "text": "As a final component and a tiebreaker, let’s compare the documentations." }, { "code": null, "e": 10465, "s": 10354, "text": "When I was a beginner, Matplotlib documentation was the last place I expected to find answers to my questions." }, { "code": null, "e": 10610, "s": 10465, "text": "First, you can’t read a single page of the documentation without opening several other linked pages. The documentation is a jumbled monstrosity." }, { "code": null, "e": 10784, "s": 10610, "text": "Second, its tutorials and example scripts seem like they are written for academic researchers. It is almost like MPL tries to intimidate beginner data scientists on purpose." }, { "code": null, "e": 10898, "s": 10784, "text": "In contrast, Plotly is much more organized. It has a full API reference and its tutorials are mostly stand-alone." }, { "code": null, "e": 11023, "s": 10898, "text": "It is not perfect, but at least it is nice to look at — it does not feel like you are reading a newspaper page from the 90s." }, { "code": null, "e": 11041, "s": 11023, "text": "plot_scores(7, 8)" }, { "code": null, "e": 11142, "s": 11041, "text": "Truthfully, I went into writing this comparison completely sure that Matplotlib will end up winning." }, { "code": null, "e": 11231, "s": 11142, "text": "By the time I finished the half, I knew that the opposite would happen, and I was right." }, { "code": null, "e": 11441, "s": 11231, "text": "Plotly is truly a remarkable library. Even though I let my personal preferences and biases affect the scores, no one can deny that the package has already achieved many milestones and still rapidly developing." }, { "code": null, "e": 11657, "s": 11441, "text": "This post was not meant to convince you to ditch one package and use the other. Rather, I wanted to highlight the areas each package excels at and show what you can create if you add both libraries to your toolbelt." }, { "code": null, "e": 11712, "s": 11657, "text": "6 Sklearn Mistakes That Silently Tell You Are a Rookie" }, { "code": null, "e": 11778, "s": 11712, "text": "19 Sklearn Features You Didn’t Know Existed | P(Guarantee) = 0.75" } ]
Ultimate Guide to Reinforcement Learning Part 1 — Creating a Game | by Daniel Brummerloh | Towards Data Science
The complete code of the environment, the training and the rollout can be found on GitHub: https://github.com/danuo/rocket-meister/ Part 1 — Creation of a playable environment with Pygame Create an environment as a gym.Env subclass. Implement the environment logic through the step() function. Acquiring user input with Pygame to make the environment playable for humans. Implementing a render() function with Pygame to visualize the environment state. Implementing interactive level design with Matplotlib. Part 2 —Training a Neural Network with Reinforced Learning https://medium.com/@d.brummerloh/ultimate-guide-for-ai-game-creation-part-2-training-e252108dfbd1 Define suitable observations while understanding the possibilities and challenges. Define suitable rewards. Training neural networks with the gym environment. Discussion of the results This is the first part of the series. We will implement the game logic, acquire user input data for the controls and implement rendering to make it possible for humans to play the game. For this, we will be using a popular python package called Pygame. As the model we are going to train is relatively small, the training can be performed on a consumer level desktop CPU in a reasonable amount time (less than a day). You do not need a powerful GPU or access to a cloud computing network. The python packages used in this guide are listed below: Python 3.8.xray 1.0tensorflow 2.3.1tensorflow-probability 0.11gym 0.17.3pygame 2.0.0 In the context of reinforced learning, an environment can be seen as an interactive problem, that needs to be solved in the best way possible. To quantify the success, a reward function is defined within the environment. The agent can see the so called observations that give information about the current state of the environment. It can then take a specific action, which will return the observation and the scalar reward of the next environment’s state. The agent’s goal is to maximize the sum of rewards achieved in a limited number of steps. From a technical standpoint, there are many different ways build an environment. The best way though, is to adopt the structure defined in the gym package. The gym package is a collection of ready to use environments providing a de facto standard API for reinforced learning. All gym environments share the same names for functions and variables, which makes the environment and the agent easily interchangeable. To adopt the gym structure, we will make our environment a sub-class of the gym.Env class. The fundamental and mandatory elements of the class are shown below: Most of these functions and variables will be discussed in more depth later on. Here is a small summary with the most important items lisetd first: action (object): The action to be performed in the step() function. In a game of chess, the action would be the specific, legal move performed by a player. observation (object): This is all the information available to the agent to choose the next action. The observation is based only on the current state of the environment. reward (float): This is the reward gained by the last performed action or during the previous step respectively. The AI will try to maximize the total reward. The reward can also be negative. done (boolean): If set to true, the environment reached an end point. No more actions can be performed, the environment needs to be reset. info (dict): Allows to extract environment data for debugging purposes. The data is not visible to the agent. env_config(dict): This optional dictionary can be used to configure the environment. observation_space and action_space: As you might imagine, only certain actions and observations are valid in regards of a specific environment. To define a format, the observation_space and action_space variables need to be assigned to a respective gym.space class. Spaces can differ in their dimensionality and their value range. Continuous and discrete spaces are both possible. For more information on the gym spaces, have a look into the documentation and the gym GitHub. self.observation_space = <gym.space>self.action_space = <gym.space> As seen in the video, we want to control a rocket which can be accelerated forwards/backwards (action 1) and rotated left/right (action 2). Thus, we define the actions as a linear vector of the size 2. The values of each array cell are continuous and must be in the range of [-1,1]. The corresponding gym space is defined in the following line of code: gym.spaces.Box(low=-1., high=1., shape=(2,), dtype=np.float32) Pygame is a Python library designed for the creation of simple games. Key features are 2d-rendering capabilities, user input acquisition and options for audio output. The following section will cover a very basic Pygame implementation with the bare minimum features. If you are more ambitious, you can consider implementing features such as dynamic frame rate or dynamic resolution. To render in Pygame, we need to create a window (also called surface) to draw the visual output on. window = pygame.display.set_mode((window_width, window_height)) Next, we can queue draw calls for the created window. You can find an overview of the available draw calls in the Pygame documentary. We will implement a couple of exemplary draw calls in a new function that we add to our CustomEnv class. The function is called render() and looks as follows: After the draw calls are made, the window needs to be updated and actually rendered with the pygame.display.update() command. Now it’s time to throw it all together by creating a render loop routine that can keep our environment running. We initialize Pygame with pygame.init() Then we create a clock object, that can maintain a static frame rate in combination with tick(fps). We create a window of the size 1000*500 pixels for the visual output. Then we start a while loop that will perform step() and render() once before one frame is generated with update(). Obviously, this render loop only makes sense, if the render() actually reflects the changes induced by step(). Pygame offers two ways to acquire user input data from the keyboard: The first one is called pygame.event.get() and will generate an event whenever a key state changes from unpressed to pressed or vise versa. Other things, such as closing the Pygame window, will also create an event. The latter (event.type == pygame.QUIT) enables us to end the while-loop and the Python script without crashing. A list of key-constants can be found in the Pygame documentation. The second method is called pygame.key.get_pressed() and will return a Boolean typed tuple with each entry representing a key on the keyboard. The value will be 0 for non-pressed keys and 1 for pressed keys. To evaluate key states, we need to know which keys map to which index of the tuple. For example, the upwards arrow key is at index 273. Next, we will implement the kinematics of the rocket. While we use a simple approach for the rotation, the translational movement will have inertia. Mathematically, the rocket’s trajectory is the solution of the Equation of Motion and is smooth. The position cannot jump, but needs to change continuously instead. Since we are fine with an approximate solution, we can calculate the trajectory using a time discretization with the Euler Forward Method. A simple and minimal 2-d implementation is shown in the following code: Now we incorporate everything (gamelogic, input and rendering) into our previously defined CustomEnv class. We will also move everything related to Pygame into the render() and a separate init() function. This way, we can execute Machine Learning routines with step() and reset() without loading the heavier Pygame package. If the environment is loaded for the AI-training, the rendering is not needed and the performance can be increased. Here is the above code running with some keyboard inputs: For now, we will be using a manually created static level. Creating one can be a tedious task. We will use Matplotlib to make our live a little bit easier. With the plt.ginput() function, coordinates can be captured by clicking inside the figure. These coordinates will be printed into the console, from where you can copy them into your code. A little reformatting should make it possible to include them into our environment, for example by storing them in numpy array as seen in rocket_gym.py. Collision Detection Let’s assume we have the level boundary stored as an array of the size n*4, each line holding the points of one segment: If two lines intersect can be checked by the following function. If the lines intersect, coordinates of the intersecting point are returned. If there is no intersection, None is returned. Now, we can apply the formula to our problem. We do this by checking, if any of the environment boundaries intersect with the movement vector In the second part, we will discuss and implement the observations and rewards that are returned by the environment. After that, the actual training is conducted. Have a read over here:
[ { "code": null, "e": 304, "s": 172, "text": "The complete code of the environment, the training and the rollout can be found on GitHub: https://github.com/danuo/rocket-meister/" }, { "code": null, "e": 360, "s": 304, "text": "Part 1 — Creation of a playable environment with Pygame" }, { "code": null, "e": 405, "s": 360, "text": "Create an environment as a gym.Env subclass." }, { "code": null, "e": 466, "s": 405, "text": "Implement the environment logic through the step() function." }, { "code": null, "e": 544, "s": 466, "text": "Acquiring user input with Pygame to make the environment playable for humans." }, { "code": null, "e": 625, "s": 544, "text": "Implementing a render() function with Pygame to visualize the environment state." }, { "code": null, "e": 680, "s": 625, "text": "Implementing interactive level design with Matplotlib." }, { "code": null, "e": 739, "s": 680, "text": "Part 2 —Training a Neural Network with Reinforced Learning" }, { "code": null, "e": 837, "s": 739, "text": "https://medium.com/@d.brummerloh/ultimate-guide-for-ai-game-creation-part-2-training-e252108dfbd1" }, { "code": null, "e": 920, "s": 837, "text": "Define suitable observations while understanding the possibilities and challenges." }, { "code": null, "e": 945, "s": 920, "text": "Define suitable rewards." }, { "code": null, "e": 996, "s": 945, "text": "Training neural networks with the gym environment." }, { "code": null, "e": 1022, "s": 996, "text": "Discussion of the results" }, { "code": null, "e": 1275, "s": 1022, "text": "This is the first part of the series. We will implement the game logic, acquire user input data for the controls and implement rendering to make it possible for humans to play the game. For this, we will be using a popular python package called Pygame." }, { "code": null, "e": 1568, "s": 1275, "text": "As the model we are going to train is relatively small, the training can be performed on a consumer level desktop CPU in a reasonable amount time (less than a day). You do not need a powerful GPU or access to a cloud computing network. The python packages used in this guide are listed below:" }, { "code": null, "e": 1653, "s": 1568, "text": "Python 3.8.xray 1.0tensorflow 2.3.1tensorflow-probability 0.11gym 0.17.3pygame 2.0.0" }, { "code": null, "e": 1796, "s": 1653, "text": "In the context of reinforced learning, an environment can be seen as an interactive problem, that needs to be solved in the best way possible." }, { "code": null, "e": 2200, "s": 1796, "text": "To quantify the success, a reward function is defined within the environment. The agent can see the so called observations that give information about the current state of the environment. It can then take a specific action, which will return the observation and the scalar reward of the next environment’s state. The agent’s goal is to maximize the sum of rewards achieved in a limited number of steps." }, { "code": null, "e": 2773, "s": 2200, "text": "From a technical standpoint, there are many different ways build an environment. The best way though, is to adopt the structure defined in the gym package. The gym package is a collection of ready to use environments providing a de facto standard API for reinforced learning. All gym environments share the same names for functions and variables, which makes the environment and the agent easily interchangeable. To adopt the gym structure, we will make our environment a sub-class of the gym.Env class. The fundamental and mandatory elements of the class are shown below:" }, { "code": null, "e": 2921, "s": 2773, "text": "Most of these functions and variables will be discussed in more depth later on. Here is a small summary with the most important items lisetd first:" }, { "code": null, "e": 3077, "s": 2921, "text": "action (object): The action to be performed in the step() function. In a game of chess, the action would be the specific, legal move performed by a player." }, { "code": null, "e": 3248, "s": 3077, "text": "observation (object): This is all the information available to the agent to choose the next action. The observation is based only on the current state of the environment." }, { "code": null, "e": 3440, "s": 3248, "text": "reward (float): This is the reward gained by the last performed action or during the previous step respectively. The AI will try to maximize the total reward. The reward can also be negative." }, { "code": null, "e": 3579, "s": 3440, "text": "done (boolean): If set to true, the environment reached an end point. No more actions can be performed, the environment needs to be reset." }, { "code": null, "e": 3689, "s": 3579, "text": "info (dict): Allows to extract environment data for debugging purposes. The data is not visible to the agent." }, { "code": null, "e": 3774, "s": 3689, "text": "env_config(dict): This optional dictionary can be used to configure the environment." }, { "code": null, "e": 4250, "s": 3774, "text": "observation_space and action_space: As you might imagine, only certain actions and observations are valid in regards of a specific environment. To define a format, the observation_space and action_space variables need to be assigned to a respective gym.space class. Spaces can differ in their dimensionality and their value range. Continuous and discrete spaces are both possible. For more information on the gym spaces, have a look into the documentation and the gym GitHub." }, { "code": null, "e": 4318, "s": 4250, "text": "self.observation_space = <gym.space>self.action_space = <gym.space>" }, { "code": null, "e": 4520, "s": 4318, "text": "As seen in the video, we want to control a rocket which can be accelerated forwards/backwards (action 1) and rotated left/right (action 2). Thus, we define the actions as a linear vector of the size 2." }, { "code": null, "e": 4671, "s": 4520, "text": "The values of each array cell are continuous and must be in the range of [-1,1]. The corresponding gym space is defined in the following line of code:" }, { "code": null, "e": 4734, "s": 4671, "text": "gym.spaces.Box(low=-1., high=1., shape=(2,), dtype=np.float32)" }, { "code": null, "e": 5117, "s": 4734, "text": "Pygame is a Python library designed for the creation of simple games. Key features are 2d-rendering capabilities, user input acquisition and options for audio output. The following section will cover a very basic Pygame implementation with the bare minimum features. If you are more ambitious, you can consider implementing features such as dynamic frame rate or dynamic resolution." }, { "code": null, "e": 5217, "s": 5117, "text": "To render in Pygame, we need to create a window (also called surface) to draw the visual output on." }, { "code": null, "e": 5281, "s": 5217, "text": "window = pygame.display.set_mode((window_width, window_height))" }, { "code": null, "e": 5574, "s": 5281, "text": "Next, we can queue draw calls for the created window. You can find an overview of the available draw calls in the Pygame documentary. We will implement a couple of exemplary draw calls in a new function that we add to our CustomEnv class. The function is called render() and looks as follows:" }, { "code": null, "e": 5700, "s": 5574, "text": "After the draw calls are made, the window needs to be updated and actually rendered with the pygame.display.update() command." }, { "code": null, "e": 6248, "s": 5700, "text": "Now it’s time to throw it all together by creating a render loop routine that can keep our environment running. We initialize Pygame with pygame.init() Then we create a clock object, that can maintain a static frame rate in combination with tick(fps). We create a window of the size 1000*500 pixels for the visual output. Then we start a while loop that will perform step() and render() once before one frame is generated with update(). Obviously, this render loop only makes sense, if the render() actually reflects the changes induced by step()." }, { "code": null, "e": 6317, "s": 6248, "text": "Pygame offers two ways to acquire user input data from the keyboard:" }, { "code": null, "e": 6711, "s": 6317, "text": "The first one is called pygame.event.get() and will generate an event whenever a key state changes from unpressed to pressed or vise versa. Other things, such as closing the Pygame window, will also create an event. The latter (event.type == pygame.QUIT) enables us to end the while-loop and the Python script without crashing. A list of key-constants can be found in the Pygame documentation." }, { "code": null, "e": 7055, "s": 6711, "text": "The second method is called pygame.key.get_pressed() and will return a Boolean typed tuple with each entry representing a key on the keyboard. The value will be 0 for non-pressed keys and 1 for pressed keys. To evaluate key states, we need to know which keys map to which index of the tuple. For example, the upwards arrow key is at index 273." }, { "code": null, "e": 7369, "s": 7055, "text": "Next, we will implement the kinematics of the rocket. While we use a simple approach for the rotation, the translational movement will have inertia. Mathematically, the rocket’s trajectory is the solution of the Equation of Motion and is smooth. The position cannot jump, but needs to change continuously instead." }, { "code": null, "e": 7580, "s": 7369, "text": "Since we are fine with an approximate solution, we can calculate the trajectory using a time discretization with the Euler Forward Method. A simple and minimal 2-d implementation is shown in the following code:" }, { "code": null, "e": 8020, "s": 7580, "text": "Now we incorporate everything (gamelogic, input and rendering) into our previously defined CustomEnv class. We will also move everything related to Pygame into the render() and a separate init() function. This way, we can execute Machine Learning routines with step() and reset() without loading the heavier Pygame package. If the environment is loaded for the AI-training, the rendering is not needed and the performance can be increased." }, { "code": null, "e": 8078, "s": 8020, "text": "Here is the above code running with some keyboard inputs:" }, { "code": null, "e": 8325, "s": 8078, "text": "For now, we will be using a manually created static level. Creating one can be a tedious task. We will use Matplotlib to make our live a little bit easier. With the plt.ginput() function, coordinates can be captured by clicking inside the figure." }, { "code": null, "e": 8575, "s": 8325, "text": "These coordinates will be printed into the console, from where you can copy them into your code. A little reformatting should make it possible to include them into our environment, for example by storing them in numpy array as seen in rocket_gym.py." }, { "code": null, "e": 8595, "s": 8575, "text": "Collision Detection" }, { "code": null, "e": 8716, "s": 8595, "text": "Let’s assume we have the level boundary stored as an array of the size n*4, each line holding the points of one segment:" }, { "code": null, "e": 8904, "s": 8716, "text": "If two lines intersect can be checked by the following function. If the lines intersect, coordinates of the intersecting point are returned. If there is no intersection, None is returned." }, { "code": null, "e": 9046, "s": 8904, "text": "Now, we can apply the formula to our problem. We do this by checking, if any of the environment boundaries intersect with the movement vector" } ]
C# | Copy the entire LinkedList<T> to Array - GeeksforGeeks
01 Feb, 2019 LinkedList<T>.CopyTo(T[], Int32) method is used to copy the entire LinkedList<T> to a compatible one-dimensional Array, starting at the specified index of the target array. Syntax: public void CopyTo (T[] array, int index); Parameters: array : It is the one-dimensional Array that is the destination of the elements copied from LinkedList. The Array must have zero-based indexing. index : It is the zero-based index in array at which copying begins. Exceptions: ArgumentNullException : If the array is null. ArgumentOutOfRangeException : If the index is less than zero. ArgumentException : If the number of elements in the source LinkedList is greater than the available space from index to the end of the destination array. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to copy LinkedList to// Array, starting at the specified// index of the target arrayusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("A"); myList.AddLast("B"); myList.AddLast("C"); myList.AddLast("D"); myList.AddLast("E"); // Creating a string array string[] myArr = new string[1000]; // Copying LinkedList to Array, // starting at the specified index // of the target array myList.CopyTo(myArr, 0); // Displaying elements in array myArr foreach(string str in myArr) { Console.WriteLine(str); } }} Output: A B C D E Example 2: // C# code to copy LinkedList to// Array, starting at the specified// index of the target arrayusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(5); myList.AddLast(7); myList.AddLast(9); myList.AddLast(11); myList.AddLast(12); // Creating an Integer array int[] myArr = new int[100]; // Copying LinkedList to Array, // starting at the specified index // of the target array // This should raise "ArgumentOutOfRangeException" // as index is less than 0 myList.CopyTo(myArr, -2); // Displaying elements in array myArr foreach(int i in myArr) { Console.WriteLine(i); } }} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: Non-negative number required.Parameter name: index Note: The elements are copied to the Array in the same order in which the enumerator iterates through the LinkedList. This method is an O(n) operation, where n is Count. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.copyto?view=netframework-4.7.2 CSharp-Generic-Namespace CSharp-LinkedList CSharp-LinkedList-Methods C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24475, "s": 24302, "text": "LinkedList<T>.CopyTo(T[], Int32) method is used to copy the entire LinkedList<T> to a compatible one-dimensional Array, starting at the specified index of the target array." }, { "code": null, "e": 24483, "s": 24475, "text": "Syntax:" }, { "code": null, "e": 24527, "s": 24483, "text": "public void CopyTo (T[] array, int index);\n" }, { "code": null, "e": 24539, "s": 24527, "text": "Parameters:" }, { "code": null, "e": 24684, "s": 24539, "text": "array : It is the one-dimensional Array that is the destination of the elements copied from LinkedList. The Array must have zero-based indexing." }, { "code": null, "e": 24753, "s": 24684, "text": "index : It is the zero-based index in array at which copying begins." }, { "code": null, "e": 24765, "s": 24753, "text": "Exceptions:" }, { "code": null, "e": 24811, "s": 24765, "text": "ArgumentNullException : If the array is null." }, { "code": null, "e": 24873, "s": 24811, "text": "ArgumentOutOfRangeException : If the index is less than zero." }, { "code": null, "e": 25028, "s": 24873, "text": "ArgumentException : If the number of elements in the source LinkedList is greater than the available space from index to the end of the destination array." }, { "code": null, "e": 25108, "s": 25028, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25119, "s": 25108, "text": "Example 1:" }, { "code": "// C# code to copy LinkedList to// Array, starting at the specified// index of the target arrayusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"A\"); myList.AddLast(\"B\"); myList.AddLast(\"C\"); myList.AddLast(\"D\"); myList.AddLast(\"E\"); // Creating a string array string[] myArr = new string[1000]; // Copying LinkedList to Array, // starting at the specified index // of the target array myList.CopyTo(myArr, 0); // Displaying elements in array myArr foreach(string str in myArr) { Console.WriteLine(str); } }}", "e": 26001, "s": 25119, "text": null }, { "code": null, "e": 26009, "s": 26001, "text": "Output:" }, { "code": null, "e": 26020, "s": 26009, "text": "A\nB\nC\nD\nE\n" }, { "code": null, "e": 26031, "s": 26020, "text": "Example 2:" }, { "code": "// C# code to copy LinkedList to// Array, starting at the specified// index of the target arrayusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(5); myList.AddLast(7); myList.AddLast(9); myList.AddLast(11); myList.AddLast(12); // Creating an Integer array int[] myArr = new int[100]; // Copying LinkedList to Array, // starting at the specified index // of the target array // This should raise \"ArgumentOutOfRangeException\" // as index is less than 0 myList.CopyTo(myArr, -2); // Displaying elements in array myArr foreach(int i in myArr) { Console.WriteLine(i); } }}", "e": 26981, "s": 26031, "text": null }, { "code": null, "e": 26996, "s": 26981, "text": "Runtime Error:" }, { "code": null, "e": 27103, "s": 26996, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Non-negative number required.Parameter name: index" }, { "code": null, "e": 27109, "s": 27103, "text": "Note:" }, { "code": null, "e": 27221, "s": 27109, "text": "The elements are copied to the Array in the same order in which the enumerator iterates through the LinkedList." }, { "code": null, "e": 27273, "s": 27221, "text": "This method is an O(n) operation, where n is Count." }, { "code": null, "e": 27284, "s": 27273, "text": "Reference:" }, { "code": null, "e": 27399, "s": 27284, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.copyto?view=netframework-4.7.2" }, { "code": null, "e": 27424, "s": 27399, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27442, "s": 27424, "text": "CSharp-LinkedList" }, { "code": null, "e": 27468, "s": 27442, "text": "CSharp-LinkedList-Methods" }, { "code": null, "e": 27471, "s": 27468, "text": "C#" }, { "code": null, "e": 27569, "s": 27471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27587, "s": 27569, "text": "Destructors in C#" }, { "code": null, "e": 27610, "s": 27587, "text": "Extension Method in C#" }, { "code": null, "e": 27638, "s": 27610, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27678, "s": 27638, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27721, "s": 27678, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27743, "s": 27721, "text": "Partial Classes in C#" }, { "code": null, "e": 27760, "s": 27743, "text": "C# | Inheritance" }, { "code": null, "e": 27776, "s": 27760, "text": "C# | List Class" }, { "code": null, "e": 27826, "s": 27776, "text": "Difference between Hashtable and Dictionary in C#" } ]
Double Brace Initialization in Java - GeeksforGeeks
24 Dec, 2021 The combination of two separate processes in Java is known as Double Brace Initialization in Java. As the name suggests, there are two braces {{ included in it. A single brace { is nothing new for programmers. The first brace in the double brace initialization is used to create an anonymous inner class. We have made many anonymous inner classes in such a way. The second brace is what makes it different from the normal braces in Java. The second brace is the initialization block which is used with the declared anonymous inner class. When this initialization block is used with the anonymous inner class, it is known as Java double brace initialization. It has fewer lines of code compared to the native way of creation and initialization. The code is more readable. Creation and Initialization are done in the same expression. It is Obscure and is not a widely known way to do the initialization. It creates an extra class every time we use it. It doesn’t support the use of the “diamond operator” – a feature introduced in Java 7. It doesn’t work if the class we are trying to extend is marked as final. It holds a hidden reference to the enclosing instance, which may cause memory leaks. Note: It’s due to these disadvantages that double brace initialization is considered as an anti-pattern. Implementation: Geeks, if you are unaware of double brace initialization you are already using the standard approach that is without double brace initialization for which we have proposed a sample below as follows: Procedure: When we use a collection in a code, we typically do the following. Declare a variable for a temporary collection.Create a new empty collection and store a reference to it in the variable.Put things into the collection.Pass the collection to the method. Declare a variable for a temporary collection. Create a new empty collection and store a reference to it in the variable. Put things into the collection. Pass the collection to the method. Example: Standard Approach Java // Java program to Demonstrate Working of Collections// Without Double Brace Initialization // Importing required classesimport java.util.HashSet;import java.util.Set; // Main class// DoubleBracepublic class GFG { // Method 1 // Main driver method public static void main(String[] args) { // Creating an empty HashSet of string entries Set<String> sets = new HashSet<String>(); // Adding elements to Set // using add() method sets.add("one"); sets.add("two"); sets.add("three"); // Calling method 2 inside main() method // Now pass above collection as parameter to method useInSomeMethod(sets); } // Method 2 // Helper method private static void useInSomeMethod(Set<String> sets) { // Print all elements of desired Set // where method is invoked System.out.println(sets); }} [one, two, three] Output explanation: Above are normal steps we all follow in our coding practices. Don’t you feel that Java should have a more convenient syntax for collections (lists, maps, sets, etc.)? Let’s see another easy way of doing it. This is known as double brace initialization. Java Double Brace Initialization is used to combine the creation and initialization in a single statement. Using double brace initialization, we can initialize collections. Procedure: When we use a double brace initialization in a code, we typically do the following. Create an anonymous inner class that extends sets.Provide an instance initialization block that invokes the add method and adds the elements to the set.Pass the set to the method. Create an anonymous inner class that extends sets. Provide an instance initialization block that invokes the add method and adds the elements to the set. Pass the set to the method. Example: Java // Java program to Demonstrate Working of Collections// With Double Brace Initialization // Importing required classesimport java.util.HashSet;import java.util.Set; // Main class// DoubleBracepublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty HashSet Set<String> sets = new HashSet<String>() // Double brace { { // Adding elements to above HashSet // This is double brace initialization add("one"); add("two"); add("three"); } }; // ... // Now pass above collection as parameter to method // Calling method 2 inside main() method useInSomeMethod(sets); } // Method 2 private static void useInSomeMethod(Set<String> sets) { // Print elements of the desired Set // where method is invoked System.out.println(sets); }} [one, two, three] Output Explanation: The first brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are creating a subclass of the HashSet class so that this inner class can use the add() method. The second braces are instance initializers. The code an instance initializers inside is executed whenever an instance is created. This article is contributed by Saumya Mishra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nishkarshgandhi solankimayank Java-Collections Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples Java Math random() method with Examples HashMap containsKey() Method in Java How to Create Array of Objects in Java? Convert Double to Integer in Java Iterating over ArrayLists in Java Generating random numbers in Java
[ { "code": null, "e": 23583, "s": 23555, "text": "\n24 Dec, 2021" }, { "code": null, "e": 23744, "s": 23583, "text": "The combination of two separate processes in Java is known as Double Brace Initialization in Java. As the name suggests, there are two braces {{ included in it." }, { "code": null, "e": 24241, "s": 23744, "text": "A single brace { is nothing new for programmers. The first brace in the double brace initialization is used to create an anonymous inner class. We have made many anonymous inner classes in such a way. The second brace is what makes it different from the normal braces in Java. The second brace is the initialization block which is used with the declared anonymous inner class. When this initialization block is used with the anonymous inner class, it is known as Java double brace initialization." }, { "code": null, "e": 24327, "s": 24241, "text": "It has fewer lines of code compared to the native way of creation and initialization." }, { "code": null, "e": 24354, "s": 24327, "text": "The code is more readable." }, { "code": null, "e": 24415, "s": 24354, "text": "Creation and Initialization are done in the same expression." }, { "code": null, "e": 24485, "s": 24415, "text": "It is Obscure and is not a widely known way to do the initialization." }, { "code": null, "e": 24533, "s": 24485, "text": "It creates an extra class every time we use it." }, { "code": null, "e": 24620, "s": 24533, "text": "It doesn’t support the use of the “diamond operator” – a feature introduced in Java 7." }, { "code": null, "e": 24693, "s": 24620, "text": "It doesn’t work if the class we are trying to extend is marked as final." }, { "code": null, "e": 24778, "s": 24693, "text": "It holds a hidden reference to the enclosing instance, which may cause memory leaks." }, { "code": null, "e": 24883, "s": 24778, "text": "Note: It’s due to these disadvantages that double brace initialization is considered as an anti-pattern." }, { "code": null, "e": 24899, "s": 24883, "text": "Implementation:" }, { "code": null, "e": 25100, "s": 24899, "text": "Geeks, if you are unaware of double brace initialization you are already using the standard approach that is without double brace initialization for which we have proposed a sample below as follows: " }, { "code": null, "e": 25178, "s": 25100, "text": "Procedure: When we use a collection in a code, we typically do the following." }, { "code": null, "e": 25364, "s": 25178, "text": "Declare a variable for a temporary collection.Create a new empty collection and store a reference to it in the variable.Put things into the collection.Pass the collection to the method." }, { "code": null, "e": 25411, "s": 25364, "text": "Declare a variable for a temporary collection." }, { "code": null, "e": 25486, "s": 25411, "text": "Create a new empty collection and store a reference to it in the variable." }, { "code": null, "e": 25518, "s": 25486, "text": "Put things into the collection." }, { "code": null, "e": 25553, "s": 25518, "text": "Pass the collection to the method." }, { "code": null, "e": 25580, "s": 25553, "text": "Example: Standard Approach" }, { "code": null, "e": 25585, "s": 25580, "text": "Java" }, { "code": "// Java program to Demonstrate Working of Collections// Without Double Brace Initialization // Importing required classesimport java.util.HashSet;import java.util.Set; // Main class// DoubleBracepublic class GFG { // Method 1 // Main driver method public static void main(String[] args) { // Creating an empty HashSet of string entries Set<String> sets = new HashSet<String>(); // Adding elements to Set // using add() method sets.add(\"one\"); sets.add(\"two\"); sets.add(\"three\"); // Calling method 2 inside main() method // Now pass above collection as parameter to method useInSomeMethod(sets); } // Method 2 // Helper method private static void useInSomeMethod(Set<String> sets) { // Print all elements of desired Set // where method is invoked System.out.println(sets); }}", "e": 26485, "s": 25585, "text": null }, { "code": null, "e": 26503, "s": 26485, "text": "[one, two, three]" }, { "code": null, "e": 26523, "s": 26503, "text": "Output explanation:" }, { "code": null, "e": 26949, "s": 26523, "text": "Above are normal steps we all follow in our coding practices. Don’t you feel that Java should have a more convenient syntax for collections (lists, maps, sets, etc.)? Let’s see another easy way of doing it. This is known as double brace initialization. Java Double Brace Initialization is used to combine the creation and initialization in a single statement. Using double brace initialization, we can initialize collections." }, { "code": null, "e": 27044, "s": 26949, "text": "Procedure: When we use a double brace initialization in a code, we typically do the following." }, { "code": null, "e": 27224, "s": 27044, "text": "Create an anonymous inner class that extends sets.Provide an instance initialization block that invokes the add method and adds the elements to the set.Pass the set to the method." }, { "code": null, "e": 27275, "s": 27224, "text": "Create an anonymous inner class that extends sets." }, { "code": null, "e": 27378, "s": 27275, "text": "Provide an instance initialization block that invokes the add method and adds the elements to the set." }, { "code": null, "e": 27406, "s": 27378, "text": "Pass the set to the method." }, { "code": null, "e": 27415, "s": 27406, "text": "Example:" }, { "code": null, "e": 27420, "s": 27415, "text": "Java" }, { "code": "// Java program to Demonstrate Working of Collections// With Double Brace Initialization // Importing required classesimport java.util.HashSet;import java.util.Set; // Main class// DoubleBracepublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty HashSet Set<String> sets = new HashSet<String>() // Double brace { { // Adding elements to above HashSet // This is double brace initialization add(\"one\"); add(\"two\"); add(\"three\"); } }; // ... // Now pass above collection as parameter to method // Calling method 2 inside main() method useInSomeMethod(sets); } // Method 2 private static void useInSomeMethod(Set<String> sets) { // Print elements of the desired Set // where method is invoked System.out.println(sets); }}", "e": 28399, "s": 27420, "text": null }, { "code": null, "e": 28417, "s": 28399, "text": "[one, two, three]" }, { "code": null, "e": 28819, "s": 28417, "text": "Output Explanation: The first brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are creating a subclass of the HashSet class so that this inner class can use the add() method. The second braces are instance initializers. The code an instance initializers inside is executed whenever an instance is created. " }, { "code": null, "e": 29241, "s": 28819, "text": "This article is contributed by Saumya Mishra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29257, "s": 29241, "text": "nishkarshgandhi" }, { "code": null, "e": 29271, "s": 29257, "text": "solankimayank" }, { "code": null, "e": 29288, "s": 29271, "text": "Java-Collections" }, { "code": null, "e": 29293, "s": 29288, "text": "Java" }, { "code": null, "e": 29312, "s": 29293, "text": "Technical Scripter" }, { "code": null, "e": 29317, "s": 29312, "text": "Java" }, { "code": null, "e": 29334, "s": 29317, "text": "Java-Collections" }, { "code": null, "e": 29432, "s": 29334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29441, "s": 29432, "text": "Comments" }, { "code": null, "e": 29454, "s": 29441, "text": "Old Comments" }, { "code": null, "e": 29472, "s": 29454, "text": "Hashtable in Java" }, { "code": null, "e": 29493, "s": 29472, "text": "Constructors in Java" }, { "code": null, "e": 29539, "s": 29493, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29582, "s": 29539, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29622, "s": 29582, "text": "Java Math random() method with Examples" }, { "code": null, "e": 29659, "s": 29622, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 29699, "s": 29659, "text": "How to Create Array of Objects in Java?" }, { "code": null, "e": 29733, "s": 29699, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29767, "s": 29733, "text": "Iterating over ArrayLists in Java" } ]
ios manipulators internal() function in C++ - GeeksforGeeks
02 Sep, 2019 The internal() method of stream manipulators in C++ is used to set the adjustfield format flag for the specified str stream. This flag sets the adjustfield to internal. It means that the number in the output will be padded to the field width by inserting fill characters at a specified internal point. Syntax: ios_base& internal (ios_base& str) Parameters: This method accepts str as a parameter which is the stream for which the format flag is affected. Return Value: This method returns the stream str with internal format flag set. Example 1: // C++ code to demonstrate// the working of internal() function #include <iostream> using namespace std; int main(){ // Initializing the integer double x = -1.23; cout.precision(5); // Using internal() cout << "internal flag: "; cout.width(12); cout << internal << x << endl; return 0;} internal flag: - 1.23 Example 2: // C++ code to demonstrate// the working of internal() function #include <iostream> using namespace std; int main(){ // Initializing the integer double x = -1.23; cout.precision(5); // Using internal() cout << "internal flag: "; cout.width(12); cout << internal << x << endl; return 0;} internal flag: - 1.23 Reference: http://www.cplusplus.com/reference/ios/internal/ cpp-ios cpp-manipulators C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Friend class and function in C++ Polymorphism in C++ List in C++ Standard Template Library (STL) Pair in C++ Standard Template Library (STL) Convert string to char array in C++ new and delete operators in C++ for dynamic memory Destructors in C++ Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23707, "s": 23679, "text": "\n02 Sep, 2019" }, { "code": null, "e": 24009, "s": 23707, "text": "The internal() method of stream manipulators in C++ is used to set the adjustfield format flag for the specified str stream. This flag sets the adjustfield to internal. It means that the number in the output will be padded to the field width by inserting fill characters at a specified internal point." }, { "code": null, "e": 24017, "s": 24009, "text": "Syntax:" }, { "code": null, "e": 24053, "s": 24017, "text": "ios_base& internal (ios_base& str)\n" }, { "code": null, "e": 24163, "s": 24053, "text": "Parameters: This method accepts str as a parameter which is the stream for which the format flag is affected." }, { "code": null, "e": 24243, "s": 24163, "text": "Return Value: This method returns the stream str with internal format flag set." }, { "code": null, "e": 24254, "s": 24243, "text": "Example 1:" }, { "code": "// C++ code to demonstrate// the working of internal() function #include <iostream> using namespace std; int main(){ // Initializing the integer double x = -1.23; cout.precision(5); // Using internal() cout << \"internal flag: \"; cout.width(12); cout << internal << x << endl; return 0;}", "e": 24578, "s": 24254, "text": null }, { "code": null, "e": 24607, "s": 24578, "text": "internal flag: - 1.23\n" }, { "code": null, "e": 24618, "s": 24607, "text": "Example 2:" }, { "code": "// C++ code to demonstrate// the working of internal() function #include <iostream> using namespace std; int main(){ // Initializing the integer double x = -1.23; cout.precision(5); // Using internal() cout << \"internal flag: \"; cout.width(12); cout << internal << x << endl; return 0;}", "e": 24942, "s": 24618, "text": null }, { "code": null, "e": 24971, "s": 24942, "text": "internal flag: - 1.23\n" }, { "code": null, "e": 25031, "s": 24971, "text": "Reference: http://www.cplusplus.com/reference/ios/internal/" }, { "code": null, "e": 25039, "s": 25031, "text": "cpp-ios" }, { "code": null, "e": 25056, "s": 25039, "text": "cpp-manipulators" }, { "code": null, "e": 25060, "s": 25056, "text": "C++" }, { "code": null, "e": 25064, "s": 25060, "text": "CPP" }, { "code": null, "e": 25162, "s": 25064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25171, "s": 25162, "text": "Comments" }, { "code": null, "e": 25184, "s": 25171, "text": "Old Comments" }, { "code": null, "e": 25212, "s": 25184, "text": "Operator Overloading in C++" }, { "code": null, "e": 25236, "s": 25212, "text": "Sorting a vector in C++" }, { "code": null, "e": 25269, "s": 25236, "text": "Friend class and function in C++" }, { "code": null, "e": 25289, "s": 25269, "text": "Polymorphism in C++" }, { "code": null, "e": 25333, "s": 25289, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 25377, "s": 25333, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 25413, "s": 25377, "text": "Convert string to char array in C++" }, { "code": null, "e": 25464, "s": 25413, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 25483, "s": 25464, "text": "Destructors in C++" } ]
AIML - <topic> Tag
<topic> Tag is used in AIML to store a context so that later conversation can be done based on that context. Usually, <topic> tag is used in Yes/No type conversation. It helps AIML to search categories written within the context of the topic. Define a topic using <set> tag <template> <set name = "topic"> topic-name </set> </template> Define the category using <topic> tag <topic name = "topic-name"> <category> ... </category> </topic> For example, consider the following conversation. Human: let discuss movies Robot: Yes movies Human: Comedy movies are nice to watch Robot: Watching good movie refreshes our minds. Human: I like watching comedy Robot: I too like watching comedy. Here bot responds taking "movie" as the topic. Create topic.aiml inside C > ab > bots > test > aiml and topic.aiml.csv inside C > ab > bots > test > aimlif directories. <?xml version = "1.0" encoding = "UTF-8"?> <aiml version = "1.0.1" encoding = "UTF-8"?> <category> <pattern>LET DISCUSS MOVIES</pattern> <template>Yes <set name = "topic">movies</set></template> </category> <topic name = "movies"> <category> <pattern> * </pattern> <template>Watching good movie refreshes our minds.</template> </category> <category> <pattern> I LIKE WATCHING COMEDY! </pattern> <template>I like comedy movies too.</template> </category> </topic> </aiml> 0,LET DISCUSS MOVIES,*,*,Yes <set name = "topic">movies</set>,topic.aiml 0,*,*,movies,Watching good movie refreshes our minds.,topic.aiml 0,I LIKE WATCHING COMEDY!,*,movies,I like comedy movies too.,topic.aiml Open the command prompt. Go to C > ab > and type the following command − java -cp lib/Ab.jar Main bot = test action = chat trace = false You will see the following output − Human: let discuss movies Robot: Yes movies Human: Comedy movies are nice to watch Robot: Watching good movie refreshes our minds. Human: I like watching comedy Robot: I too like watching comedy. Print Add Notes Bookmark this page
[ { "code": null, "e": 2055, "s": 1811, "text": "<topic> Tag is used in AIML to store a context so that later conversation can be done based on that context. Usually, <topic> tag is used in Yes/No type conversation. It helps AIML to search categories written within the context of the topic. " }, { "code": null, "e": 2086, "s": 2055, "text": "Define a topic using <set> tag" }, { "code": null, "e": 2153, "s": 2086, "text": "<template> \n <set name = \"topic\"> topic-name </set>\n</template>\n" }, { "code": null, "e": 2191, "s": 2153, "text": "Define the category using <topic> tag" }, { "code": null, "e": 2272, "s": 2191, "text": "<topic name = \"topic-name\">\n <category>\n ...\n </category> \n</topic>" }, { "code": null, "e": 2322, "s": 2272, "text": "For example, consider the following conversation." }, { "code": null, "e": 2519, "s": 2322, "text": "Human: let discuss movies\nRobot: Yes movies\nHuman: Comedy movies are nice to watch\nRobot: Watching good movie refreshes our minds.\nHuman: I like watching comedy\nRobot: I too like watching comedy.\n" }, { "code": null, "e": 2566, "s": 2519, "text": "Here bot responds taking \"movie\" as the topic." }, { "code": null, "e": 2688, "s": 2566, "text": "Create topic.aiml inside C > ab > bots > test > aiml and topic.aiml.csv inside C > ab > bots > test > aimlif directories." }, { "code": null, "e": 3263, "s": 2688, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern>LET DISCUSS MOVIES</pattern>\n <template>Yes <set name = \"topic\">movies</set></template> \n </category>\n \n <topic name = \"movies\">\n <category>\n <pattern> * </pattern>\n <template>Watching good movie refreshes our minds.</template>\n </category>\n \n <category>\n <pattern> I LIKE WATCHING COMEDY! </pattern>\n <template>I like comedy movies too.</template>\n </category>\n \n </topic>\n</aiml>" }, { "code": null, "e": 3473, "s": 3263, "text": "0,LET DISCUSS MOVIES,*,*,Yes <set name = \"topic\">movies</set>,topic.aiml\n0,*,*,movies,Watching good movie refreshes our minds.,topic.aiml\n0,I LIKE WATCHING COMEDY!,*,movies,I like comedy movies too.,topic.aiml" }, { "code": null, "e": 3546, "s": 3473, "text": "Open the command prompt. Go to C > ab > and type the following command −" }, { "code": null, "e": 3611, "s": 3546, "text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n" }, { "code": null, "e": 3647, "s": 3611, "text": "You will see the following output −" }, { "code": null, "e": 3844, "s": 3647, "text": "Human: let discuss movies\nRobot: Yes movies\nHuman: Comedy movies are nice to watch\nRobot: Watching good movie refreshes our minds.\nHuman: I like watching comedy\nRobot: I too like watching comedy.\n" }, { "code": null, "e": 3851, "s": 3844, "text": " Print" }, { "code": null, "e": 3862, "s": 3851, "text": " Add Notes" } ]
CSS @media Rule - GeeksforGeeks
03 Nov, 2021 The @media CSS at-rule is used to apply a different set of styles for different media/devices using the Media Queries. A Media Query is mainly used to check the height, width, resolution, and orientation(Portrait/Landscape) of the device. This CSS rule is a way out for making more out of responsive design through delivering a more optimized design for specific screen type or device i.e smartphone, PC. The media queries can also be used for specifying certain styles only for printed documents or for screen readers. Syntax: @media not|only mediatype and (media feature and|or|not mediafeature) { // CSS Property } Used Keywords: not: It reverts the entire media query. only: It prevents the older browser(unsupported browsers) from applying the specified styles. and: It is used to combine two media types or media features. Media Types: all: It is the default media type. It is used for all media type devices. print: It is used for printer devices. screen: It is used for computer screens, mobile screens, etc. speech: It is used for screen readers that read the page. Media Features: There are many media features in Media Query some of them are listed below: any-hover: Any available input mechanism allow the user to hover over any element. any-pointer: It defines that any available input mechanism as a pointing device, and if so, how accurate is it? any-ratio: It is used to set the ratio between width and height of the viewport. color: It is used to set the color components of the output devices. color-gamut: It is used to set the color range that is to support by the user agent or in output devices. color-index: It is used to set the number of colors that the device can display. grid: It is used to specify the size of rows and columns. height: It is used to set the height of the viewport. hover: It allows the user to hover over any elements. inverted-colors: This defines does any device inverting colors light-level: It defines the light level. max-aspect-ratio: It is used to set the max ratio of width and height. max-color: It is used to set the maximum number of bits per color component for an output device. max-color-index; It is used to set the maximum number of colors that the device can display. max-height: It sets the max height of the browser display area. max-monochrome: It is used to set the maximum number of bits per “color” on a monochrome device. max-resolution: It is used to set the max resolution of the output device. max-width: It sets the max-width of the browser display area. min-aspect-ratio: It is used to set the min ratio of width and height. min-color: It is used to set the minimum number of bits per color component for an output device. min-color-index; It is used to set the min number of colors that the device can display. min-height: It sets the minimum height of the browser display area. max-monochrome: It is used to set a maximum number of bits per “color” on a monochrome device. min-resolution: It is used to set the min resolution of the output device. min-width: It sets the minimum width of the browser display area. monochrome: It is used to set the number of bits per “color” on a monochrome device. orientation: It is used to set the orientation of the viewport that landscape or portrait. overflow-block: It is used to control the situation when the content overflows the viewport. overflow-inline: It is used to control the situation when the content overflows the viewport along the inline axis be scrolled. pointer: It is a primary input mechanism for a pointing device. resolution: It sets the resolution of the device using dpi or dpcm. scan: It is used to do the scanning process of the output devices. scripting: Is there any scripting available like JS. update: It is used to update quickly update the output devices. width: It is used to set the width of the viewport. Example: This example illustrates the use of the @media rule to implement the various styling properties based on the result of one or more media queries. The @media rule will only work if the media query matches the device on which the content is being used. HTML <!DOCTYPE html><html> <head> <title> CSS @media rule </title> <style> @media screen and (max-width: 600px) { h1, h2 { color: green; font-size: 25px; } p { background-color: green; color: white; } } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS @media rule</h2> <p>GeeksforGeeks: A computer science portal</p> </body> </html> Output: From the output, we can see when screen width resizes less than or equal to 600px then the text color also changes to green. Supported Browsers: The browser supported by the @media rule are listed below: Google Chrome 21.0 Internet Explorer 9.0 Microsoft Edge Firefox 3.5 Opera 9 Safari 4.0 Code_r sagar0719kumar bhaskargeeksforgeeks CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23574, "s": 23546, "text": "\n03 Nov, 2021" }, { "code": null, "e": 24094, "s": 23574, "text": "The @media CSS at-rule is used to apply a different set of styles for different media/devices using the Media Queries. A Media Query is mainly used to check the height, width, resolution, and orientation(Portrait/Landscape) of the device. This CSS rule is a way out for making more out of responsive design through delivering a more optimized design for specific screen type or device i.e smartphone, PC. The media queries can also be used for specifying certain styles only for printed documents or for screen readers." }, { "code": null, "e": 24102, "s": 24094, "text": "Syntax:" }, { "code": null, "e": 24197, "s": 24102, "text": "@media not|only mediatype and (media feature and|or|not mediafeature) \n{\n // CSS Property\n}" }, { "code": null, "e": 24212, "s": 24197, "text": "Used Keywords:" }, { "code": null, "e": 24252, "s": 24212, "text": "not: It reverts the entire media query." }, { "code": null, "e": 24346, "s": 24252, "text": "only: It prevents the older browser(unsupported browsers) from applying the specified styles." }, { "code": null, "e": 24408, "s": 24346, "text": "and: It is used to combine two media types or media features." }, { "code": null, "e": 24421, "s": 24408, "text": "Media Types:" }, { "code": null, "e": 24495, "s": 24421, "text": "all: It is the default media type. It is used for all media type devices." }, { "code": null, "e": 24534, "s": 24495, "text": "print: It is used for printer devices." }, { "code": null, "e": 24596, "s": 24534, "text": "screen: It is used for computer screens, mobile screens, etc." }, { "code": null, "e": 24654, "s": 24596, "text": "speech: It is used for screen readers that read the page." }, { "code": null, "e": 24746, "s": 24654, "text": "Media Features: There are many media features in Media Query some of them are listed below:" }, { "code": null, "e": 24829, "s": 24746, "text": "any-hover: Any available input mechanism allow the user to hover over any element." }, { "code": null, "e": 24941, "s": 24829, "text": "any-pointer: It defines that any available input mechanism as a pointing device, and if so, how accurate is it?" }, { "code": null, "e": 25022, "s": 24941, "text": "any-ratio: It is used to set the ratio between width and height of the viewport." }, { "code": null, "e": 25091, "s": 25022, "text": "color: It is used to set the color components of the output devices." }, { "code": null, "e": 25197, "s": 25091, "text": "color-gamut: It is used to set the color range that is to support by the user agent or in output devices." }, { "code": null, "e": 25278, "s": 25197, "text": "color-index: It is used to set the number of colors that the device can display." }, { "code": null, "e": 25336, "s": 25278, "text": "grid: It is used to specify the size of rows and columns." }, { "code": null, "e": 25390, "s": 25336, "text": "height: It is used to set the height of the viewport." }, { "code": null, "e": 25444, "s": 25390, "text": "hover: It allows the user to hover over any elements." }, { "code": null, "e": 25507, "s": 25444, "text": "inverted-colors: This defines does any device inverting colors" }, { "code": null, "e": 25548, "s": 25507, "text": "light-level: It defines the light level." }, { "code": null, "e": 25619, "s": 25548, "text": "max-aspect-ratio: It is used to set the max ratio of width and height." }, { "code": null, "e": 25717, "s": 25619, "text": "max-color: It is used to set the maximum number of bits per color component for an output device." }, { "code": null, "e": 25810, "s": 25717, "text": "max-color-index; It is used to set the maximum number of colors that the device can display." }, { "code": null, "e": 25874, "s": 25810, "text": "max-height: It sets the max height of the browser display area." }, { "code": null, "e": 25971, "s": 25874, "text": "max-monochrome: It is used to set the maximum number of bits per “color” on a monochrome device." }, { "code": null, "e": 26046, "s": 25971, "text": "max-resolution: It is used to set the max resolution of the output device." }, { "code": null, "e": 26108, "s": 26046, "text": "max-width: It sets the max-width of the browser display area." }, { "code": null, "e": 26179, "s": 26108, "text": "min-aspect-ratio: It is used to set the min ratio of width and height." }, { "code": null, "e": 26277, "s": 26179, "text": "min-color: It is used to set the minimum number of bits per color component for an output device." }, { "code": null, "e": 26366, "s": 26277, "text": "min-color-index; It is used to set the min number of colors that the device can display." }, { "code": null, "e": 26434, "s": 26366, "text": "min-height: It sets the minimum height of the browser display area." }, { "code": null, "e": 26529, "s": 26434, "text": "max-monochrome: It is used to set a maximum number of bits per “color” on a monochrome device." }, { "code": null, "e": 26604, "s": 26529, "text": "min-resolution: It is used to set the min resolution of the output device." }, { "code": null, "e": 26670, "s": 26604, "text": "min-width: It sets the minimum width of the browser display area." }, { "code": null, "e": 26755, "s": 26670, "text": "monochrome: It is used to set the number of bits per “color” on a monochrome device." }, { "code": null, "e": 26846, "s": 26755, "text": "orientation: It is used to set the orientation of the viewport that landscape or portrait." }, { "code": null, "e": 26939, "s": 26846, "text": "overflow-block: It is used to control the situation when the content overflows the viewport." }, { "code": null, "e": 27067, "s": 26939, "text": "overflow-inline: It is used to control the situation when the content overflows the viewport along the inline axis be scrolled." }, { "code": null, "e": 27131, "s": 27067, "text": "pointer: It is a primary input mechanism for a pointing device." }, { "code": null, "e": 27199, "s": 27131, "text": "resolution: It sets the resolution of the device using dpi or dpcm." }, { "code": null, "e": 27266, "s": 27199, "text": "scan: It is used to do the scanning process of the output devices." }, { "code": null, "e": 27319, "s": 27266, "text": "scripting: Is there any scripting available like JS." }, { "code": null, "e": 27383, "s": 27319, "text": "update: It is used to update quickly update the output devices." }, { "code": null, "e": 27435, "s": 27383, "text": "width: It is used to set the width of the viewport." }, { "code": null, "e": 27695, "s": 27435, "text": "Example: This example illustrates the use of the @media rule to implement the various styling properties based on the result of one or more media queries. The @media rule will only work if the media query matches the device on which the content is being used." }, { "code": null, "e": 27700, "s": 27695, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS @media rule </title> <style> @media screen and (max-width: 600px) { h1, h2 { color: green; font-size: 25px; } p { background-color: green; color: white; } } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS @media rule</h2> <p>GeeksforGeeks: A computer science portal</p> </body> </html>", "e": 28137, "s": 27700, "text": null }, { "code": null, "e": 28270, "s": 28137, "text": "Output: From the output, we can see when screen width resizes less than or equal to 600px then the text color also changes to green." }, { "code": null, "e": 28349, "s": 28270, "text": "Supported Browsers: The browser supported by the @media rule are listed below:" }, { "code": null, "e": 28368, "s": 28349, "text": "Google Chrome 21.0" }, { "code": null, "e": 28390, "s": 28368, "text": "Internet Explorer 9.0" }, { "code": null, "e": 28405, "s": 28390, "text": "Microsoft Edge" }, { "code": null, "e": 28417, "s": 28405, "text": "Firefox 3.5" }, { "code": null, "e": 28425, "s": 28417, "text": "Opera 9" }, { "code": null, "e": 28436, "s": 28425, "text": "Safari 4.0" }, { "code": null, "e": 28443, "s": 28436, "text": "Code_r" }, { "code": null, "e": 28458, "s": 28443, "text": "sagar0719kumar" }, { "code": null, "e": 28479, "s": 28458, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28494, "s": 28479, "text": "CSS-Properties" }, { "code": null, "e": 28501, "s": 28494, "text": "Picked" }, { "code": null, "e": 28505, "s": 28501, "text": "CSS" }, { "code": null, "e": 28522, "s": 28505, "text": "Web Technologies" }, { "code": null, "e": 28620, "s": 28522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28682, "s": 28620, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28732, "s": 28682, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28790, "s": 28732, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28838, "s": 28790, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28888, "s": 28838, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 28930, "s": 28888, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28963, "s": 28930, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29006, "s": 28963, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29068, "s": 29006, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Make your own Audiobook using Azure Cognitive Service | by Sagnik Chattopadhyaya | Towards Data Science
Lets say you already have an PDF version of a book that you got from some sources (maybe for free) and you are not getting time to read it line by line. Also it may happen that you don’t want to spend money on buying its audio version or maybe its audio version is not available. Then this article is for you. In this article, you will see how you can make your own Audiobook using simple python scripts and text to speech feature of Azure Cognitive service. But first let me tell you a bit about an Audiobook. “An audiobook (or a talking book) is a recording of a book or other work being read out loud. A reading of the complete text is described as ‘unabridged’, while readings of a shorter version are an abridgement.” — Wikipedia. There are many services available in market that provide you the facility of an audiobook. Some of the popular one are Audible, Scribd, Audiobooks and many more. But all these charges you a subscription fee. So, let us start building our own audiobook. For that make sure you have the following prerequisites. Make sure you have Python 3.5 or later installed in your PC. In case you don’t have it, then you can install it from official website. In my PC, I have Python 3.6 installed and all these demo will be based on that. Don’t worry, there wont be any difference if you are working with the latest Python 3.9 .Next we will need something that will help us in working with PDF. For that Python has an awesome library, which would act as a PDF toolkit, known as PyPDF2. You can look at its full documentation also.We would also need an Azure account for using Azure Cognitive Services. But wait, we were looking for ways to make free Audiobook, right? Yes! Don’t worry I will tell things that comes for free. Make sure you have Python 3.5 or later installed in your PC. In case you don’t have it, then you can install it from official website. In my PC, I have Python 3.6 installed and all these demo will be based on that. Don’t worry, there wont be any difference if you are working with the latest Python 3.9 . Next we will need something that will help us in working with PDF. For that Python has an awesome library, which would act as a PDF toolkit, known as PyPDF2. You can look at its full documentation also. We would also need an Azure account for using Azure Cognitive Services. But wait, we were looking for ways to make free Audiobook, right? Yes! Don’t worry I will tell things that comes for free. First we will install PyPDF2. For that open your terminal or command prompt and type : pip install PyPDF2 Now if you are using Python (or maybe PIP) for the first time then its of high probability that you will get an error, something like “pip is not recognised as an internal or external command.....” . That basically means you didn’t set path for pip. Below I’m giving a link of an article that will explain in details how to solve it. medium.com Though we would need some other libraries but lets first look into working with the pdf. Our PyPDF2 library can do a huge variety of operations with a PDF file. Among which we will use reading capability of it. To do so we first need to create an python file (an file with .py as extension) and import the library. import PyPDF2 Then we will create an object called book which we will use to open our pdf in read mode. book = open("yourPdfName.pdf","rb") An important point to note here is the location of the pdf. The code above assumes that the desired pdf is in same folder as of the python file. In case it is in different folder then you have two options. 1: Move the file (pdf or python) to the same folder as of the other. 2: Give exact file location to the pdf file. Suppose my pdf is in Desktop then I would write, “C:\\Users\\Sagnik\\Desktop\\yourPdfName.pdf”. This would solve the problem. Now it might be a question that what is “rb” written towards the end. “rb” is basically an access mode used in file handling. To know more about other access modes or File handling in Python, refer to Python File Handling. stackabuse.com Till now we just opened our PDF file. Now we need to assign a reader who can read our pdf and extract text from the pdf file page by page. To do this we will use the following lines of code. reader = PyPDF2.PdfFileReader(book)for num in range(0,reader.numPages): text = reader.getPage(num).extractText() # print(text) Here the object reader makes use of PyPDF2 library to read our book. After that it goes through each page of the book and extract text from it by using a for-loop based on book page number. In case you are curious about what text it would read then you can go ahead and remove that ‘#’ and see what it prints. Even you can match it with the text from your pdf. Now we got our text and the only thing we are left with is to convert it to speech and listen to it. To do so we would use Azure Cognitive Service. To know more about Cognitive Services you can visit the links below. azure.microsoft.com docs.microsoft.com In order to use Azure Cognitive Services you would need an Azure account. But we need to get that for free, right? To do so, visit Azure Sign up page and select Start free to create your new Azure account. You can also watch this YouTube video for exact help in setting up your free account. If you are a student (like me) then you have three different options to get Azure account and use that for free. Using Azure for Students. But this would require you to sign in using your university email id (an .edu email). If your school doesn’t provide any such, then you have next two options. azure.microsoft.com Using GitHub Student developer pack. This pack has a huge number of other premium facilities as well. This gives you $100 Azure credits. education.github.com Becoming a Microsoft Learn Student Ambassador. This program gives you $150 Azure credit monthly and lot of other benefits including MTC voucher and a domain name for free. I am personally in huge love for this community. studentambassadors.microsoft.com After we got our Azure account, its time to create some Azure resources. But Why? For that we need to look at the definition of Azure Cognitive services to understand. Cognitive Services brings AI within reach of every developer — without requiring machine-learning expertise. All it takes is an API call to embed the ability to see, hear, speak, search, understand and accelerate decision-making into your apps. Enable developers of all skill levels to easily add AI capabilities to their apps. Now we can clearly see that we need to make an API call in order to embed the utilities of Cognitive Service. To make an API call we would need some keys and endpoints. And that would be provided by our Azure resource. For that first Sign in to the Azure portal. It would look something like shown below. Then we will head towards Create a resource and click on it. Look for the big plus (+) sign in top left and you will find the option there. Here you can find the list of all available services the Azure provides. Now search for Speech in the search bar, as shown in above image, and hit Enter. Then you can see a page like shown below. Now Click Create to create your Azure resources for Speech. It would now ask you about a name. Give a significant name to your resource. This name would help you find out your resource later. For me, I choose ‘learnoverflow’ as its name as our learning from this article should overflow. In the Subscription area choose a subscription or create a new one which you want to use. This basically determines how the Azure fees will be billed to you. but don’t worry you wont be billed anything this time. I will explain how in next few steps. It also asks for a Location. By that it means in which area you want to use the resource. Azure being a global platform, it offers you a large number of locations where you can create your resource. But in order to get best performance from your resource, choose a location that is nearest to you. Next comes an important part, this is the Pricing Tier. For Speech resource you would get two type of options: 1. Free F0 , 2. Standard S0 . Both have different advantages and benefits. If you use the free, low-volume Speech service tier you can keep this free subscription even after your free trial or service credit expires. And obviously we will use Free F0 for our Resource this time. This is the key to use this resource for free. If you are curious about all pricing tiers than you can see speech service pricing. In the Resource Group section create a new resource group for this Speech subscription or assign the subscription to an existing resource group. Resource groups are a container that help you keep your various Azure subscriptions organized by holding related resources at a place. Now that you have filled up all the details, just click on Create and wait for few seconds for resource allocation. Now click on ‘Go to resource’ to visit your resources. In the image above, you can see all the details about the resource. But we are searching for API key, right. On the overview page (the main page on which you land every time you open your resource) we don’t have so many work to do. Now look on the left panel (of the above image), I marked something in RED, this is Keys and Endpoints. All of our API key and other required information are in this tab. After you click on it, you would find something like the image below. Here you can see you have two API keys. Either one of the key is enough to access your Cognitive Service API. We would need one of the key and the location in our Python code. You can note them down in Notepad for future reference or can directly come over this page and find out as required. Now open your Python code editor and start implementing your API that you just got. But before that we would need to prepare our local machine to handle such API call. For that we need to make some Python package installations. We would require the Cognitive Service Speech SDK Python package. To do so we will again use pip command. pip install azure-cognitiveservices-speech This package would be completely helpful for us. We will start with importing the speech library we just installed. Add this to the 2nd line after previous import statement that we wrote previously. import azure.cognitiveservices.speech as sdk After that we will assign our API key and region to an variable in our Python code. This is basic setup of our subscription info. Keep these statements before the start of the for-loop that we wrote earlier. key = "YourSubscriptionKey"region = "YourServiceRegion" Replace YourSubscriptionKey and YourServiceRegion with the key and region you got after creating your Azure resources. After that we will create an instance of speech config with our subscription key and service region using the code below. config = sdk.SpeechConfig(subscription=key, region=region) We will move on to create our Speech Synthesizer using our default speaker as audio output. This would work as a human voice which is produced artificially. synthesizer = sdk.SpeechSynthesizer(speech_config=config) Now we will move inside the for-loop that we created earlier to read each pages of our book. Our approach will be to make a audio out of the text we get at each page we go through. But if you wish you can also modify the code to get the text of your whole book and then pass it through the below code. result = synthesizer.speak_text_async(text).get() Remember the variable text we created earlier? Now its time to synthesize the received text to speech. Once your Python Interpreter execute the above line, then you can expect your speaker to play the text written on the particular page. Once you hear a voice coming out of your computer speaker or from your earphone that is connected with your PC, you be sure that you finally made your own Audiobook. Hurray!!! If you wish to see this program in action, then at the end I will link a YouTube video where you can go through the whole article in a Video format. But before that let me discuss something important. If your are using this Azure Speech library for the first time then there can be few problems that you might face. It might prompt that “azure is not recognised as internal or external command” even though you have installed the proper libraries with the command written above. To avoid those make sure your pip in updated before you actually install the Speech SDK. Let us assume that you have already installed the Speech SDK and now you are getting these errors, then How to solve? In that case you will first need to uninstall your Speech SDK. pip uninstall azure-cognitiveservices-speech Then upgrade pip using the below command. Its always recommended to make sure your pip is updated before you install any libraries. python -m pip install --upgrade pip And after that install Azure speech SDK using the same command used previously. This would solve your issue. In any case you still face the same issue then you might need to install azure using the command below. pip install azure But don’t worry just upgrading your pip will definitely solve your problem. There can be a lot of Improvements that you can make to this. To listen to a particular book again and again you don’t need to run this program again again. You can actually save your generated audio in a your desired audio format. Also you can create your own custom voice. And many more other things with this. But remember that not all features come under the free tier API. If you are interested you can definitely view the Full Documentation of using this Text-to-Speech feature. Finally as you have successfully build your Audiobook, its time to listen to it. But this article is written document and its impossible to show final output here. So, below is a video implementation of the whole process of building it as shown in this article. Skip to 23:00 to only view its implementation. Hopefully this would help you. In this article, we have covered the implementation of a basic audiobook, that can read the entire book using a few lines of python code and Azure Cognitive Services. The end audio result of the audiobook is not the best, as the text needs some pre-processing before feeding to the speaker engine. Thank You for reading! I’m Sagnik Chattopadhyaya, a Microsoft Learn Student Ambassador. You can Visit my website to know more about me. Twitter: @sagnik_20 . YouTube: Learn Overflow Hope you got to learn something from this story. ❤ Happy Learning! 🐱‍💻
[ { "code": null, "e": 558, "s": 47, "text": "Lets say you already have an PDF version of a book that you got from some sources (maybe for free) and you are not getting time to read it line by line. Also it may happen that you don’t want to spend money on buying its audio version or maybe its audio version is not available. Then this article is for you. In this article, you will see how you can make your own Audiobook using simple python scripts and text to speech feature of Azure Cognitive service. But first let me tell you a bit about an Audiobook." }, { "code": null, "e": 783, "s": 558, "text": "“An audiobook (or a talking book) is a recording of a book or other work being read out loud. A reading of the complete text is described as ‘unabridged’, while readings of a shorter version are an abridgement.” — Wikipedia." }, { "code": null, "e": 991, "s": 783, "text": "There are many services available in market that provide you the facility of an audiobook. Some of the popular one are Audible, Scribd, Audiobooks and many more. But all these charges you a subscription fee." }, { "code": null, "e": 1093, "s": 991, "text": "So, let us start building our own audiobook. For that make sure you have the following prerequisites." }, { "code": null, "e": 1794, "s": 1093, "text": "Make sure you have Python 3.5 or later installed in your PC. In case you don’t have it, then you can install it from official website. In my PC, I have Python 3.6 installed and all these demo will be based on that. Don’t worry, there wont be any difference if you are working with the latest Python 3.9 .Next we will need something that will help us in working with PDF. For that Python has an awesome library, which would act as a PDF toolkit, known as PyPDF2. You can look at its full documentation also.We would also need an Azure account for using Azure Cognitive Services. But wait, we were looking for ways to make free Audiobook, right? Yes! Don’t worry I will tell things that comes for free." }, { "code": null, "e": 2099, "s": 1794, "text": "Make sure you have Python 3.5 or later installed in your PC. In case you don’t have it, then you can install it from official website. In my PC, I have Python 3.6 installed and all these demo will be based on that. Don’t worry, there wont be any difference if you are working with the latest Python 3.9 ." }, { "code": null, "e": 2302, "s": 2099, "text": "Next we will need something that will help us in working with PDF. For that Python has an awesome library, which would act as a PDF toolkit, known as PyPDF2. You can look at its full documentation also." }, { "code": null, "e": 2497, "s": 2302, "text": "We would also need an Azure account for using Azure Cognitive Services. But wait, we were looking for ways to make free Audiobook, right? Yes! Don’t worry I will tell things that comes for free." }, { "code": null, "e": 2584, "s": 2497, "text": "First we will install PyPDF2. For that open your terminal or command prompt and type :" }, { "code": null, "e": 2603, "s": 2584, "text": "pip install PyPDF2" }, { "code": null, "e": 2937, "s": 2603, "text": "Now if you are using Python (or maybe PIP) for the first time then its of high probability that you will get an error, something like “pip is not recognised as an internal or external command.....” . That basically means you didn’t set path for pip. Below I’m giving a link of an article that will explain in details how to solve it." }, { "code": null, "e": 2948, "s": 2937, "text": "medium.com" }, { "code": null, "e": 3037, "s": 2948, "text": "Though we would need some other libraries but lets first look into working with the pdf." }, { "code": null, "e": 3263, "s": 3037, "text": "Our PyPDF2 library can do a huge variety of operations with a PDF file. Among which we will use reading capability of it. To do so we first need to create an python file (an file with .py as extension) and import the library." }, { "code": null, "e": 3277, "s": 3263, "text": "import PyPDF2" }, { "code": null, "e": 3367, "s": 3277, "text": "Then we will create an object called book which we will use to open our pdf in read mode." }, { "code": null, "e": 3403, "s": 3367, "text": "book = open(\"yourPdfName.pdf\",\"rb\")" }, { "code": null, "e": 3849, "s": 3403, "text": "An important point to note here is the location of the pdf. The code above assumes that the desired pdf is in same folder as of the python file. In case it is in different folder then you have two options. 1: Move the file (pdf or python) to the same folder as of the other. 2: Give exact file location to the pdf file. Suppose my pdf is in Desktop then I would write, “C:\\\\Users\\\\Sagnik\\\\Desktop\\\\yourPdfName.pdf”. This would solve the problem." }, { "code": null, "e": 4072, "s": 3849, "text": "Now it might be a question that what is “rb” written towards the end. “rb” is basically an access mode used in file handling. To know more about other access modes or File handling in Python, refer to Python File Handling." }, { "code": null, "e": 4087, "s": 4072, "text": "stackabuse.com" }, { "code": null, "e": 4278, "s": 4087, "text": "Till now we just opened our PDF file. Now we need to assign a reader who can read our pdf and extract text from the pdf file page by page. To do this we will use the following lines of code." }, { "code": null, "e": 4411, "s": 4278, "text": "reader = PyPDF2.PdfFileReader(book)for num in range(0,reader.numPages): text = reader.getPage(num).extractText() # print(text)" }, { "code": null, "e": 4772, "s": 4411, "text": "Here the object reader makes use of PyPDF2 library to read our book. After that it goes through each page of the book and extract text from it by using a for-loop based on book page number. In case you are curious about what text it would read then you can go ahead and remove that ‘#’ and see what it prints. Even you can match it with the text from your pdf." }, { "code": null, "e": 4989, "s": 4772, "text": "Now we got our text and the only thing we are left with is to convert it to speech and listen to it. To do so we would use Azure Cognitive Service. To know more about Cognitive Services you can visit the links below." }, { "code": null, "e": 5009, "s": 4989, "text": "azure.microsoft.com" }, { "code": null, "e": 5028, "s": 5009, "text": "docs.microsoft.com" }, { "code": null, "e": 5320, "s": 5028, "text": "In order to use Azure Cognitive Services you would need an Azure account. But we need to get that for free, right? To do so, visit Azure Sign up page and select Start free to create your new Azure account. You can also watch this YouTube video for exact help in setting up your free account." }, { "code": null, "e": 5433, "s": 5320, "text": "If you are a student (like me) then you have three different options to get Azure account and use that for free." }, { "code": null, "e": 5618, "s": 5433, "text": "Using Azure for Students. But this would require you to sign in using your university email id (an .edu email). If your school doesn’t provide any such, then you have next two options." }, { "code": null, "e": 5638, "s": 5618, "text": "azure.microsoft.com" }, { "code": null, "e": 5775, "s": 5638, "text": "Using GitHub Student developer pack. This pack has a huge number of other premium facilities as well. This gives you $100 Azure credits." }, { "code": null, "e": 5796, "s": 5775, "text": "education.github.com" }, { "code": null, "e": 6017, "s": 5796, "text": "Becoming a Microsoft Learn Student Ambassador. This program gives you $150 Azure credit monthly and lot of other benefits including MTC voucher and a domain name for free. I am personally in huge love for this community." }, { "code": null, "e": 6050, "s": 6017, "text": "studentambassadors.microsoft.com" }, { "code": null, "e": 6218, "s": 6050, "text": "After we got our Azure account, its time to create some Azure resources. But Why? For that we need to look at the definition of Azure Cognitive services to understand." }, { "code": null, "e": 6546, "s": 6218, "text": "Cognitive Services brings AI within reach of every developer — without requiring machine-learning expertise. All it takes is an API call to embed the ability to see, hear, speak, search, understand and accelerate decision-making into your apps. Enable developers of all skill levels to easily add AI capabilities to their apps." }, { "code": null, "e": 6765, "s": 6546, "text": "Now we can clearly see that we need to make an API call in order to embed the utilities of Cognitive Service. To make an API call we would need some keys and endpoints. And that would be provided by our Azure resource." }, { "code": null, "e": 6851, "s": 6765, "text": "For that first Sign in to the Azure portal. It would look something like shown below." }, { "code": null, "e": 6991, "s": 6851, "text": "Then we will head towards Create a resource and click on it. Look for the big plus (+) sign in top left and you will find the option there." }, { "code": null, "e": 7187, "s": 6991, "text": "Here you can find the list of all available services the Azure provides. Now search for Speech in the search bar, as shown in above image, and hit Enter. Then you can see a page like shown below." }, { "code": null, "e": 7475, "s": 7187, "text": "Now Click Create to create your Azure resources for Speech. It would now ask you about a name. Give a significant name to your resource. This name would help you find out your resource later. For me, I choose ‘learnoverflow’ as its name as our learning from this article should overflow." }, { "code": null, "e": 7726, "s": 7475, "text": "In the Subscription area choose a subscription or create a new one which you want to use. This basically determines how the Azure fees will be billed to you. but don’t worry you wont be billed anything this time. I will explain how in next few steps." }, { "code": null, "e": 8024, "s": 7726, "text": "It also asks for a Location. By that it means in which area you want to use the resource. Azure being a global platform, it offers you a large number of locations where you can create your resource. But in order to get best performance from your resource, choose a location that is nearest to you." }, { "code": null, "e": 8545, "s": 8024, "text": "Next comes an important part, this is the Pricing Tier. For Speech resource you would get two type of options: 1. Free F0 , 2. Standard S0 . Both have different advantages and benefits. If you use the free, low-volume Speech service tier you can keep this free subscription even after your free trial or service credit expires. And obviously we will use Free F0 for our Resource this time. This is the key to use this resource for free. If you are curious about all pricing tiers than you can see speech service pricing." }, { "code": null, "e": 8825, "s": 8545, "text": "In the Resource Group section create a new resource group for this Speech subscription or assign the subscription to an existing resource group. Resource groups are a container that help you keep your various Azure subscriptions organized by holding related resources at a place." }, { "code": null, "e": 8941, "s": 8825, "text": "Now that you have filled up all the details, just click on Create and wait for few seconds for resource allocation." }, { "code": null, "e": 8996, "s": 8941, "text": "Now click on ‘Go to resource’ to visit your resources." }, { "code": null, "e": 9228, "s": 8996, "text": "In the image above, you can see all the details about the resource. But we are searching for API key, right. On the overview page (the main page on which you land every time you open your resource) we don’t have so many work to do." }, { "code": null, "e": 9469, "s": 9228, "text": "Now look on the left panel (of the above image), I marked something in RED, this is Keys and Endpoints. All of our API key and other required information are in this tab. After you click on it, you would find something like the image below." }, { "code": null, "e": 9762, "s": 9469, "text": "Here you can see you have two API keys. Either one of the key is enough to access your Cognitive Service API. We would need one of the key and the location in our Python code. You can note them down in Notepad for future reference or can directly come over this page and find out as required." }, { "code": null, "e": 9990, "s": 9762, "text": "Now open your Python code editor and start implementing your API that you just got. But before that we would need to prepare our local machine to handle such API call. For that we need to make some Python package installations." }, { "code": null, "e": 10096, "s": 9990, "text": "We would require the Cognitive Service Speech SDK Python package. To do so we will again use pip command." }, { "code": null, "e": 10139, "s": 10096, "text": "pip install azure-cognitiveservices-speech" }, { "code": null, "e": 10188, "s": 10139, "text": "This package would be completely helpful for us." }, { "code": null, "e": 10338, "s": 10188, "text": "We will start with importing the speech library we just installed. Add this to the 2nd line after previous import statement that we wrote previously." }, { "code": null, "e": 10383, "s": 10338, "text": "import azure.cognitiveservices.speech as sdk" }, { "code": null, "e": 10591, "s": 10383, "text": "After that we will assign our API key and region to an variable in our Python code. This is basic setup of our subscription info. Keep these statements before the start of the for-loop that we wrote earlier." }, { "code": null, "e": 10647, "s": 10591, "text": "key = \"YourSubscriptionKey\"region = \"YourServiceRegion\"" }, { "code": null, "e": 10888, "s": 10647, "text": "Replace YourSubscriptionKey and YourServiceRegion with the key and region you got after creating your Azure resources. After that we will create an instance of speech config with our subscription key and service region using the code below." }, { "code": null, "e": 10947, "s": 10888, "text": "config = sdk.SpeechConfig(subscription=key, region=region)" }, { "code": null, "e": 11104, "s": 10947, "text": "We will move on to create our Speech Synthesizer using our default speaker as audio output. This would work as a human voice which is produced artificially." }, { "code": null, "e": 11162, "s": 11104, "text": "synthesizer = sdk.SpeechSynthesizer(speech_config=config)" }, { "code": null, "e": 11464, "s": 11162, "text": "Now we will move inside the for-loop that we created earlier to read each pages of our book. Our approach will be to make a audio out of the text we get at each page we go through. But if you wish you can also modify the code to get the text of your whole book and then pass it through the below code." }, { "code": null, "e": 11514, "s": 11464, "text": "result = synthesizer.speak_text_async(text).get()" }, { "code": null, "e": 11752, "s": 11514, "text": "Remember the variable text we created earlier? Now its time to synthesize the received text to speech. Once your Python Interpreter execute the above line, then you can expect your speaker to play the text written on the particular page." }, { "code": null, "e": 11928, "s": 11752, "text": "Once you hear a voice coming out of your computer speaker or from your earphone that is connected with your PC, you be sure that you finally made your own Audiobook. Hurray!!!" }, { "code": null, "e": 12129, "s": 11928, "text": "If you wish to see this program in action, then at the end I will link a YouTube video where you can go through the whole article in a Video format. But before that let me discuss something important." }, { "code": null, "e": 12614, "s": 12129, "text": "If your are using this Azure Speech library for the first time then there can be few problems that you might face. It might prompt that “azure is not recognised as internal or external command” even though you have installed the proper libraries with the command written above. To avoid those make sure your pip in updated before you actually install the Speech SDK. Let us assume that you have already installed the Speech SDK and now you are getting these errors, then How to solve?" }, { "code": null, "e": 12677, "s": 12614, "text": "In that case you will first need to uninstall your Speech SDK." }, { "code": null, "e": 12722, "s": 12677, "text": "pip uninstall azure-cognitiveservices-speech" }, { "code": null, "e": 12854, "s": 12722, "text": "Then upgrade pip using the below command. Its always recommended to make sure your pip is updated before you install any libraries." }, { "code": null, "e": 12890, "s": 12854, "text": "python -m pip install --upgrade pip" }, { "code": null, "e": 12970, "s": 12890, "text": "And after that install Azure speech SDK using the same command used previously." }, { "code": null, "e": 13103, "s": 12970, "text": "This would solve your issue. In any case you still face the same issue then you might need to install azure using the command below." }, { "code": null, "e": 13121, "s": 13103, "text": "pip install azure" }, { "code": null, "e": 13197, "s": 13121, "text": "But don’t worry just upgrading your pip will definitely solve your problem." }, { "code": null, "e": 13682, "s": 13197, "text": "There can be a lot of Improvements that you can make to this. To listen to a particular book again and again you don’t need to run this program again again. You can actually save your generated audio in a your desired audio format. Also you can create your own custom voice. And many more other things with this. But remember that not all features come under the free tier API. If you are interested you can definitely view the Full Documentation of using this Text-to-Speech feature." }, { "code": null, "e": 14022, "s": 13682, "text": "Finally as you have successfully build your Audiobook, its time to listen to it. But this article is written document and its impossible to show final output here. So, below is a video implementation of the whole process of building it as shown in this article. Skip to 23:00 to only view its implementation. Hopefully this would help you." }, { "code": null, "e": 14320, "s": 14022, "text": "In this article, we have covered the implementation of a basic audiobook, that can read the entire book using a few lines of python code and Azure Cognitive Services. The end audio result of the audiobook is not the best, as the text needs some pre-processing before feeding to the speaker engine." }, { "code": null, "e": 14343, "s": 14320, "text": "Thank You for reading!" }, { "code": null, "e": 14456, "s": 14343, "text": "I’m Sagnik Chattopadhyaya, a Microsoft Learn Student Ambassador. You can Visit my website to know more about me." }, { "code": null, "e": 14502, "s": 14456, "text": "Twitter: @sagnik_20 . YouTube: Learn Overflow" }, { "code": null, "e": 14553, "s": 14502, "text": "Hope you got to learn something from this story. ❤" } ]
MobileNetV2: Inverted Residuals and Linear Bottlenecks | by Paul-Louis Pröve | Towards Data Science
In April 2017 a group of researchers from Google published a paper which introduced a neural network architecture that was optimized for mobile devices. They strived for a model that delivered high accuracy while keeping the parameters and mathematical operations as low as possible. This was much needed in order to bring deep neural networks to smartphones. The architecture dubbed MobileNet revolves around the idea of using depthwise separable convolutions, which consist of a depthwise and a pointwise convolution after one another. If you’re a little fuzzy on the details of this operation feel free to check out my other article that explains this concept in detail. MobileNetV2 extends its predecessor with 2 main ideas. Residual blocks connect the beginning and end of a convolutional block with a skip connection. By adding these two states the network has the opportunity of accessing earlier activations that weren’t modified in the convolutional block. This approach turned out to be essential in order to build networks of great depth. When looking a little closer at the skip connection we notice that an original residual block follows a wide->narrow->wide approach concerning the number of channels. The input has a high number of channels, which are compressed with an inexpensive 1x1 convolution. That way the following 3x3 convolution has far fewer parameters. In order to add input and output in the end the number of channels is increased again using another 1x1 convolution. In Keras it would look like this: def residual_block(x, squeeze=16, expand=64): m = Conv2D(squeeze, (1,1), activation='relu')(x) m = Conv2D(squeeze, (3,3), activation='relu')(m) m = Conv2D(expand, (1,1), activation='relu')(m) return Add()([m, x]) On the other hand, MobileNetV2 follows a narrow->wide->narrow approach. The first step widens the network using a 1x1 convolution because the following 3x3 depthwise convolution already greatly reduces the number of parameters. Afterwards another 1x1 convolution squeezes the network in order to match the initial number of channels. In Keras it would look like this: def inverted_residual_block(x, expand=64, squeeze=16): m = Conv2D(expand, (1,1), activation='relu')(x) m = DepthwiseConv2D((3,3), activation='relu')(m) m = Conv2D(squeeze, (1,1), activation='relu')(m) return Add()([m, x]) The authors describe this idea as an inverted residual block because skip connections exist between narrow parts of the network which is opposite of how an original residual connection works. When you run the two snippets above you will notice that the inverted block has far fewer parameters. The reason we use non-linear activation functions in neural networks is that multiple matrix multiplications cannot be reduced to a single numerical operation. It allows us to build neural networks that have multiple layers. At the same time the activation function ReLU, which is commonly used in neural networks, discards values that are smaller than 0. This loss of information can be tackled by increasing the number of channels in order to increase the capacity of the network. With inverted residual blocks we do the opposite and squeeze the layers where the skip connections are linked. This hurts the performance of the network. The authors introduced the idea of a linear bottleneck where the last convolution of a residual block has a linear output before it’s added to the initial activations. Putting this into code is super simple as we simply discard the last activation function of the convolutional block: def inverted_linear_residual_block(x, expand=64, squeeze=16): m = Conv2D(expand, (1,1), activation='relu')(x) m = DepthwiseConv2D((3,3), activation='relu')(m) m = Conv2D(squeeze, (1,1))(m) return Add()([m, x]) The snippet above shows the structure of a convolutional block that incorporates inverted residuals and linear bottlenecks. If you want to match MobileNetV2 as closely as possible there are two other pieces you need. The first aspect simply adds Batch Normalization behind every convolutional layer as you’re probably used to by now anyways. The second addition is not quite as common. The authors use ReLU6 instead of ReLU, which limits the value of activations to a maximum of...well...6. The activation is linear as long as it’s between 0 and 6. def relu(x): return max(0, x)def relu6(x): return min(max(0, x), 6) This is helpful when you’re dealing with fixed point inference. It limits the information left of the decimal point to 3 bits, meaning we have a guaranteed precision right of the decimal point. This was also used in the orignal MobileNet paper. The final building block looks like this: def bottleneck_block(x, expand=64, squeeze=16): m = Conv2D(expand, (1,1))(x) m = BatchNormalization()(m) m = Activation('relu6')(m) m = DepthwiseConv2D((3,3))(m) m = BatchNormalization()(m) m = Activation('relu6')(m) m = Conv2D(squeeze, (1,1))(m) m = BatchNormalization()(m) return Add()([m, x]) Now that we understand the building block of MobileNetV2 we can take a look at the entire architecture. In the table you can see how the bottleneck blocks are arranged. t stands for expansion rate of the channels. As you can see they used a factor of 6 opposed to the 4 in our example. c represents the number of input channels and n how often the block is repeated. Lastly s tells us whether the first repetition of a block used a stride of 2 for the downsampling process. All in all it’s a very simple and common assembly of convolutional blocks. Something that I’m particuarly happy about is the fact that MobileNetV2 provides a similar parameter efficiency to NASNet. NASNet is the current state of the art on several image recognition tasks. It’s building blocks are quite complex making it rather unintuitive why it works so well. The building block of NASNet were not designed by humans but by another neural network. Introducing a simple architecture like MobileNetV2 that shows a comparable efficiency makes me a little more confident that the next big architecture might be designed by a human being as well.
[ { "code": null, "e": 532, "s": 172, "text": "In April 2017 a group of researchers from Google published a paper which introduced a neural network architecture that was optimized for mobile devices. They strived for a model that delivered high accuracy while keeping the parameters and mathematical operations as low as possible. This was much needed in order to bring deep neural networks to smartphones." }, { "code": null, "e": 901, "s": 532, "text": "The architecture dubbed MobileNet revolves around the idea of using depthwise separable convolutions, which consist of a depthwise and a pointwise convolution after one another. If you’re a little fuzzy on the details of this operation feel free to check out my other article that explains this concept in detail. MobileNetV2 extends its predecessor with 2 main ideas." }, { "code": null, "e": 1222, "s": 901, "text": "Residual blocks connect the beginning and end of a convolutional block with a skip connection. By adding these two states the network has the opportunity of accessing earlier activations that weren’t modified in the convolutional block. This approach turned out to be essential in order to build networks of great depth." }, { "code": null, "e": 1704, "s": 1222, "text": "When looking a little closer at the skip connection we notice that an original residual block follows a wide->narrow->wide approach concerning the number of channels. The input has a high number of channels, which are compressed with an inexpensive 1x1 convolution. That way the following 3x3 convolution has far fewer parameters. In order to add input and output in the end the number of channels is increased again using another 1x1 convolution. In Keras it would look like this:" }, { "code": null, "e": 1921, "s": 1704, "text": "def residual_block(x, squeeze=16, expand=64): m = Conv2D(squeeze, (1,1), activation='relu')(x) m = Conv2D(squeeze, (3,3), activation='relu')(m) m = Conv2D(expand, (1,1), activation='relu')(m) return Add()([m, x])" }, { "code": null, "e": 2255, "s": 1921, "text": "On the other hand, MobileNetV2 follows a narrow->wide->narrow approach. The first step widens the network using a 1x1 convolution because the following 3x3 depthwise convolution already greatly reduces the number of parameters. Afterwards another 1x1 convolution squeezes the network in order to match the initial number of channels." }, { "code": null, "e": 2289, "s": 2255, "text": "In Keras it would look like this:" }, { "code": null, "e": 2515, "s": 2289, "text": "def inverted_residual_block(x, expand=64, squeeze=16): m = Conv2D(expand, (1,1), activation='relu')(x) m = DepthwiseConv2D((3,3), activation='relu')(m) m = Conv2D(squeeze, (1,1), activation='relu')(m) return Add()([m, x])" }, { "code": null, "e": 2809, "s": 2515, "text": "The authors describe this idea as an inverted residual block because skip connections exist between narrow parts of the network which is opposite of how an original residual connection works. When you run the two snippets above you will notice that the inverted block has far fewer parameters." }, { "code": null, "e": 3292, "s": 2809, "text": "The reason we use non-linear activation functions in neural networks is that multiple matrix multiplications cannot be reduced to a single numerical operation. It allows us to build neural networks that have multiple layers. At the same time the activation function ReLU, which is commonly used in neural networks, discards values that are smaller than 0. This loss of information can be tackled by increasing the number of channels in order to increase the capacity of the network." }, { "code": null, "e": 3731, "s": 3292, "text": "With inverted residual blocks we do the opposite and squeeze the layers where the skip connections are linked. This hurts the performance of the network. The authors introduced the idea of a linear bottleneck where the last convolution of a residual block has a linear output before it’s added to the initial activations. Putting this into code is super simple as we simply discard the last activation function of the convolutional block:" }, { "code": null, "e": 3946, "s": 3731, "text": "def inverted_linear_residual_block(x, expand=64, squeeze=16): m = Conv2D(expand, (1,1), activation='relu')(x) m = DepthwiseConv2D((3,3), activation='relu')(m) m = Conv2D(squeeze, (1,1))(m) return Add()([m, x])" }, { "code": null, "e": 4288, "s": 3946, "text": "The snippet above shows the structure of a convolutional block that incorporates inverted residuals and linear bottlenecks. If you want to match MobileNetV2 as closely as possible there are two other pieces you need. The first aspect simply adds Batch Normalization behind every convolutional layer as you’re probably used to by now anyways." }, { "code": null, "e": 4495, "s": 4288, "text": "The second addition is not quite as common. The authors use ReLU6 instead of ReLU, which limits the value of activations to a maximum of...well...6. The activation is linear as long as it’s between 0 and 6." }, { "code": null, "e": 4565, "s": 4495, "text": "def relu(x): return max(0, x)def relu6(x): return min(max(0, x), 6)" }, { "code": null, "e": 4852, "s": 4565, "text": "This is helpful when you’re dealing with fixed point inference. It limits the information left of the decimal point to 3 bits, meaning we have a guaranteed precision right of the decimal point. This was also used in the orignal MobileNet paper. The final building block looks like this:" }, { "code": null, "e": 5157, "s": 4852, "text": "def bottleneck_block(x, expand=64, squeeze=16): m = Conv2D(expand, (1,1))(x) m = BatchNormalization()(m) m = Activation('relu6')(m) m = DepthwiseConv2D((3,3))(m) m = BatchNormalization()(m) m = Activation('relu6')(m) m = Conv2D(squeeze, (1,1))(m) m = BatchNormalization()(m) return Add()([m, x])" }, { "code": null, "e": 5706, "s": 5157, "text": "Now that we understand the building block of MobileNetV2 we can take a look at the entire architecture. In the table you can see how the bottleneck blocks are arranged. t stands for expansion rate of the channels. As you can see they used a factor of 6 opposed to the 4 in our example. c represents the number of input channels and n how often the block is repeated. Lastly s tells us whether the first repetition of a block used a stride of 2 for the downsampling process. All in all it’s a very simple and common assembly of convolutional blocks." } ]
Real-time anomaly detection with Apache Kafka and Python | by Rodrigo Arenas | Towards Data Science
In this post, I'm going to discuss how to make real-time predictions with incoming stream data from Apache Kafka; the solution we are going to implement looks like this: The idea is to: Train an anomaly detection algorithm using unsupervised machine learning. Create a new data producer that sends the transactions to a Kafka topic. Read the data from the Kafka topic to make the prediction using the trained ml model. If the model detects that the transaction is an inlier, send it to another Kafka topic. Create the last consumer that reads the anomalies and sends an alert to a Slack channel. The article assumes that you know the basics of Apache Kafka, machine learning, and Python. The transactions could represent any relevant information to analyze in real-time and predict if there could be something out of the ordinary, such as credit card transactions, GPS logs, system consumption metrics, etc. Our project structure will look like this, you can get the complete code here or by using: git clone https://github.com/rodrigo-arenas/kafkaml-anomaly-detection.git First, check the settings.py; it has some variables we need to set, like the Kafka broker host and port; you can leave the ones by default (listening on localhost and default ports of Kafka and zookeeper). The streaming/utils.py file contains the configurations to create Kafka consumers and producers; it has some default options that you can also change if needed. Now install the requirements: pip install -r requirements.txt To illustrate how to set up this solution, we are going to generate random data; it will have two variables, they look like this: Next, we are going to use an Isolation Forest model to detect the outliers; in simple words, this model will try to isolate the data points by tracing random lines over one of the (sampled) variables axes and, after several iterations, measure how "hard" was to isolate each observation, so in the train.py file we have: After running this, the isolation_forest.joblib file should be created; this is the trained model. We will use two topics; the first one is called "transactions," where the producer will send new transactions records. Let's create it from the terminal with: kafka-topics.sh --zookeeper localhost:2181 --topic transactions --create --partitions 3 --replication-factor 1 The second topic is going to be called "anomalies," here is where the module that detects anomalies will send the data, and the last consumer will read it to send a slack notification: kafka-topics.sh --zookeeper localhost:2181 --topic anomalies --create --partitions 3 --replication-factor 1 Now we are going to generate the first producer that will send new data to the Kafka topic "transactions"; we'll use the confluent-Kafka package; in the file streaming/producer.py, we have: With this code, a producer will send data to a Kafka topic, with a probability of OUTLIERS_GENERATION_PROBABILITY; the data will come from an "outlier generator," will send an auto-incremental id, the data needed for the machine learning model and the current time in UTC. Let's check everything is correct so far, run the producer.py file, and logging to the topic as a consumer from the terminal: kafka-console-consumer.sh --bootstrap-server 127.0.0.1:9092 --topic transactions You should see the incoming messages like this: The data is coming! Now we must read it from a consumer, pass it to the machine learning model to make the predictions, and filter the outliers. This is done in the streaming/anomalies_detector.py file that looks like this: The consumer read messages from the "transactions" topic and a consumer to send outliers to the "anomalies" topic; besides the data we already had, it will enrich the record with the score given by the model, a measure of "how much" the data is considered an outlier. Notice that the only messages that go to the new topic are those whose prediction output is -1; this is how this model categorizes that the data is an inlier. Also, notice that the topic has three partitions, so at the end, I'm using multiprocessing to simulate three independent consumers and speed up the process; they all belong to the same group_id. In production probably those consumers will run in different servers. Let's check this step, make sure the producer is running and run the anomalies_detector.py file, now in a terminal, let's open the anomalies topic, we should see the incoming transactions that the model predicted as inlier, it should look like this: Here there is a visualization of how the transactions producer and outlier detection run simultaneously; the top window is the transaction producer topic, the bottom one is the outliers sent to the anomalies topic. As the last step, we want to take some actions with these detected outliers; in a real-life scenario, it could block a transaction, scale a server, generate a recommendation, send an alert to an administrative user, etc. Here we are going to send an alert to a Slack channel; for this, make sure to create a slack app, add the app to the slack channel and register an environment variable called SLACK_API_TOKEN to authenticate Slack. Here is the related documentation. Now we use the file streaming/bot_alerts.py; here is the code: So here, the script creates a new consumer, but it's subscribed to the "anomalies" topic; once a message arrives, it will use the Slack API to send the message; for this demo, I sent the same raw message (Try to make it prettier!). The incoming messages look like this: So that is it, the solution is up and running! I hope this was useful for you. Remember that the full code is here: github.com I want to leave some final considerations about this particular implementation: I made all the settings and running were made in a local machine, the choice of how many partitions, consumers, brokers, zookeeper servers, replicas to set (and others configurations) is something that you must analyze with the base of your business characteristics, the rate in how the data is generated, available resources, etc. I used small enough numbers for the demo. I used scikit-learn and "pure" Python to process the data streaming, but depending on the messages volume/production rate, it could be necessary to use streaming processing capabilities, like spark streaming. There are also limits on the Slack API you must be aware of.
[ { "code": null, "e": 342, "s": 172, "text": "In this post, I'm going to discuss how to make real-time predictions with incoming stream data from Apache Kafka; the solution we are going to implement looks like this:" }, { "code": null, "e": 358, "s": 342, "text": "The idea is to:" }, { "code": null, "e": 432, "s": 358, "text": "Train an anomaly detection algorithm using unsupervised machine learning." }, { "code": null, "e": 505, "s": 432, "text": "Create a new data producer that sends the transactions to a Kafka topic." }, { "code": null, "e": 591, "s": 505, "text": "Read the data from the Kafka topic to make the prediction using the trained ml model." }, { "code": null, "e": 679, "s": 591, "text": "If the model detects that the transaction is an inlier, send it to another Kafka topic." }, { "code": null, "e": 768, "s": 679, "text": "Create the last consumer that reads the anomalies and sends an alert to a Slack channel." }, { "code": null, "e": 860, "s": 768, "text": "The article assumes that you know the basics of Apache Kafka, machine learning, and Python." }, { "code": null, "e": 1080, "s": 860, "text": "The transactions could represent any relevant information to analyze in real-time and predict if there could be something out of the ordinary, such as credit card transactions, GPS logs, system consumption metrics, etc." }, { "code": null, "e": 1171, "s": 1080, "text": "Our project structure will look like this, you can get the complete code here or by using:" }, { "code": null, "e": 1245, "s": 1171, "text": "git clone https://github.com/rodrigo-arenas/kafkaml-anomaly-detection.git" }, { "code": null, "e": 1451, "s": 1245, "text": "First, check the settings.py; it has some variables we need to set, like the Kafka broker host and port; you can leave the ones by default (listening on localhost and default ports of Kafka and zookeeper)." }, { "code": null, "e": 1612, "s": 1451, "text": "The streaming/utils.py file contains the configurations to create Kafka consumers and producers; it has some default options that you can also change if needed." }, { "code": null, "e": 1642, "s": 1612, "text": "Now install the requirements:" }, { "code": null, "e": 1674, "s": 1642, "text": "pip install -r requirements.txt" }, { "code": null, "e": 1804, "s": 1674, "text": "To illustrate how to set up this solution, we are going to generate random data; it will have two variables, they look like this:" }, { "code": null, "e": 2125, "s": 1804, "text": "Next, we are going to use an Isolation Forest model to detect the outliers; in simple words, this model will try to isolate the data points by tracing random lines over one of the (sampled) variables axes and, after several iterations, measure how \"hard\" was to isolate each observation, so in the train.py file we have:" }, { "code": null, "e": 2224, "s": 2125, "text": "After running this, the isolation_forest.joblib file should be created; this is the trained model." }, { "code": null, "e": 2383, "s": 2224, "text": "We will use two topics; the first one is called \"transactions,\" where the producer will send new transactions records. Let's create it from the terminal with:" }, { "code": null, "e": 2494, "s": 2383, "text": "kafka-topics.sh --zookeeper localhost:2181 --topic transactions --create --partitions 3 --replication-factor 1" }, { "code": null, "e": 2679, "s": 2494, "text": "The second topic is going to be called \"anomalies,\" here is where the module that detects anomalies will send the data, and the last consumer will read it to send a slack notification:" }, { "code": null, "e": 2787, "s": 2679, "text": "kafka-topics.sh --zookeeper localhost:2181 --topic anomalies --create --partitions 3 --replication-factor 1" }, { "code": null, "e": 2977, "s": 2787, "text": "Now we are going to generate the first producer that will send new data to the Kafka topic \"transactions\"; we'll use the confluent-Kafka package; in the file streaming/producer.py, we have:" }, { "code": null, "e": 3250, "s": 2977, "text": "With this code, a producer will send data to a Kafka topic, with a probability of OUTLIERS_GENERATION_PROBABILITY; the data will come from an \"outlier generator,\" will send an auto-incremental id, the data needed for the machine learning model and the current time in UTC." }, { "code": null, "e": 3376, "s": 3250, "text": "Let's check everything is correct so far, run the producer.py file, and logging to the topic as a consumer from the terminal:" }, { "code": null, "e": 3457, "s": 3376, "text": "kafka-console-consumer.sh --bootstrap-server 127.0.0.1:9092 --topic transactions" }, { "code": null, "e": 3505, "s": 3457, "text": "You should see the incoming messages like this:" }, { "code": null, "e": 3729, "s": 3505, "text": "The data is coming! Now we must read it from a consumer, pass it to the machine learning model to make the predictions, and filter the outliers. This is done in the streaming/anomalies_detector.py file that looks like this:" }, { "code": null, "e": 3997, "s": 3729, "text": "The consumer read messages from the \"transactions\" topic and a consumer to send outliers to the \"anomalies\" topic; besides the data we already had, it will enrich the record with the score given by the model, a measure of \"how much\" the data is considered an outlier." }, { "code": null, "e": 4156, "s": 3997, "text": "Notice that the only messages that go to the new topic are those whose prediction output is -1; this is how this model categorizes that the data is an inlier." }, { "code": null, "e": 4421, "s": 4156, "text": "Also, notice that the topic has three partitions, so at the end, I'm using multiprocessing to simulate three independent consumers and speed up the process; they all belong to the same group_id. In production probably those consumers will run in different servers." }, { "code": null, "e": 4671, "s": 4421, "text": "Let's check this step, make sure the producer is running and run the anomalies_detector.py file, now in a terminal, let's open the anomalies topic, we should see the incoming transactions that the model predicted as inlier, it should look like this:" }, { "code": null, "e": 4886, "s": 4671, "text": "Here there is a visualization of how the transactions producer and outlier detection run simultaneously; the top window is the transaction producer topic, the bottom one is the outliers sent to the anomalies topic." }, { "code": null, "e": 5107, "s": 4886, "text": "As the last step, we want to take some actions with these detected outliers; in a real-life scenario, it could block a transaction, scale a server, generate a recommendation, send an alert to an administrative user, etc." }, { "code": null, "e": 5356, "s": 5107, "text": "Here we are going to send an alert to a Slack channel; for this, make sure to create a slack app, add the app to the slack channel and register an environment variable called SLACK_API_TOKEN to authenticate Slack. Here is the related documentation." }, { "code": null, "e": 5419, "s": 5356, "text": "Now we use the file streaming/bot_alerts.py; here is the code:" }, { "code": null, "e": 5689, "s": 5419, "text": "So here, the script creates a new consumer, but it's subscribed to the \"anomalies\" topic; once a message arrives, it will use the Slack API to send the message; for this demo, I sent the same raw message (Try to make it prettier!). The incoming messages look like this:" }, { "code": null, "e": 5805, "s": 5689, "text": "So that is it, the solution is up and running! I hope this was useful for you. Remember that the full code is here:" }, { "code": null, "e": 5816, "s": 5805, "text": "github.com" }, { "code": null, "e": 5896, "s": 5816, "text": "I want to leave some final considerations about this particular implementation:" }, { "code": null, "e": 6270, "s": 5896, "text": "I made all the settings and running were made in a local machine, the choice of how many partitions, consumers, brokers, zookeeper servers, replicas to set (and others configurations) is something that you must analyze with the base of your business characteristics, the rate in how the data is generated, available resources, etc. I used small enough numbers for the demo." }, { "code": null, "e": 6479, "s": 6270, "text": "I used scikit-learn and \"pure\" Python to process the data streaming, but depending on the messages volume/production rate, it could be necessary to use streaming processing capabilities, like spark streaming." } ]
How to use Machine Learning in Power BI with R | by Octavio Santiago | Towards Data Science
Microsoft has recently been making a strong move to align Open Source technologies and insert Artificial Intelligence technologies into its products, and Power BI is included in this plan. Power BI is one of the main tools for building dashboards today and Microsoft is increasing its development power and flexibility every day. To make the development of dashboards feasible, Power BI has several functionalities for data treatment, and one of the most important is the integration tool with R and more recently the integration with Python. The option of working with R and Python development languages ​​opens up a huge range of possibilities within the BI tool, and one of these possibilities is to work with Machine Learning tools and build models directly in Power BI. In this article I will be going step-by-step on how to train and make predictions with a machine learning model directly in PowerBI using the R language, from the following topics: Installing the dependenciesAnalyzing the dataHands-on — the codeResultsConclusion Installing the dependencies Analyzing the data Hands-on — the code Results Conclusion The first step is to install R Studio on your machine, as the development will be in the R language. As much as PowerBI has native integration with the R language, it requires the user to install the R packages on the machine. The download can be done through this link: https://www.rstudio.com/products/rstudio/download/ Right after installation, you must open R studio and install the dependency libraries. caret datasets monomvn To install the packages in R, the website R-bloggers has a great tutorial that teaches you how to install and load packages in R Studio. Link: https://www.r-bloggers.com/2013/01/how-to-install-packages-on-r-screenshots/ The dataset was obtained from the kaggle.com website and consists of beer consumption data at a university in São Paulo, together with the minimum, maximum and average temperatures for each day and the volumetric rainfall. To add another important feature I created a column called “Weekend” that indicates when the day is Saturday or Sunday, to take a little bit of the seasonality of consumption since the weekend presents a higher consumption, I could have considered Friday too, but for this first moment, I decided to be more conservative. For the tests, I put together a Bayesian linear regression model using the monomvn package (Bayesian Ridge Regression) to predict the beer consumption data in liters per day, along with validation through Cross Validation with 10 folds. I will not go into much of the model and its results in this article, as the goal is to focus more on integration with Power BI than on modeling. The first part of the code imports the libraries library(caret)library(datasets)library(monomvn) Right after we import the Power BI data as a dataset, inside the R mydata <- datasetmydata <- data.frame(mydata) With that we can create the model and perform the prediction. In this case I did not define a test dataset, I just used the training dataset with CV10 validation to briefly analyze the training metrics. fitControl <- trainControl( method = "repeatedcv", number = 10, repeats = 10)lmFit <- train(mydata[1:365, 2:6],mydata[1:365,7], method ='bridge',trControl = fitControl)predictedValues <- predict(lmFit,newdata = mydata[, 2:6]) Finally, we created a new column in the PowerBI dataset with the values ​​generated by the model’s prediction. mydata$PredictedValues <- predictedValues Full Code library(caret)library(datasets)library(monomvn)mydata <- datasetmydata <- data.frame(mydata)fitControl <- trainControl( method = "repeatedcv", number = 10, repeats = 10)lmFit <- train(mydata[1:365, 2:6],mydata[1:365,7], method ='bridge',trControl = fitControl)predictedValues <- predict(lmFit,newdata = mydata[, 2:6])mydata$PredictedValues <- predictedValues Below is the complete dataset with the real value, the prediction and the error (%). The average error in training was 7.82% with a maximum of 20.23% and a minimum of 0.03% Below is a graph with the real data in black and the prediction data in red, in addition to the error in blue bars for the entire test period. When plotting the beer consumption (in black/red) with the temperature (in blue) we see that the consumption follows well the temperature variations between the months, both the “micro” (daily) variations and the “macro” (trends) of temperature variation. We see that the increase in temperature results in greater consumption, for example at the end and beginning of the year, which is when we have summer and the lower temperature in winter results in lower consumption of beer in SP. Applying a correlation between the real values ​​and the values ​​predicted by the model, we would have as ideal the data concentrated in the black dashed line (graph below), in a scenario where the predicted data would be equal to the real data. By making this correlation graph we can see how dispersed the model’s prediction is and whether the concentration of the predictions is under or overestimated. When analyzing the correlation graph we see that the dispersion is not as high for an initial model, with an average variation of 7.8% as seen previously. When analyzing the concentration of the data, we see that the model varies between predictions greater or less than the real, but in most cases the model slightly overestimates the consumption data, predicting a higher consumption than the real. After training the model with the 2015 data, I tried to obtain data for an inference and obtained a 2018 dataset with temperature and rainfall data for the city of São Paulo. It is noted below that the values ​​presented by the inference in the 2018 data show the same pattern as the real data, reducing consumption in the middle of the year with a reduction in temperature and showing peaks on weekends. Then the values ​​plotted together with the temperature, in blue, prove a correlation between consumption and temperature and demonstrate its dynamics throughout the year also in the inference data. One way to explain the seasonal cycles is the increase in beer consumption on weekends, we can see below the graph of consumption by the average temperature, where the black bars represent the days of the weekend, Saturday and Sunday. This seasonality also happens in the real data, when we plot the real consumption of 2015, the high consumption pattern is repeated on weekends, which shows that the model, even though simple, was well adapted to the data dynamics. Power BI as a graphical tool provides great versatility and velocity to development an analytical visualization from Machine Learning model outputs, besides being able to present at the same time an exploratory view of the database itself. Incorporating the power of Machine Learning models into a BI tool is undoubtedly a major advance for developers working in analytical sectors and PowerBI brings this functionality in a simple and functional way. Finally, any questions or suggestions about the article or the topics of Machine Learning, PowerBI, R, Python, among others feel free to contact me on LinkedIn: https://www.linkedin.com/in/octavio-b-santiago/
[ { "code": null, "e": 501, "s": 171, "text": "Microsoft has recently been making a strong move to align Open Source technologies and insert Artificial Intelligence technologies into its products, and Power BI is included in this plan. Power BI is one of the main tools for building dashboards today and Microsoft is increasing its development power and flexibility every day." }, { "code": null, "e": 946, "s": 501, "text": "To make the development of dashboards feasible, Power BI has several functionalities for data treatment, and one of the most important is the integration tool with R and more recently the integration with Python. The option of working with R and Python development languages ​​opens up a huge range of possibilities within the BI tool, and one of these possibilities is to work with Machine Learning tools and build models directly in Power BI." }, { "code": null, "e": 1127, "s": 946, "text": "In this article I will be going step-by-step on how to train and make predictions with a machine learning model directly in PowerBI using the R language, from the following topics:" }, { "code": null, "e": 1209, "s": 1127, "text": "Installing the dependenciesAnalyzing the dataHands-on — the codeResultsConclusion" }, { "code": null, "e": 1237, "s": 1209, "text": "Installing the dependencies" }, { "code": null, "e": 1256, "s": 1237, "text": "Analyzing the data" }, { "code": null, "e": 1276, "s": 1256, "text": "Hands-on — the code" }, { "code": null, "e": 1284, "s": 1276, "text": "Results" }, { "code": null, "e": 1295, "s": 1284, "text": "Conclusion" }, { "code": null, "e": 1522, "s": 1295, "text": "The first step is to install R Studio on your machine, as the development will be in the R language. As much as PowerBI has native integration with the R language, it requires the user to install the R packages on the machine." }, { "code": null, "e": 1617, "s": 1522, "text": "The download can be done through this link: https://www.rstudio.com/products/rstudio/download/" }, { "code": null, "e": 1704, "s": 1617, "text": "Right after installation, you must open R studio and install the dependency libraries." }, { "code": null, "e": 1710, "s": 1704, "text": "caret" }, { "code": null, "e": 1719, "s": 1710, "text": "datasets" }, { "code": null, "e": 1727, "s": 1719, "text": "monomvn" }, { "code": null, "e": 1947, "s": 1727, "text": "To install the packages in R, the website R-bloggers has a great tutorial that teaches you how to install and load packages in R Studio. Link: https://www.r-bloggers.com/2013/01/how-to-install-packages-on-r-screenshots/" }, { "code": null, "e": 2171, "s": 1947, "text": "The dataset was obtained from the kaggle.com website and consists of beer consumption data at a university in São Paulo, together with the minimum, maximum and average temperatures for each day and the volumetric rainfall." }, { "code": null, "e": 2493, "s": 2171, "text": "To add another important feature I created a column called “Weekend” that indicates when the day is Saturday or Sunday, to take a little bit of the seasonality of consumption since the weekend presents a higher consumption, I could have considered Friday too, but for this first moment, I decided to be more conservative." }, { "code": null, "e": 2730, "s": 2493, "text": "For the tests, I put together a Bayesian linear regression model using the monomvn package (Bayesian Ridge Regression) to predict the beer consumption data in liters per day, along with validation through Cross Validation with 10 folds." }, { "code": null, "e": 2876, "s": 2730, "text": "I will not go into much of the model and its results in this article, as the goal is to focus more on integration with Power BI than on modeling." }, { "code": null, "e": 2925, "s": 2876, "text": "The first part of the code imports the libraries" }, { "code": null, "e": 2973, "s": 2925, "text": "library(caret)library(datasets)library(monomvn)" }, { "code": null, "e": 3040, "s": 2973, "text": "Right after we import the Power BI data as a dataset, inside the R" }, { "code": null, "e": 3086, "s": 3040, "text": "mydata <- datasetmydata <- data.frame(mydata)" }, { "code": null, "e": 3289, "s": 3086, "text": "With that we can create the model and perform the prediction. In this case I did not define a test dataset, I just used the training dataset with CV10 validation to briefly analyze the training metrics." }, { "code": null, "e": 3518, "s": 3289, "text": "fitControl <- trainControl( method = \"repeatedcv\", number = 10, repeats = 10)lmFit <- train(mydata[1:365, 2:6],mydata[1:365,7], method ='bridge',trControl = fitControl)predictedValues <- predict(lmFit,newdata = mydata[, 2:6])" }, { "code": null, "e": 3629, "s": 3518, "text": "Finally, we created a new column in the PowerBI dataset with the values ​​generated by the model’s prediction." }, { "code": null, "e": 3671, "s": 3629, "text": "mydata$PredictedValues <- predictedValues" }, { "code": null, "e": 3681, "s": 3671, "text": "Full Code" }, { "code": null, "e": 4043, "s": 3681, "text": "library(caret)library(datasets)library(monomvn)mydata <- datasetmydata <- data.frame(mydata)fitControl <- trainControl( method = \"repeatedcv\", number = 10, repeats = 10)lmFit <- train(mydata[1:365, 2:6],mydata[1:365,7], method ='bridge',trControl = fitControl)predictedValues <- predict(lmFit,newdata = mydata[, 2:6])mydata$PredictedValues <- predictedValues" }, { "code": null, "e": 4216, "s": 4043, "text": "Below is the complete dataset with the real value, the prediction and the error (%). The average error in training was 7.82% with a maximum of 20.23% and a minimum of 0.03%" }, { "code": null, "e": 4359, "s": 4216, "text": "Below is a graph with the real data in black and the prediction data in red, in addition to the error in blue bars for the entire test period." }, { "code": null, "e": 4846, "s": 4359, "text": "When plotting the beer consumption (in black/red) with the temperature (in blue) we see that the consumption follows well the temperature variations between the months, both the “micro” (daily) variations and the “macro” (trends) of temperature variation. We see that the increase in temperature results in greater consumption, for example at the end and beginning of the year, which is when we have summer and the lower temperature in winter results in lower consumption of beer in SP." }, { "code": null, "e": 5253, "s": 4846, "text": "Applying a correlation between the real values ​​and the values ​​predicted by the model, we would have as ideal the data concentrated in the black dashed line (graph below), in a scenario where the predicted data would be equal to the real data. By making this correlation graph we can see how dispersed the model’s prediction is and whether the concentration of the predictions is under or overestimated." }, { "code": null, "e": 5654, "s": 5253, "text": "When analyzing the correlation graph we see that the dispersion is not as high for an initial model, with an average variation of 7.8% as seen previously. When analyzing the concentration of the data, we see that the model varies between predictions greater or less than the real, but in most cases the model slightly overestimates the consumption data, predicting a higher consumption than the real." }, { "code": null, "e": 5830, "s": 5654, "text": "After training the model with the 2015 data, I tried to obtain data for an inference and obtained a 2018 dataset with temperature and rainfall data for the city of São Paulo." }, { "code": null, "e": 6060, "s": 5830, "text": "It is noted below that the values ​​presented by the inference in the 2018 data show the same pattern as the real data, reducing consumption in the middle of the year with a reduction in temperature and showing peaks on weekends." }, { "code": null, "e": 6259, "s": 6060, "text": "Then the values ​​plotted together with the temperature, in blue, prove a correlation between consumption and temperature and demonstrate its dynamics throughout the year also in the inference data." }, { "code": null, "e": 6494, "s": 6259, "text": "One way to explain the seasonal cycles is the increase in beer consumption on weekends, we can see below the graph of consumption by the average temperature, where the black bars represent the days of the weekend, Saturday and Sunday." }, { "code": null, "e": 6726, "s": 6494, "text": "This seasonality also happens in the real data, when we plot the real consumption of 2015, the high consumption pattern is repeated on weekends, which shows that the model, even though simple, was well adapted to the data dynamics." }, { "code": null, "e": 7178, "s": 6726, "text": "Power BI as a graphical tool provides great versatility and velocity to development an analytical visualization from Machine Learning model outputs, besides being able to present at the same time an exploratory view of the database itself. Incorporating the power of Machine Learning models into a BI tool is undoubtedly a major advance for developers working in analytical sectors and PowerBI brings this functionality in a simple and functional way." } ]
A gentle introduction to Deep Reinforcement Learning | by Jordi TORRES.AI | Towards Data Science
This is the first post of the series “Deep Reinforcement Learning Explained”; an introductory series that gradually and with a practical approach introduces the reader to the basic concepts and methods used in modern Deep Reinforcement Learning. Spanish version of this publication: medium.com Deep Reinforcement Learning (DRL), a very fast-moving field, is the combination of Reinforcement Learning and Deep Learning. It is also the most trending type of Machine Learning because it can solve a wide range of complex decision-making tasks that were previously out of reach for a machine to solve real-world problems with human-like intelligence. Today I’m starting a series about Deep Reinforcement Learning that will bring the topic closer to the reader. The purpose is to review the field from specialized terms and jargons to fundamental concepts and classical algorithms in the area, that newbies would not get lost while starting in this amazing area. My first serious contact with Deep Reinforcement Learning was in Cadiz (Spain), during the Machine Learning Summer School in 2016. I attended the three days seminar of John Schulman (at that time from UC Berkeley and cofounder of OpenAI) about Deep Reinforcement Learning. It was awesome, but I also have to confess that it was tremendously difficult for me to follow John’s explanations. It’s been a long time since then, and thanks to working with Xavier Giró and Ph.D. students like Victor Campos and MPh.D.am Bellver, I’ve been able to move forward and enjoy the subject. But even though several years have passed since then, I sincerely believe that the taxonomy of different approaches to Reinforcement Learning that he presented is still a good scheme to organize knowledge for beginners. Dynamic Programming is actually what most reinforcement learning courses in textbooks start. I will do that, but before, as John did in his seminar, I will introduce the Cross-Entropy method, a sort of evolutionary algorithm, although most books do not deal with it. It will go very well with this first method to introduce deep learning in reinforcement learning, Deep Reinforcement Learning, because it is a straightforward method to implement, and it works surprisingly well. With this method, we will be able to do a convenient review of how Deep Learning and Reinforcement Learning collaborate before entering the more classical approaches of treating an RL problem without considering DL such as Dynamic Programming, Monte Carlo, Temporal Difference Learning following the order of the vast majority of academic books on the subject. We will then dedicate the last part of this series to the most fundamental algorithms (not the state of the art because it is pervasive) of DL + RL as Policy Gradient Methods. Specifically, in this first publication, we will briefly present what Deep Reinforcement Learning is and the basic terms used in this research and innovation area. I think that Deep Reinforcement Learning is one of the most exciting fields in Artificial Intelligence. It’s marrying the power and the ability of deep neural networks to represent and comprehend the world with the ability to act on that understanding. Let’s see if I’m able to share that excitement. Here we go! Exciting news in Artificial Intelligence (AI) has just happened in recent years. For instance, AlphaGo defeated the best professional human player in the game of Go. Or last year, for example, our friend Oriol Vinyals and his team in DeepMind showed the AlphaStar Agent beat professional players at the game of StarCraft II. Or a few months later, OpenAI’s Dota-2-playing bot became the first AI system to beat the world champions in an e-sports game. All these systems have in common that they use Deep Reinforcement Learning (DRL). But what are AI and DRL? We have to take a step back to look at the types of learning. Sometimes the terminology itself can confuse us with the fundamentals. Artificial Intelligence, the main field of computer science in which Reinforcement Learning (RL) falls into, is a discipline concerned with creating computer programs that display humanlike “intelligence”. What do we mean when we talk about Artificial Intelligence? Artificial intelligence (AI) is a vast area. Even an authoritative AI textbook Artificial Intelligence, a modern approach written by Stuart Rusell and Peter Norvig, does not give a precise definition and discuss definitions of AI from different perspectives: Artificial Intelligence: A Modern Approach (AIMA) ·3rd edition, Stuart J Russell and Peter Norvig, Prentice Hall, 2009. ISBN 0–13–604259–7 Without a doubt, this book is the best starting point to have a global vision of the subject. But trying to make a more general approach (purpose of this series), we could accept a simple definition in which by Artificial Intelligence we refer to that intelligence shown by machines, in contrast to the natural intelligence of humans. In this sense, a possible concise and general definition of Artificial Intelligence could be the effort to automate intellectual tasks usually performed by humans. As such, the area of artificial intelligence is a vast scientific field that covers many areas of knowledge related to machine learning; even many more approaches are not always cataloged as Machine Learning is included by my university colleagues who are experts in the subject. Besides, over time, as computers have been increasingly able to “do things”, tasks or technologies considered “smart” have been changing. Furthermore, since the 1950s, Artificial Intelligence has experienced several waves of optimism, followed by disappointment and loss of funding and interest (periods known as AI winter), followed by new approaches, success, and financing. Moreover, during most of its history, Artificial Intelligence research has been dynamically divided into subfields based on technical considerations or concrete mathematical tools and with research communities that sometimes did not communicate sufficiently with each other. Machine Learning (ML) is in itself a large field of research and development. In particular, Machine Learning could be defined as the subfield of Artificial Intelligence that gives computers the ability to learn without being explicitly programmed, that is, without requiring the programmer to indicate the rules that must be followed to achieve their task; the computers do them automatically. Generalizing, we can say that Machine Learning consists of developing a prediction “algorithm” for a particular use case for each problem. These algorithms learn from the data to find patterns or trends to understand what the data tell us, and in this way, build a model to predict and classify the elements. Given the maturity of the research area in Machine Learning, there are many well-established approaches to Machine Learning. Each of them uses a different algorithmic structure to optimize the predictions based on the received data. Machine Learning is a broad field with a complex taxonomy of algorithms that are grouped, in general, into three main categories: Supervised Learning is the task of learning from tagged data, and its goal is to generalize. We mean that learning is supervised when the data we use for training includes the desired solution, called “label”. Some of the most popular machine learning algorithms in this category are linear regression, logistic regression, support vector machines, decision trees, random forest, or neural networks. Unsupervised Learning is the task of learning from unlabeled data, and its goal is to compress. When the training data do not include the labels, we refer to Unsupervised Learning, and it will be the algorithm that will try to classify the information by itself. Some of the best-known algorithms in this category are clustering (K-means) or principal component analysis (PCA). Reinforcement Learning is the task of learning through trial and error and its goal is to act. This learning category allows it to be combined with other categories, and it is now a very active research area, as we will see in this series. Orthogonal to this categorization, we can consider a powerful approach to ML, called Deep Learning (DL), a topic of which we have discussed extensively in previous posts. Remember that Deep Learning algorithms are based on artificial neural networks, whose algorithmic structures allow models composed of multiple processing layers to learn data representations with various abstraction levels. DL is not a separate ML branch, so it’s not a different task than those described above. DL is a collection of techniques and methods for using neural networks to solve ML tasks, either Supervised Learning, Unsupervised Learning, or Reinforcement Learning. We can represent it graphically in Figure 1. Deep Learning is one of the best tools that we have today to handle unstructured environments; they can learn from large amounts of data or discover patterns. But this is not decision-making; it is a recognition problem. Reinforcement Learning provides this feature. Reinforcement Learning can solve the problems using a variety of ML methods and techniques, from decision trees to SVMs, to neural networks. However, in this series, we only use neural networks; this is what the “deep” part of DRL refers to, after all. However, neural networks are not necessarily the best solution to every problem. For instance, neural networks are very data-hungry and challenging to interpret. Still, without doubt, neural networks are at this moment one of the most powerful techniques available, and their performance is often the best. In this section, we provide a brief first approach to RL, due it is essential for a good understanding of deep reinforcement learning, a particular type of RL, with deep neural networks for state representation and/or function approximation for value function, policy, and so on. Learning by interacting with our Environment is probably the first approach that comes to our mind when we think about the nature of learning. It is the way we intuit that an infant learns. And we know that such interactions are undoubtedly an essential source of knowledge about our environment and ourselves throughout people’s lives, not just infants. For example, when we are learning to drive a car, we are entirely aware of how the environment responds to what we do, and we also seek to influence what happens in our environment through our actions. Learning from the interaction is a fundamental concept that underlies almost all learning theories and is the foundation of Reinforcement Learning. The approach of Reinforcement Learning is much more focused on goal-directed learning from interaction than are other approaches to Machine Learning. The learning entity is not told what actions to take, but instead must discover for itself which actions produce the greatest reward, its goal, by testing them by “trial and error.” Furthermore, these actions can affect not only the immediate reward but also the future ones, “delayed rewards”, since the current actions will determine future situations (how it happens in real life). These two characteristics, “trial and error” search and “delayed reward”, are two distinguishing characteristics of reinforcement learning that we will cover throughout this series of posts. Reinforcement Learning (RL) is a field that is influenced by a variety of other well-established fields that tackle decision-making problems under uncertainty. For instance, Control Theory studies ways to control complex known dynamical systems; however, the dynamics of the systems we try to control are usually known in advance, unlike the case of DRL, which is not known in advance. Another field can be Operations Research that also studies decision-making under uncertainty but often contemplates much larger action spaces than those commonly seen in RL. As a result, there is a synergy between these fields, which is undoubtedly positive for science advancement. But it also brings some inconsistencies in terminologies, notations, and so on. That is why in this section, we will provide a detailed introduction to terminologies and notations that we will use throughout the series. Reinforcement Learning is essentially a mathematical formalization of a decision-making problem that we will introduce later in this series. In Reinforcement Learning there are two core components: An Agent, that represents the “solution” , which is a computer program with a single role of making decisions (actions) to solve complex decision-making problems under uncertainty. An Environment, that is the representation of a “problem”, which is everything that comes after the decision of the Agent. The environment responds with the consequences of those actions, which are observations or states, and rewards, also sometimes called costs. For example, in the tic-tac-toe game, we can consider that the Agent is one of the players, and the Environment includes the board game and the other player. These two core components continuously interact so that the Agent attempts to influence the Environment through actions, and the Environment reacts to the Agent’s actions. How the environment reacts to specific actions is defined by a model that may or may not be known by the Agent, and this differentiates two circumstances: When the Agent knows the model, we refer to this situation as a model-based RL. In this case, when we fully know the Environment, we can find the optimal solution by Dynamic Programming. This is not the purpose of this post. When the Agent does not know the model, it needs to make decisions with incomplete information; do model-free RL, or try to learn the model explicitly as part of the algorithm. The Environment is represented by a set of variables related to the problem (very dependent on the type of problem we want to solve). This set of variables and all the possible values they can take are referred to as the state space. A state is an instantiation of the state space, a set of values the variables take. Due that we are considering that the Agent doesn’t have access to the actual full state of the Environment, it is usually called observation, the part of the state that the Agent can observe. However, we will often see in the literature observations and states being used interchangeably, so we will do this in this series of posts. At each state, the Environment makes available a set of actions, from which the Agent will choose an action. The Agent influences the Environment through these actions, and the Environment may change states as a response to the Agent’s action. The function responsible for this mapping is called in the literature transition function or transition probabilities between states. The Environment commonly has a well-defined task and may provide to the Agent a reward signal as a direct answer to the Agent’s actions. This reward is feedback on how well the last action contributes to achieving the task to be performed by the Environment. The function responsible for this mapping is called the reward function. As we will see later, the Agent’s goal is to maximize the overall reward it receives, and so rewards are the motivation the Agent needs to act in the desired behavior. Let’s summarize in the following Figure the concepts introduced earlier in the Reinforcement Learning cycle: Generally speaking, Reinforcement Learning is basically about turning this Figure into a mathematical formalism. The cycle begins with the Agent observing the Environment (step 1) and receiving a state and a reward. The Agent uses this state and reward for deciding the next action to take (step 2). The Agent then sends an action to the Environment in an attempt to control it in a favorable way (step 3). Finally, the environment transitions, and its internal state changes as a consequence due to the previous state and the Agent’s action (step 4). Then, the cycle repeats. The task the Agent is trying to solve may or may not have a natural ending. Tasks that have a natural ending, such as a game, are called episodic tasks. Conversely, tasks that do not, are called continuous tasks, for example learning forward motion. The sequence of time steps from the beginning to the end of an episodic task is called an episode. As we will see, Agents may take several time steps and episodes to learn how to solve a task. The sum of rewards collected in a single episode is called a return. Agents are often designed to maximize the return. One of the limitations is that these rewards are not disclosed to the Agent until the end of an episode, which we introduced earlier as “delayed reward”. For example, in the game of tic-tac-toe the rewards for each movement (action) are not known until the end of the game. It would be a positive reward if the agent won the game (because the agent had achieved the overall desired outcome) or a negative reward (penalties) if the agent had lost the game. Another important characteristic, and challenge in Reinforcement Learning, is the trade-off between “exploration” and “exploitation”. Trying to obtain many rewards, an Agent must prefer actions that it has tried in the past and knows that will be effective actions in producing reward. But to discover such actions, paradoxically, it has to try actions that it has not selected never before. In summary, an Agent has to exploit what it has already experienced to obtain as much reward as possible, but at the same time, it also has to explore to make select better action in the future. The exploration-exploitation dilemma is a crucial topic and still an unsolved research topic. We will talk about this trade-off later in this series. Let’s strengthen our understanding of Reinforcement Learning by looking at a simple example, a Frozen Lake (very slippery) where our agent can skate: The Frozen-Lake Environment that we will use as an example is an ice skating rink, divided into 16 cells (4x4), and as shown in the figure below, some of the cells have broken the ice. The skater named Agent begins to skate in the top-left position, and its goal is to reach the bottom-right place avoiding falling into the four holes in the track. The described example is coded as the Frozen-Lake Environment from Gym. With this example of Environment, we will review and clarify the RL terminology introduced until now. It will also be useful for future posts in this series to have this example. OpenAI is an artificial intelligence (AI) research organization that provides a famous toolkit called Gym for training a reinforcement learning agent to develop and compare RL algorithms. Gym offers a variety of environments for training an RL agent ranging from classic control tasks to Atari game environments. We can train our RL agent to learn in these simulated environments using various RL algorithms. Throughout the series, we will use the Gym toolkit to build and evaluate reinforcement learning algorithms for several classic control tasks such as Cart-Pole balancing or mountain car climbing. Gym also provides 59 Atari game environments, including Pong, Space Invaders, Air Raid, Asteroids, Centipede, Ms. Pac-Man, etc. Training our reinforcement learning agent to play Atari games is an interesting as well as challenging task. Later in this series, we will train our DQN reinforcement learning agent to play Atari Pong game environment. Let’s introduce as an example one of the most straightforward environments called Frozen-Lake environment. Frozen-Lake Environment is from the so-called grid-world category when the Agent lives in a grid of size 4x4 (has 16 cells), which means a state space composed of 16 states (0–15) in the i, j coordinates of the grid-world. In Frozen-Lake, the Agent always starts at a top-left position, and its goal is to reach the bottom-right position of the grid. There are four holes in the fixed cells of the grid, and if the Agent gets into those holes, the episode ends, and the reward obtained is zero. If the Agent reaches the destination cell, it receives a reward of +1, and the episode ends. The following Figure shows a visual representation of the Frozen-Lake Environment: To reach the goal, the Agent has an action space composed of four directions movements: up, down, left, and right. We also know that there is a fence around the lake, so if the Agent tries to move out of the grid world, it will just bounce back to the cell from which it tried to move. Because the lake is frozen, the world is slippery, so the Agent’s actions do not always turn out as expected — there is a 33% chance that it will slip to the right or the left. If we want the Agent to move left, for example, there is a 33% probability that it will, indeed, move left, a 33% chance that it will end up in the cell above, and a 33% chance that it will end up in the cell below. This behavior of the Environment is reflected in the transition function or transition probabilities presented before. However, at this point, we do not need to go into more detail on this function and leave it for later. As a summary, we could represent all this information visually in the following Figure: Let’s look at how this Environment is represented in Gym. I suggest to use the Colab offered by Google to execute the code described in this post (Gym package is already installed). If you prefer to use your Python programming environment, you can install Gym using the steps provided here. The first step is to import Gym: import gym Then, specify the game from Gym you want to use. We will use the Frozen-Lake game: env = gym.make('FrozenLake-v0') The environment of the game can be reset to the initial state using: env.reset() And, to see a view of the game state, we can use: env.render() The surface rendered by render()is presented using a grid like the following: Where the highlighted character indicates the position of the Agent in the current time step and “S” indicates the starting cell (safe position) “F” indicates a frozen surface (safe position) “H” indicates a hole “G”: indicates the goal The official documentation can be found here to see the detailed usage and explanation of Gym toolkit. For the moment, we will create the most straightforward Agent that we can make that only does random actions. For this purpose, we will use the action_space.sample() that samples a random action from the action space. Assume that we allow a maximum of 10 iterations; the following code can be our “dumb” Agent: import gymenv = gym.make("FrozenLake-v0")env.reset()for t in range(10): print("\nTimestep {}".format(t)) env.render() a = env.action_space.sample() ob, r, done, _ = env.step(a) if done: print("\nEpisode terminated early") break If we run this code, it will output something like the following lines, where we can observe the Timestep, the action, and the Environment state: In general, it is challenging, if not almost impossible, to find an episode of our “dumb” Agent in which, with randomly selected actions, it can overcome the obstacles and reach the goal cell. So how could we build an Agent to pursue it?. This is what we will present in the next installment of this series, where we will further formalize the problem and build a new Agent version that can learn to reach the goal cell. To finish this post, let’s review the basis of Reinforcement Learning for a moment, comparing it with other learning methods. In supervised learning, the system learns from training data that consists of a labeled pair of inputs and outputs. So, we train the model (Agent) using the training data in such a way that the model can generalize its learning to new unseen data (the labeled pairs of inputs and outputs guide the model in learning the given task). Let’s understand the difference between supervised and reinforcement learning with an example. Imagine we want to train a model to play chess using supervised learning. In this case, we will train the model to learn using a training dataset that includes all the moves a player can make in each state, along with labels indicating whether it is a good move or not. Whereas in the case of RL, our agent will not be given any sort of training data; instead, we just provide a reward to the agent for each action it performs. Then, the agent will learn by interacting with the environment, and it will choose its actions based on the reward it gets. Similar to supervised learning, in unsupervised learning, we train the model based on the training data. But in the case of unsupervised learning, the training data does not contain any labels. And this leads to a common misconception that RL is a kind of unsupervised learning due we don’t have labels as input data. But it is not. In unsupervised learning, the model learns the hidden structure in the input data, whereas, in RL, the model learns by maximizing the reward. A classic example is a movie recommendation system that wants to recommend a new movie to the user. With unsupervised learning, the model (agent) will find movies similar to the film the user (or users with a profile similar to the user) has viewed before and recommend new movies to the user. Instead, with Reinforcement Learning, the agent continually receives feedback from the user. This feedback represents rewards (a reward could be time spent watching a movie, time spent watching trailers, how many movies in a row have he watched, and so on). Based on the rewards, an RL agent will understand the user’s movie preference and then suggest new movies accordingly. It is essential to notice that an RL agent can know if the user’s movie preference changes and suggest new movies according to the user’s changed movie preference dynamically. We can think that we don’t have data in Reinforcement Learning as we have in Supervised or Unsupervised Learning. However, the data is actually the Environment because if you interact with this Environment, then data (trajectories) can be created, which are sequences of observations and actions. Then we can do some learning on top, and that’s basically the core of Reinforcement Learning. Sometimes, we can use extra data from people or trajectories that exist, for instance, in imitation learning. We might actually just observe a bunch of people playing the game, and we don’t need to know precisely how the Environment works. Sometimes we have explicitly given a data set, as a sort of a supervised data set, but in the pure Reinforcement Learning setting, the only data is the Environment. Reinforcement Learning has evolved rapidly over the past few years with a wide range of applications. One of the primary reasons for this evolution is the combination of Reinforcement Learning and Deep Learning. This is why we focus this series on presenting the basic state-of-the-art Deep Reinforcement Learning algorithms (DRL). The media has tended to focus on applications where DRL defeat humans at games, with examples as I mentioned at the beginning of this post: AlphaGo defeated the best professional human player in the game of Go; AlphaStar beat professional players at the game of StarCraft II; OpenAI’s Dota-2-playing bot beat the world champions in an e-sports game. Fortunately, there are many real-life applications of DRL. One of the well known is in the area of driverless cars. In manufacturing, intelligent robots are trained using DRL to place objects in the right position, reducing labor costs, and increasing productivity. Another popular application of RL is dynamic pricing that allows changing the price of products based on demand and supply. Also, in a recommendation system, RL is used to build a recommendation system where the user’s behavior continually changes. In today’s business activities, DRL is used extensively in supply chain management, demand forecasting, inventory management, handling warehouse operations, etc. DRL is also widely used in financial portfolio management, predicting, and trading in commercial transaction markets. DRL has been commonly used in several Natural Language Processing (NLP) tasks, such as abstractive text summarization, chatbots, etc. Many recent research papers suggest applications of DRL in healthcare, education systems, smart cities, among many others. In summary, no business sector is left untouched by DRL. DRL agents can sometimes control hazardous real-life Environments, like robots or cars, which increases the risk of making incorrect choices. There is an important field called safe RL that attempts to deal with this risk, for instance, learning a policy that maximizes rewards while operating within predefined safety constraints. Also, DRL agents are also at risk from an attack, like any other software system. But DRL adds a few new attack vectors over and above traditional machine learning systems because, in general, we are dealing with systems much more complex to understand and model. Considering the safety and security of DRL systems are outside the introductory scope of this post. Still, I would like the reader to be aware of it and if in the future you put a DRL system into operation, keep in mind that you should treat this point in more depth. Artificial Intelligence is definitely penetrating society, like electricity, what will we expect? The future we will “invent” is a choice we make jointly, not something that happens. We are in a position of power. With DRL, we have the power and authority to automate decisions and entire strategies. This is good! But as in most things in life, where there is light, can be the shadow, and DRL technology is hazardous in the wrong hands. I ask you that as engineers consider what we are building: Could our DRL system accidentally add bias? How does this affect individuals?. Or how does our solution affect the climate due to its energy consumption? Can be our DRL solution unintended used? Or use?. Or, in accordance with our ethics, can it have a type of use that we could consider nefarious? We must mull over the imminent adoption of Artificial Intelligence and its impact. Were we to go on to build Artificial Intelligence without regard to our responsibility of preventing its misuse, we can never expect to see Artificial Intelligence help humanity prosper. All of us, who are working or want to work on these topics, cannot shy away from our responsibility, because otherwise, we will regret it in the future. We started the post by understanding the basic idea of RL. We learned that RL is a trial and error learning process and the learning in RL happens based on a reward. We presented the difference between RL and the other ML paradigms. Finally, we looked into some real-life applications of RL and thought about the safety, security, and ethics of DRL. In the next post, we will learn about the Markov Decision Process (MDP) and how the RL environment can be modeled as an MDP. Next, we will review several important fundamental concepts involved in RL. See you in the next post! Post updated on 8/12/2020 by UPC Barcelona Tech and Barcelona Supercomputing Center A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence. I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made. Disclaimers — These posts were written during this period of lockdown in Barcelona as a personal distraction and dissemination of scientific knowledge, in case it could be of help to someone, but without the purpose of being an academic reference document in the DRL area. If the reader needs a more rigorous document, the last post in the series offers an extensive list of academic resources and books that the reader can consult. The author is aware that this series of posts may contain some errors and suffers from a revision of the English text to improve it if the purpose were an academic document. But although the author would like to improve the content in quantity and quality, his professional commitments do not leave him free time to do so. However, the author agrees to refine all those errors that readers can report as soon as he can.
[ { "code": null, "e": 418, "s": 172, "text": "This is the first post of the series “Deep Reinforcement Learning Explained”; an introductory series that gradually and with a practical approach introduces the reader to the basic concepts and methods used in modern Deep Reinforcement Learning." }, { "code": null, "e": 455, "s": 418, "text": "Spanish version of this publication:" }, { "code": null, "e": 466, "s": 455, "text": "medium.com" }, { "code": null, "e": 819, "s": 466, "text": "Deep Reinforcement Learning (DRL), a very fast-moving field, is the combination of Reinforcement Learning and Deep Learning. It is also the most trending type of Machine Learning because it can solve a wide range of complex decision-making tasks that were previously out of reach for a machine to solve real-world problems with human-like intelligence." }, { "code": null, "e": 1130, "s": 819, "text": "Today I’m starting a series about Deep Reinforcement Learning that will bring the topic closer to the reader. The purpose is to review the field from specialized terms and jargons to fundamental concepts and classical algorithms in the area, that newbies would not get lost while starting in this amazing area." }, { "code": null, "e": 1403, "s": 1130, "text": "My first serious contact with Deep Reinforcement Learning was in Cadiz (Spain), during the Machine Learning Summer School in 2016. I attended the three days seminar of John Schulman (at that time from UC Berkeley and cofounder of OpenAI) about Deep Reinforcement Learning." }, { "code": null, "e": 1707, "s": 1403, "text": "It was awesome, but I also have to confess that it was tremendously difficult for me to follow John’s explanations. It’s been a long time since then, and thanks to working with Xavier Giró and Ph.D. students like Victor Campos and MPh.D.am Bellver, I’ve been able to move forward and enjoy the subject." }, { "code": null, "e": 1927, "s": 1707, "text": "But even though several years have passed since then, I sincerely believe that the taxonomy of different approaches to Reinforcement Learning that he presented is still a good scheme to organize knowledge for beginners." }, { "code": null, "e": 2406, "s": 1927, "text": "Dynamic Programming is actually what most reinforcement learning courses in textbooks start. I will do that, but before, as John did in his seminar, I will introduce the Cross-Entropy method, a sort of evolutionary algorithm, although most books do not deal with it. It will go very well with this first method to introduce deep learning in reinforcement learning, Deep Reinforcement Learning, because it is a straightforward method to implement, and it works surprisingly well." }, { "code": null, "e": 2943, "s": 2406, "text": "With this method, we will be able to do a convenient review of how Deep Learning and Reinforcement Learning collaborate before entering the more classical approaches of treating an RL problem without considering DL such as Dynamic Programming, Monte Carlo, Temporal Difference Learning following the order of the vast majority of academic books on the subject. We will then dedicate the last part of this series to the most fundamental algorithms (not the state of the art because it is pervasive) of DL + RL as Policy Gradient Methods." }, { "code": null, "e": 3107, "s": 2943, "text": "Specifically, in this first publication, we will briefly present what Deep Reinforcement Learning is and the basic terms used in this research and innovation area." }, { "code": null, "e": 3420, "s": 3107, "text": "I think that Deep Reinforcement Learning is one of the most exciting fields in Artificial Intelligence. It’s marrying the power and the ability of deep neural networks to represent and comprehend the world with the ability to act on that understanding. Let’s see if I’m able to share that excitement. Here we go!" }, { "code": null, "e": 3979, "s": 3420, "text": "Exciting news in Artificial Intelligence (AI) has just happened in recent years. For instance, AlphaGo defeated the best professional human player in the game of Go. Or last year, for example, our friend Oriol Vinyals and his team in DeepMind showed the AlphaStar Agent beat professional players at the game of StarCraft II. Or a few months later, OpenAI’s Dota-2-playing bot became the first AI system to beat the world champions in an e-sports game. All these systems have in common that they use Deep Reinforcement Learning (DRL). But what are AI and DRL?" }, { "code": null, "e": 4318, "s": 3979, "text": "We have to take a step back to look at the types of learning. Sometimes the terminology itself can confuse us with the fundamentals. Artificial Intelligence, the main field of computer science in which Reinforcement Learning (RL) falls into, is a discipline concerned with creating computer programs that display humanlike “intelligence”." }, { "code": null, "e": 4637, "s": 4318, "text": "What do we mean when we talk about Artificial Intelligence? Artificial intelligence (AI) is a vast area. Even an authoritative AI textbook Artificial Intelligence, a modern approach written by Stuart Rusell and Peter Norvig, does not give a precise definition and discuss definitions of AI from different perspectives:" }, { "code": null, "e": 4776, "s": 4637, "text": "Artificial Intelligence: A Modern Approach (AIMA) ·3rd edition, Stuart J Russell and Peter Norvig, Prentice Hall, 2009. ISBN 0–13–604259–7" }, { "code": null, "e": 5275, "s": 4776, "text": "Without a doubt, this book is the best starting point to have a global vision of the subject. But trying to make a more general approach (purpose of this series), we could accept a simple definition in which by Artificial Intelligence we refer to that intelligence shown by machines, in contrast to the natural intelligence of humans. In this sense, a possible concise and general definition of Artificial Intelligence could be the effort to automate intellectual tasks usually performed by humans." }, { "code": null, "e": 5693, "s": 5275, "text": "As such, the area of artificial intelligence is a vast scientific field that covers many areas of knowledge related to machine learning; even many more approaches are not always cataloged as Machine Learning is included by my university colleagues who are experts in the subject. Besides, over time, as computers have been increasingly able to “do things”, tasks or technologies considered “smart” have been changing." }, { "code": null, "e": 6207, "s": 5693, "text": "Furthermore, since the 1950s, Artificial Intelligence has experienced several waves of optimism, followed by disappointment and loss of funding and interest (periods known as AI winter), followed by new approaches, success, and financing. Moreover, during most of its history, Artificial Intelligence research has been dynamically divided into subfields based on technical considerations or concrete mathematical tools and with research communities that sometimes did not communicate sufficiently with each other." }, { "code": null, "e": 6602, "s": 6207, "text": "Machine Learning (ML) is in itself a large field of research and development. In particular, Machine Learning could be defined as the subfield of Artificial Intelligence that gives computers the ability to learn without being explicitly programmed, that is, without requiring the programmer to indicate the rules that must be followed to achieve their task; the computers do them automatically." }, { "code": null, "e": 6911, "s": 6602, "text": "Generalizing, we can say that Machine Learning consists of developing a prediction “algorithm” for a particular use case for each problem. These algorithms learn from the data to find patterns or trends to understand what the data tell us, and in this way, build a model to predict and classify the elements." }, { "code": null, "e": 7274, "s": 6911, "text": "Given the maturity of the research area in Machine Learning, there are many well-established approaches to Machine Learning. Each of them uses a different algorithmic structure to optimize the predictions based on the received data. Machine Learning is a broad field with a complex taxonomy of algorithms that are grouped, in general, into three main categories:" }, { "code": null, "e": 7674, "s": 7274, "text": "Supervised Learning is the task of learning from tagged data, and its goal is to generalize. We mean that learning is supervised when the data we use for training includes the desired solution, called “label”. Some of the most popular machine learning algorithms in this category are linear regression, logistic regression, support vector machines, decision trees, random forest, or neural networks." }, { "code": null, "e": 8052, "s": 7674, "text": "Unsupervised Learning is the task of learning from unlabeled data, and its goal is to compress. When the training data do not include the labels, we refer to Unsupervised Learning, and it will be the algorithm that will try to classify the information by itself. Some of the best-known algorithms in this category are clustering (K-means) or principal component analysis (PCA)." }, { "code": null, "e": 8292, "s": 8052, "text": "Reinforcement Learning is the task of learning through trial and error and its goal is to act. This learning category allows it to be combined with other categories, and it is now a very active research area, as we will see in this series." }, { "code": null, "e": 8687, "s": 8292, "text": "Orthogonal to this categorization, we can consider a powerful approach to ML, called Deep Learning (DL), a topic of which we have discussed extensively in previous posts. Remember that Deep Learning algorithms are based on artificial neural networks, whose algorithmic structures allow models composed of multiple processing layers to learn data representations with various abstraction levels." }, { "code": null, "e": 8989, "s": 8687, "text": "DL is not a separate ML branch, so it’s not a different task than those described above. DL is a collection of techniques and methods for using neural networks to solve ML tasks, either Supervised Learning, Unsupervised Learning, or Reinforcement Learning. We can represent it graphically in Figure 1." }, { "code": null, "e": 9256, "s": 8989, "text": "Deep Learning is one of the best tools that we have today to handle unstructured environments; they can learn from large amounts of data or discover patterns. But this is not decision-making; it is a recognition problem. Reinforcement Learning provides this feature." }, { "code": null, "e": 9816, "s": 9256, "text": "Reinforcement Learning can solve the problems using a variety of ML methods and techniques, from decision trees to SVMs, to neural networks. However, in this series, we only use neural networks; this is what the “deep” part of DRL refers to, after all. However, neural networks are not necessarily the best solution to every problem. For instance, neural networks are very data-hungry and challenging to interpret. Still, without doubt, neural networks are at this moment one of the most powerful techniques available, and their performance is often the best." }, { "code": null, "e": 10096, "s": 9816, "text": "In this section, we provide a brief first approach to RL, due it is essential for a good understanding of deep reinforcement learning, a particular type of RL, with deep neural networks for state representation and/or function approximation for value function, policy, and so on." }, { "code": null, "e": 10801, "s": 10096, "text": "Learning by interacting with our Environment is probably the first approach that comes to our mind when we think about the nature of learning. It is the way we intuit that an infant learns. And we know that such interactions are undoubtedly an essential source of knowledge about our environment and ourselves throughout people’s lives, not just infants. For example, when we are learning to drive a car, we are entirely aware of how the environment responds to what we do, and we also seek to influence what happens in our environment through our actions. Learning from the interaction is a fundamental concept that underlies almost all learning theories and is the foundation of Reinforcement Learning." }, { "code": null, "e": 11527, "s": 10801, "text": "The approach of Reinforcement Learning is much more focused on goal-directed learning from interaction than are other approaches to Machine Learning. The learning entity is not told what actions to take, but instead must discover for itself which actions produce the greatest reward, its goal, by testing them by “trial and error.” Furthermore, these actions can affect not only the immediate reward but also the future ones, “delayed rewards”, since the current actions will determine future situations (how it happens in real life). These two characteristics, “trial and error” search and “delayed reward”, are two distinguishing characteristics of reinforcement learning that we will cover throughout this series of posts." }, { "code": null, "e": 12087, "s": 11527, "text": "Reinforcement Learning (RL) is a field that is influenced by a variety of other well-established fields that tackle decision-making problems under uncertainty. For instance, Control Theory studies ways to control complex known dynamical systems; however, the dynamics of the systems we try to control are usually known in advance, unlike the case of DRL, which is not known in advance. Another field can be Operations Research that also studies decision-making under uncertainty but often contemplates much larger action spaces than those commonly seen in RL." }, { "code": null, "e": 12416, "s": 12087, "text": "As a result, there is a synergy between these fields, which is undoubtedly positive for science advancement. But it also brings some inconsistencies in terminologies, notations, and so on. That is why in this section, we will provide a detailed introduction to terminologies and notations that we will use throughout the series." }, { "code": null, "e": 12557, "s": 12416, "text": "Reinforcement Learning is essentially a mathematical formalization of a decision-making problem that we will introduce later in this series." }, { "code": null, "e": 12614, "s": 12557, "text": "In Reinforcement Learning there are two core components:" }, { "code": null, "e": 12795, "s": 12614, "text": "An Agent, that represents the “solution” , which is a computer program with a single role of making decisions (actions) to solve complex decision-making problems under uncertainty." }, { "code": null, "e": 13059, "s": 12795, "text": "An Environment, that is the representation of a “problem”, which is everything that comes after the decision of the Agent. The environment responds with the consequences of those actions, which are observations or states, and rewards, also sometimes called costs." }, { "code": null, "e": 13217, "s": 13059, "text": "For example, in the tic-tac-toe game, we can consider that the Agent is one of the players, and the Environment includes the board game and the other player." }, { "code": null, "e": 13544, "s": 13217, "text": "These two core components continuously interact so that the Agent attempts to influence the Environment through actions, and the Environment reacts to the Agent’s actions. How the environment reacts to specific actions is defined by a model that may or may not be known by the Agent, and this differentiates two circumstances:" }, { "code": null, "e": 13769, "s": 13544, "text": "When the Agent knows the model, we refer to this situation as a model-based RL. In this case, when we fully know the Environment, we can find the optimal solution by Dynamic Programming. This is not the purpose of this post." }, { "code": null, "e": 13946, "s": 13769, "text": "When the Agent does not know the model, it needs to make decisions with incomplete information; do model-free RL, or try to learn the model explicitly as part of the algorithm." }, { "code": null, "e": 14264, "s": 13946, "text": "The Environment is represented by a set of variables related to the problem (very dependent on the type of problem we want to solve). This set of variables and all the possible values they can take are referred to as the state space. A state is an instantiation of the state space, a set of values the variables take." }, { "code": null, "e": 14597, "s": 14264, "text": "Due that we are considering that the Agent doesn’t have access to the actual full state of the Environment, it is usually called observation, the part of the state that the Agent can observe. However, we will often see in the literature observations and states being used interchangeably, so we will do this in this series of posts." }, { "code": null, "e": 14975, "s": 14597, "text": "At each state, the Environment makes available a set of actions, from which the Agent will choose an action. The Agent influences the Environment through these actions, and the Environment may change states as a response to the Agent’s action. The function responsible for this mapping is called in the literature transition function or transition probabilities between states." }, { "code": null, "e": 15475, "s": 14975, "text": "The Environment commonly has a well-defined task and may provide to the Agent a reward signal as a direct answer to the Agent’s actions. This reward is feedback on how well the last action contributes to achieving the task to be performed by the Environment. The function responsible for this mapping is called the reward function. As we will see later, the Agent’s goal is to maximize the overall reward it receives, and so rewards are the motivation the Agent needs to act in the desired behavior." }, { "code": null, "e": 15584, "s": 15475, "text": "Let’s summarize in the following Figure the concepts introduced earlier in the Reinforcement Learning cycle:" }, { "code": null, "e": 15697, "s": 15584, "text": "Generally speaking, Reinforcement Learning is basically about turning this Figure into a mathematical formalism." }, { "code": null, "e": 16161, "s": 15697, "text": "The cycle begins with the Agent observing the Environment (step 1) and receiving a state and a reward. The Agent uses this state and reward for deciding the next action to take (step 2). The Agent then sends an action to the Environment in an attempt to control it in a favorable way (step 3). Finally, the environment transitions, and its internal state changes as a consequence due to the previous state and the Agent’s action (step 4). Then, the cycle repeats." }, { "code": null, "e": 16510, "s": 16161, "text": "The task the Agent is trying to solve may or may not have a natural ending. Tasks that have a natural ending, such as a game, are called episodic tasks. Conversely, tasks that do not, are called continuous tasks, for example learning forward motion. The sequence of time steps from the beginning to the end of an episodic task is called an episode." }, { "code": null, "e": 16723, "s": 16510, "text": "As we will see, Agents may take several time steps and episodes to learn how to solve a task. The sum of rewards collected in a single episode is called a return. Agents are often designed to maximize the return." }, { "code": null, "e": 17179, "s": 16723, "text": "One of the limitations is that these rewards are not disclosed to the Agent until the end of an episode, which we introduced earlier as “delayed reward”. For example, in the game of tic-tac-toe the rewards for each movement (action) are not known until the end of the game. It would be a positive reward if the agent won the game (because the agent had achieved the overall desired outcome) or a negative reward (penalties) if the agent had lost the game." }, { "code": null, "e": 17571, "s": 17179, "text": "Another important characteristic, and challenge in Reinforcement Learning, is the trade-off between “exploration” and “exploitation”. Trying to obtain many rewards, an Agent must prefer actions that it has tried in the past and knows that will be effective actions in producing reward. But to discover such actions, paradoxically, it has to try actions that it has not selected never before." }, { "code": null, "e": 17916, "s": 17571, "text": "In summary, an Agent has to exploit what it has already experienced to obtain as much reward as possible, but at the same time, it also has to explore to make select better action in the future. The exploration-exploitation dilemma is a crucial topic and still an unsolved research topic. We will talk about this trade-off later in this series." }, { "code": null, "e": 18066, "s": 17916, "text": "Let’s strengthen our understanding of Reinforcement Learning by looking at a simple example, a Frozen Lake (very slippery) where our agent can skate:" }, { "code": null, "e": 18415, "s": 18066, "text": "The Frozen-Lake Environment that we will use as an example is an ice skating rink, divided into 16 cells (4x4), and as shown in the figure below, some of the cells have broken the ice. The skater named Agent begins to skate in the top-left position, and its goal is to reach the bottom-right place avoiding falling into the four holes in the track." }, { "code": null, "e": 18666, "s": 18415, "text": "The described example is coded as the Frozen-Lake Environment from Gym. With this example of Environment, we will review and clarify the RL terminology introduced until now. It will also be useful for future posts in this series to have this example." }, { "code": null, "e": 19270, "s": 18666, "text": "OpenAI is an artificial intelligence (AI) research organization that provides a famous toolkit called Gym for training a reinforcement learning agent to develop and compare RL algorithms. Gym offers a variety of environments for training an RL agent ranging from classic control tasks to Atari game environments. We can train our RL agent to learn in these simulated environments using various RL algorithms. Throughout the series, we will use the Gym toolkit to build and evaluate reinforcement learning algorithms for several classic control tasks such as Cart-Pole balancing or mountain car climbing." }, { "code": null, "e": 19617, "s": 19270, "text": "Gym also provides 59 Atari game environments, including Pong, Space Invaders, Air Raid, Asteroids, Centipede, Ms. Pac-Man, etc. Training our reinforcement learning agent to play Atari games is an interesting as well as challenging task. Later in this series, we will train our DQN reinforcement learning agent to play Atari Pong game environment." }, { "code": null, "e": 19724, "s": 19617, "text": "Let’s introduce as an example one of the most straightforward environments called Frozen-Lake environment." }, { "code": null, "e": 19947, "s": 19724, "text": "Frozen-Lake Environment is from the so-called grid-world category when the Agent lives in a grid of size 4x4 (has 16 cells), which means a state space composed of 16 states (0–15) in the i, j coordinates of the grid-world." }, { "code": null, "e": 20395, "s": 19947, "text": "In Frozen-Lake, the Agent always starts at a top-left position, and its goal is to reach the bottom-right position of the grid. There are four holes in the fixed cells of the grid, and if the Agent gets into those holes, the episode ends, and the reward obtained is zero. If the Agent reaches the destination cell, it receives a reward of +1, and the episode ends. The following Figure shows a visual representation of the Frozen-Lake Environment:" }, { "code": null, "e": 20681, "s": 20395, "text": "To reach the goal, the Agent has an action space composed of four directions movements: up, down, left, and right. We also know that there is a fence around the lake, so if the Agent tries to move out of the grid world, it will just bounce back to the cell from which it tried to move." }, { "code": null, "e": 21074, "s": 20681, "text": "Because the lake is frozen, the world is slippery, so the Agent’s actions do not always turn out as expected — there is a 33% chance that it will slip to the right or the left. If we want the Agent to move left, for example, there is a 33% probability that it will, indeed, move left, a 33% chance that it will end up in the cell above, and a 33% chance that it will end up in the cell below." }, { "code": null, "e": 21296, "s": 21074, "text": "This behavior of the Environment is reflected in the transition function or transition probabilities presented before. However, at this point, we do not need to go into more detail on this function and leave it for later." }, { "code": null, "e": 21384, "s": 21296, "text": "As a summary, we could represent all this information visually in the following Figure:" }, { "code": null, "e": 21675, "s": 21384, "text": "Let’s look at how this Environment is represented in Gym. I suggest to use the Colab offered by Google to execute the code described in this post (Gym package is already installed). If you prefer to use your Python programming environment, you can install Gym using the steps provided here." }, { "code": null, "e": 21708, "s": 21675, "text": "The first step is to import Gym:" }, { "code": null, "e": 21719, "s": 21708, "text": "import gym" }, { "code": null, "e": 21802, "s": 21719, "text": "Then, specify the game from Gym you want to use. We will use the Frozen-Lake game:" }, { "code": null, "e": 21834, "s": 21802, "text": "env = gym.make('FrozenLake-v0')" }, { "code": null, "e": 21903, "s": 21834, "text": "The environment of the game can be reset to the initial state using:" }, { "code": null, "e": 21915, "s": 21903, "text": "env.reset()" }, { "code": null, "e": 21965, "s": 21915, "text": "And, to see a view of the game state, we can use:" }, { "code": null, "e": 21978, "s": 21965, "text": "env.render()" }, { "code": null, "e": 22056, "s": 21978, "text": "The surface rendered by render()is presented using a grid like the following:" }, { "code": null, "e": 22153, "s": 22056, "text": "Where the highlighted character indicates the position of the Agent in the current time step and" }, { "code": null, "e": 22201, "s": 22153, "text": "“S” indicates the starting cell (safe position)" }, { "code": null, "e": 22248, "s": 22201, "text": "“F” indicates a frozen surface (safe position)" }, { "code": null, "e": 22269, "s": 22248, "text": "“H” indicates a hole" }, { "code": null, "e": 22293, "s": 22269, "text": "“G”: indicates the goal" }, { "code": null, "e": 22396, "s": 22293, "text": "The official documentation can be found here to see the detailed usage and explanation of Gym toolkit." }, { "code": null, "e": 22614, "s": 22396, "text": "For the moment, we will create the most straightforward Agent that we can make that only does random actions. For this purpose, we will use the action_space.sample() that samples a random action from the action space." }, { "code": null, "e": 22707, "s": 22614, "text": "Assume that we allow a maximum of 10 iterations; the following code can be our “dumb” Agent:" }, { "code": null, "e": 22955, "s": 22707, "text": "import gymenv = gym.make(\"FrozenLake-v0\")env.reset()for t in range(10): print(\"\\nTimestep {}\".format(t)) env.render() a = env.action_space.sample() ob, r, done, _ = env.step(a) if done: print(\"\\nEpisode terminated early\") break" }, { "code": null, "e": 23101, "s": 22955, "text": "If we run this code, it will output something like the following lines, where we can observe the Timestep, the action, and the Environment state:" }, { "code": null, "e": 23522, "s": 23101, "text": "In general, it is challenging, if not almost impossible, to find an episode of our “dumb” Agent in which, with randomly selected actions, it can overcome the obstacles and reach the goal cell. So how could we build an Agent to pursue it?. This is what we will present in the next installment of this series, where we will further formalize the problem and build a new Agent version that can learn to reach the goal cell." }, { "code": null, "e": 23648, "s": 23522, "text": "To finish this post, let’s review the basis of Reinforcement Learning for a moment, comparing it with other learning methods." }, { "code": null, "e": 23981, "s": 23648, "text": "In supervised learning, the system learns from training data that consists of a labeled pair of inputs and outputs. So, we train the model (Agent) using the training data in such a way that the model can generalize its learning to new unseen data (the labeled pairs of inputs and outputs guide the model in learning the given task)." }, { "code": null, "e": 24628, "s": 23981, "text": "Let’s understand the difference between supervised and reinforcement learning with an example. Imagine we want to train a model to play chess using supervised learning. In this case, we will train the model to learn using a training dataset that includes all the moves a player can make in each state, along with labels indicating whether it is a good move or not. Whereas in the case of RL, our agent will not be given any sort of training data; instead, we just provide a reward to the agent for each action it performs. Then, the agent will learn by interacting with the environment, and it will choose its actions based on the reward it gets." }, { "code": null, "e": 25103, "s": 24628, "text": "Similar to supervised learning, in unsupervised learning, we train the model based on the training data. But in the case of unsupervised learning, the training data does not contain any labels. And this leads to a common misconception that RL is a kind of unsupervised learning due we don’t have labels as input data. But it is not. In unsupervised learning, the model learns the hidden structure in the input data, whereas, in RL, the model learns by maximizing the reward." }, { "code": null, "e": 25950, "s": 25103, "text": "A classic example is a movie recommendation system that wants to recommend a new movie to the user. With unsupervised learning, the model (agent) will find movies similar to the film the user (or users with a profile similar to the user) has viewed before and recommend new movies to the user. Instead, with Reinforcement Learning, the agent continually receives feedback from the user. This feedback represents rewards (a reward could be time spent watching a movie, time spent watching trailers, how many movies in a row have he watched, and so on). Based on the rewards, an RL agent will understand the user’s movie preference and then suggest new movies accordingly. It is essential to notice that an RL agent can know if the user’s movie preference changes and suggest new movies according to the user’s changed movie preference dynamically." }, { "code": null, "e": 26341, "s": 25950, "text": "We can think that we don’t have data in Reinforcement Learning as we have in Supervised or Unsupervised Learning. However, the data is actually the Environment because if you interact with this Environment, then data (trajectories) can be created, which are sequences of observations and actions. Then we can do some learning on top, and that’s basically the core of Reinforcement Learning." }, { "code": null, "e": 26746, "s": 26341, "text": "Sometimes, we can use extra data from people or trajectories that exist, for instance, in imitation learning. We might actually just observe a bunch of people playing the game, and we don’t need to know precisely how the Environment works. Sometimes we have explicitly given a data set, as a sort of a supervised data set, but in the pure Reinforcement Learning setting, the only data is the Environment." }, { "code": null, "e": 27078, "s": 26746, "text": "Reinforcement Learning has evolved rapidly over the past few years with a wide range of applications. One of the primary reasons for this evolution is the combination of Reinforcement Learning and Deep Learning. This is why we focus this series on presenting the basic state-of-the-art Deep Reinforcement Learning algorithms (DRL)." }, { "code": null, "e": 27428, "s": 27078, "text": "The media has tended to focus on applications where DRL defeat humans at games, with examples as I mentioned at the beginning of this post: AlphaGo defeated the best professional human player in the game of Go; AlphaStar beat professional players at the game of StarCraft II; OpenAI’s Dota-2-playing bot beat the world champions in an e-sports game." }, { "code": null, "e": 27943, "s": 27428, "text": "Fortunately, there are many real-life applications of DRL. One of the well known is in the area of driverless cars. In manufacturing, intelligent robots are trained using DRL to place objects in the right position, reducing labor costs, and increasing productivity. Another popular application of RL is dynamic pricing that allows changing the price of products based on demand and supply. Also, in a recommendation system, RL is used to build a recommendation system where the user’s behavior continually changes." }, { "code": null, "e": 28357, "s": 27943, "text": "In today’s business activities, DRL is used extensively in supply chain management, demand forecasting, inventory management, handling warehouse operations, etc. DRL is also widely used in financial portfolio management, predicting, and trading in commercial transaction markets. DRL has been commonly used in several Natural Language Processing (NLP) tasks, such as abstractive text summarization, chatbots, etc." }, { "code": null, "e": 28537, "s": 28357, "text": "Many recent research papers suggest applications of DRL in healthcare, education systems, smart cities, among many others. In summary, no business sector is left untouched by DRL." }, { "code": null, "e": 28869, "s": 28537, "text": "DRL agents can sometimes control hazardous real-life Environments, like robots or cars, which increases the risk of making incorrect choices. There is an important field called safe RL that attempts to deal with this risk, for instance, learning a policy that maximizes rewards while operating within predefined safety constraints." }, { "code": null, "e": 29133, "s": 28869, "text": "Also, DRL agents are also at risk from an attack, like any other software system. But DRL adds a few new attack vectors over and above traditional machine learning systems because, in general, we are dealing with systems much more complex to understand and model." }, { "code": null, "e": 29401, "s": 29133, "text": "Considering the safety and security of DRL systems are outside the introductory scope of this post. Still, I would like the reader to be aware of it and if in the future you put a DRL system into operation, keep in mind that you should treat this point in more depth." }, { "code": null, "e": 29702, "s": 29401, "text": "Artificial Intelligence is definitely penetrating society, like electricity, what will we expect? The future we will “invent” is a choice we make jointly, not something that happens. We are in a position of power. With DRL, we have the power and authority to automate decisions and entire strategies." }, { "code": null, "e": 30198, "s": 29702, "text": "This is good! But as in most things in life, where there is light, can be the shadow, and DRL technology is hazardous in the wrong hands. I ask you that as engineers consider what we are building: Could our DRL system accidentally add bias? How does this affect individuals?. Or how does our solution affect the climate due to its energy consumption? Can be our DRL solution unintended used? Or use?. Or, in accordance with our ethics, can it have a type of use that we could consider nefarious?" }, { "code": null, "e": 30468, "s": 30198, "text": "We must mull over the imminent adoption of Artificial Intelligence and its impact. Were we to go on to build Artificial Intelligence without regard to our responsibility of preventing its misuse, we can never expect to see Artificial Intelligence help humanity prosper." }, { "code": null, "e": 30621, "s": 30468, "text": "All of us, who are working or want to work on these topics, cannot shy away from our responsibility, because otherwise, we will regret it in the future." }, { "code": null, "e": 30971, "s": 30621, "text": "We started the post by understanding the basic idea of RL. We learned that RL is a trial and error learning process and the learning in RL happens based on a reward. We presented the difference between RL and the other ML paradigms. Finally, we looked into some real-life applications of RL and thought about the safety, security, and ethics of DRL." }, { "code": null, "e": 31198, "s": 30971, "text": "In the next post, we will learn about the Markov Decision Process (MDP) and how the RL environment can be modeled as an MDP. Next, we will review several important fundamental concepts involved in RL. See you in the next post!" }, { "code": null, "e": 31224, "s": 31198, "text": "Post updated on 8/12/2020" }, { "code": null, "e": 31282, "s": 31224, "text": "by UPC Barcelona Tech and Barcelona Supercomputing Center" }, { "code": null, "e": 31507, "s": 31282, "text": "A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence." }, { "code": null, "e": 31773, "s": 31507, "text": "I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made." } ]
How to create a list of matrices in R?
To create a list of matrices, we simply need to find the matrix object inside list function. For example, if we have five matrix objects either of same or different dimensions defined as Matrix1, Matrix2, Matrix3, Matrix4, and Matrix5 then the list of these matrices can be created as − List_of_Matrix<-list(Matrix1,Matrix2,Matrix3,Matrix4,Matrix5) Consider the below matrices − Live Demo M1<-matrix(1:25,ncol=5) M1 [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 Live Demo M2<-matrix(rnorm(36,5,1),ncol=6) M2 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 5.832047 4.945123 5.358729 3.574902 4.350990 4.087932 [2,] 4.772671 5.250141 4.988955 5.365941 4.880831 3.562414 [3,] 5.266137 5.618243 4.059351 5.248413 5.664136 4.202910 [4,] 4.623297 4.827376 4.884175 5.065288 6.100969 6.254083 [5,] 7.441365 2.776100 4.185031 5.019156 5.143771 5.772142 [6,] 4.204661 3.736386 5.242263 5.257338 4.882246 4.780484 Live Demo M3<-matrix(rpois(100,5),nrow=10) M3 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 4 6 6 7 3 9 2 5 3 5 [2,] 6 5 9 4 3 9 4 4 5 4 [3,] 4 8 5 7 6 4 7 5 9 9 [4,] 6 4 6 4 9 3 4 4 6 5 [5,] 7 3 4 3 2 3 3 5 9 4 [6,] 7 8 2 5 7 4 4 8 5 4 [7,] 4 5 8 4 9 5 6 3 5 7 [8,] 4 8 4 3 7 8 4 4 5 6 [9,] 8 3 5 5 4 5 6 3 2 3 [10,] 6 6 2 5 6 3 6 4 3 2 Live Demo M4<-matrix(runif(25,2,5),nrow=5) M4 [,1] [,2] [,3] [,4] [,5] [1,] 4.264117 3.145149 2.543695 4.640957 2.464495 [2,] 3.861230 2.507933 3.431941 3.119190 2.396685 [3,] 2.508730 2.895958 4.312211 2.143877 2.663918 [4,] 2.186642 2.576629 2.083361 2.415885 2.679142 [5,] 2.327088 2.771510 3.581932 2.964476 2.394250 Live Demo M5<-matrix(sample(0:5,64,replace=TRUE),nrow=8) M5 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 3 0 2 3 3 0 4 2 [2,] 3 0 4 3 5 0 3 2 [3,] 0 5 0 5 3 3 5 1 [4,] 1 5 0 3 4 3 0 0 [5,] 3 5 0 4 3 4 1 3 [6,] 0 3 5 1 1 4 0 1 [7,] 0 2 4 3 1 5 4 4 [8,] 2 4 3 0 1 0 1 4 Live Demo M6<-matrix(sample(c(5,15,20,25,30),49,replace=TRUE),nrow=7) M6 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 20 30 15 20 20 20 15 [2,] 15 25 30 5 15 30 25 [3,] 25 30 5 30 25 15 5 [4,] 20 20 20 25 5 30 5 [5,] 20 20 15 15 5 25 5 [6,] 5 5 25 30 5 15 30 [7,] 25 5 5 30 20 15 5 Creating list of matrices − List<-list(M1,M2,M3,M4,M5,M6) List [[1]] [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 [[2]] [,1] [,2] [,3] [,4] [,5] [,6] [1,] 5.832047 4.945123 5.358729 3.574902 4.350990 4.087932 [2,] 4.772671 5.250141 4.988955 5.365941 4.880831 3.562414 [3,] 5.266137 5.618243 4.059351 5.248413 5.664136 4.202910 [4,] 4.623297 4.827376 4.884175 5.065288 6.100969 6.254083 [5,] 7.441365 2.776100 4.185031 5.019156 5.143771 5.772142 [6,] 4.204661 3.736386 5.242263 5.257338 4.882246 4.780484 [[3]] [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 4 6 6 7 3 9 2 5 3 5 [2,] 6 5 9 4 3 9 4 4 5 4 [3,] 4 8 5 7 6 4 7 5 9 9 [4,] 6 4 6 4 9 3 4 4 6 5 [5,] 7 3 4 3 2 3 3 5 9 4 [6,] 7 8 2 5 7 4 4 8 5 4 [7,] 4 5 8 4 9 5 6 3 5 7 [8,] 4 8 4 3 7 8 4 4 5 6 [9,] 8 3 5 5 4 5 6 3 2 3 [10,] 6 6 2 5 6 3 6 4 3 2 [[4]] [,1] [,2] [,3] [,4] [,5] [1,] 4.264117 3.145149 2.543695 4.640957 2.464495 [2,] 3.861230 2.507933 3.431941 3.119190 2.396685 [3,] 2.508730 2.895958 4.312211 2.143877 2.663918 [4,] 2.186642 2.576629 2.083361 2.415885 2.679142 [5,] 2.327088 2.771510 3.581932 2.964476 2.394250 [[5]] [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 3 0 2 3 3 0 4 2 [2,] 3 0 4 3 5 0 3 2 [3,] 0 5 0 5 3 3 5 1 [4,] 1 5 0 3 4 3 0 0 [5,] 3 5 0 4 3 4 1 3 [6,] 0 3 5 1 1 4 0 1 [7,] 0 2 4 3 1 5 4 4 [8,] 2 4 3 0 1 0 1 4 [[6]] [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 20 30 15 20 20 20 15 [2,] 15 25 30 5 15 30 25 [3,] 25 30 5 30 25 15 5 [4,] 20 20 20 25 5 30 5 [5,] 20 20 15 15 5 25 5 [6,] 5 5 25 30 5 15 30 [7,] 25 5 5 30 20 15 5
[ { "code": null, "e": 1349, "s": 1062, "text": "To create a list of matrices, we simply need to find the matrix object inside list function. For example, if we have five matrix objects either of same or different dimensions defined as Matrix1, Matrix2, Matrix3, Matrix4, and Matrix5 then the list of these matrices can be created as −" }, { "code": null, "e": 1411, "s": 1349, "text": "List_of_Matrix<-list(Matrix1,Matrix2,Matrix3,Matrix4,Matrix5)" }, { "code": null, "e": 1441, "s": 1411, "text": "Consider the below matrices −" }, { "code": null, "e": 1452, "s": 1441, "text": " Live Demo" }, { "code": null, "e": 1479, "s": 1452, "text": "M1<-matrix(1:25,ncol=5)\nM1" }, { "code": null, "e": 1647, "s": 1479, "text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 1 6 11 16 21\n[2,] 2 7 12 17 22\n[3,] 3 8 13 18 23\n[4,] 4 9 14 19 24\n[5,] 5 10 15 20 25" }, { "code": null, "e": 1658, "s": 1647, "text": " Live Demo" }, { "code": null, "e": 1694, "s": 1658, "text": "M2<-matrix(rnorm(36,5,1),ncol=6)\nM2" }, { "code": null, "e": 2105, "s": 1694, "text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 5.832047 4.945123 5.358729 3.574902 4.350990 4.087932\n[2,] 4.772671 5.250141 4.988955 5.365941 4.880831 3.562414\n[3,] 5.266137 5.618243 4.059351 5.248413 5.664136 4.202910\n[4,] 4.623297 4.827376 4.884175 5.065288 6.100969 6.254083\n[5,] 7.441365 2.776100 4.185031 5.019156 5.143771 5.772142\n[6,] 4.204661 3.736386 5.242263 5.257338 4.882246 4.780484" }, { "code": null, "e": 2116, "s": 2105, "text": " Live Demo" }, { "code": null, "e": 2152, "s": 2116, "text": "M3<-matrix(rpois(100,5),nrow=10)\nM3" }, { "code": null, "e": 2726, "s": 2152, "text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 4 6 6 7 3 9 2 5 3 5\n[2,] 6 5 9 4 3 9 4 4 5 4\n[3,] 4 8 5 7 6 4 7 5 9 9\n[4,] 6 4 6 4 9 3 4 4 6 5\n[5,] 7 3 4 3 2 3 3 5 9 4\n[6,] 7 8 2 5 7 4 4 8 5 4\n[7,] 4 5 8 4 9 5 6 3 5 7\n[8,] 4 8 4 3 7 8 4 4 5 6\n[9,] 8 3 5 5 4 5 6 3 2 3\n[10,] 6 6 2 5 6 3 6 4 3 2" }, { "code": null, "e": 2737, "s": 2726, "text": " Live Demo" }, { "code": null, "e": 2773, "s": 2737, "text": "M4<-matrix(runif(25,2,5),nrow=5)\nM4" }, { "code": null, "e": 3072, "s": 2773, "text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 4.264117 3.145149 2.543695 4.640957 2.464495\n[2,] 3.861230 2.507933 3.431941 3.119190 2.396685\n[3,] 2.508730 2.895958 4.312211 2.143877 2.663918\n[4,] 2.186642 2.576629 2.083361 2.415885 2.679142\n[5,] 2.327088 2.771510 3.581932 2.964476 2.394250" }, { "code": null, "e": 3083, "s": 3072, "text": " Live Demo" }, { "code": null, "e": 3133, "s": 3083, "text": "M5<-matrix(sample(0:5,64,replace=TRUE),nrow=8)\nM5" }, { "code": null, "e": 3512, "s": 3133, "text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 3 0 2 3 3 0 4 2\n[2,] 3 0 4 3 5 0 3 2\n[3,] 0 5 0 5 3 3 5 1\n[4,] 1 5 0 3 4 3 0 0\n[5,] 3 5 0 4 3 4 1 3\n[6,] 0 3 5 1 1 4 0 1\n[7,] 0 2 4 3 1 5 4 4\n[8,] 2 4 3 0 1 0 1 4" }, { "code": null, "e": 3523, "s": 3512, "text": " Live Demo" }, { "code": null, "e": 3586, "s": 3523, "text": "M6<-matrix(sample(c(5,15,20,25,30),49,replace=TRUE),nrow=7)\nM6" }, { "code": null, "e": 3894, "s": 3586, "text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n[1,] 20 30 15 20 20 20 15\n[2,] 15 25 30 5 15 30 25\n[3,] 25 30 5 30 25 15 5\n[4,] 20 20 20 25 5 30 5\n[5,] 20 20 15 15 5 25 5\n[6,] 5 5 25 30 5 15 30\n[7,] 25 5 5 30 20 15 5" }, { "code": null, "e": 3922, "s": 3894, "text": "Creating list of matrices −" }, { "code": null, "e": 3957, "s": 3922, "text": "List<-list(M1,M2,M3,M4,M5,M6)\nList" }, { "code": null, "e": 6131, "s": 3957, "text": "[[1]]\n [,1] [,2] [,3] [,4] [,5]\n[1,] 1 6 11 16 21\n[2,] 2 7 12 17 22\n[3,] 3 8 13 18 23\n[4,] 4 9 14 19 24\n[5,] 5 10 15 20 25\n[[2]]\n [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 5.832047 4.945123 5.358729 3.574902 4.350990 4.087932\n[2,] 4.772671 5.250141 4.988955 5.365941 4.880831 3.562414\n[3,] 5.266137 5.618243 4.059351 5.248413 5.664136 4.202910\n[4,] 4.623297 4.827376 4.884175 5.065288 6.100969 6.254083\n[5,] 7.441365 2.776100 4.185031 5.019156 5.143771 5.772142\n[6,] 4.204661 3.736386 5.242263 5.257338 4.882246 4.780484\n[[3]]\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 4 6 6 7 3 9 2 5 3 5\n[2,] 6 5 9 4 3 9 4 4 5 4\n[3,] 4 8 5 7 6 4 7 5 9 9\n[4,] 6 4 6 4 9 3 4 4 6 5\n[5,] 7 3 4 3 2 3 3 5 9 4\n[6,] 7 8 2 5 7 4 4 8 5 4\n[7,] 4 5 8 4 9 5 6 3 5 7\n[8,] 4 8 4 3 7 8 4 4 5 6\n[9,] 8 3 5 5 4 5 6 3 2 3\n[10,] 6 6 2 5 6 3 6 4 3 2\n[[4]]\n [,1] [,2] [,3] [,4] [,5]\n[1,] 4.264117 3.145149 2.543695 4.640957 2.464495\n[2,] 3.861230 2.507933 3.431941 3.119190 2.396685\n[3,] 2.508730 2.895958 4.312211 2.143877 2.663918\n[4,] 2.186642 2.576629 2.083361 2.415885 2.679142\n[5,] 2.327088 2.771510 3.581932 2.964476 2.394250\n[[5]]\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 3 0 2 3 3 0 4 2\n[2,] 3 0 4 3 5 0 3 2\n[3,] 0 5 0 5 3 3 5 1\n[4,] 1 5 0 3 4 3 0 0\n[5,] 3 5 0 4 3 4 1 3\n[6,] 0 3 5 1 1 4 0 1\n[7,] 0 2 4 3 1 5 4 4\n[8,] 2 4 3 0 1 0 1 4\n[[6]]\n [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n[1,] 20 30 15 20 20 20 15\n[2,] 15 25 30 5 15 30 25\n[3,] 25 30 5 30 25 15 5\n[4,] 20 20 20 25 5 30 5\n[5,] 20 20 15 15 5 25 5\n[6,] 5 5 25 30 5 15 30\n[7,] 25 5 5 30 20 15 5" } ]
C library function - ceil()
The C library function double ceil(double x) returns the smallest integer value greater than or equal to x. Following is the declaration for ceil() function. double ceil(double x) x − This is the floating point value. x − This is the floating point value. This function returns the smallest integral value not less than x. The following example shows the usage of ceil() function. #include <stdio.h> #include <math.h> int main () { float val1, val2, val3, val4; val1 = 1.6; val2 = 1.2; val3 = 2.8; val4 = 2.3; printf ("value1 = %.1lf\n", ceil(val1)); printf ("value2 = %.1lf\n", ceil(val2)); printf ("value3 = %.1lf\n", ceil(val3)); printf ("value4 = %.1lf\n", ceil(val4)); return(0); } Let us compile and run the above program that will produce the following result − value1 = 2.0 value2 = 2.0 value3 = 3.0 value4 = 3.0 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2115, "s": 2007, "text": "The C library function double ceil(double x) returns the smallest integer value greater than or equal to x." }, { "code": null, "e": 2165, "s": 2115, "text": "Following is the declaration for ceil() function." }, { "code": null, "e": 2187, "s": 2165, "text": "double ceil(double x)" }, { "code": null, "e": 2225, "s": 2187, "text": "x − This is the floating point value." }, { "code": null, "e": 2263, "s": 2225, "text": "x − This is the floating point value." }, { "code": null, "e": 2330, "s": 2263, "text": "This function returns the smallest integral value not less than x." }, { "code": null, "e": 2388, "s": 2330, "text": "The following example shows the usage of ceil() function." }, { "code": null, "e": 2731, "s": 2388, "text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n float val1, val2, val3, val4;\n\n val1 = 1.6;\n val2 = 1.2;\n val3 = 2.8;\n val4 = 2.3;\n\n printf (\"value1 = %.1lf\\n\", ceil(val1));\n printf (\"value2 = %.1lf\\n\", ceil(val2));\n printf (\"value3 = %.1lf\\n\", ceil(val3));\n printf (\"value4 = %.1lf\\n\", ceil(val4));\n \n return(0);\n}" }, { "code": null, "e": 2813, "s": 2731, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2866, "s": 2813, "text": "value1 = 2.0\nvalue2 = 2.0\nvalue3 = 3.0\nvalue4 = 3.0\n" }, { "code": null, "e": 2899, "s": 2866, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2914, "s": 2899, "text": " Nishant Malik" }, { "code": null, "e": 2949, "s": 2914, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2964, "s": 2949, "text": " Nishant Malik" }, { "code": null, "e": 2999, "s": 2964, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3013, "s": 2999, "text": " Asif Hussain" }, { "code": null, "e": 3046, "s": 3013, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3064, "s": 3046, "text": " Richa Maheshwari" }, { "code": null, "e": 3099, "s": 3064, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3118, "s": 3099, "text": " Vandana Annavaram" }, { "code": null, "e": 3151, "s": 3118, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3163, "s": 3151, "text": " Amit Diwan" }, { "code": null, "e": 3170, "s": 3163, "text": " Print" }, { "code": null, "e": 3181, "s": 3170, "text": " Add Notes" } ]
Node.js dns.resolve() Method - GeeksforGeeks
13 Oct, 2021 The dns.resolve() method is an inbuilt application programming interface of the dns module which is used to resolve hostname into an array of the resource records. Syntax: dns.resolve( hostname, rrtype, callback ) Parameters: This method accept three parameters as mentioned above and described below: hostname: This parameter specifies a string which denotes the hostname to be resolved. rrtype: It specifies the resource record type. Its default value is ‘A’. The list of records (‘A’, ‘AAAA’, ‘ANY’, ‘CNAME’, ‘MX’, ‘TXT’, ‘NS’, ‘NAPTR’, ‘PTR’, ‘SOA’, ‘SRV’) are described below:A: IPv4 addressAAAA: IPv6 addressANY: Any recordsCNAME: canonical name recordsMX: mail exchange recordsNAPTR: name authority pointer recordsNS: name server recordsPTR: pointer recordsSOA: start of authority recordsSRV: service recordsTXT: text records A: IPv4 address AAAA: IPv6 address ANY: Any records CNAME: canonical name records MX: mail exchange records NAPTR: name authority pointer records NS: name server records PTR: pointer records SOA: start of authority records SRV: service records TXT: text records callback: It specifies a function which to be called after DNS resolution of the hostname.error: It specifies error if generated.records: It’s string or object that signifies the returned record.Return Value: This method returns error, records through callback function, These data are passed as parameters to the callback function.Below examples illustrate the use of dns.resolve() Method in Node.js:Example 1:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="A"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: ["34.218.62.116"]Example 2:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="MX"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: [ {"exchange":"alt1.aspmx.l.google.com", "priority":5}, {"exchange":"alt2.aspmx.l.google.com", "priority":5}, {"exchange":"aspmx.l.google.com", "priority":1}, {"exchange":"alt3.aspmx.l.google.com", "priority":10}, {"exchange":"alt4.aspmx.l.google.com", "priority":10} ] Example 3:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="TXT"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: [ ["v=spf1 include:amazonses.com include:_spf.google.com -all"], ["fob1m1abcdp777bf2ncvnjm08n"] ] Example 4:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="NS"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: [ "ns-1520.awsdns-62.org", "ns-1569.awsdns-04.co.uk", "ns-245.awsdns-30.com", "ns-869.awsdns-44.net" ] Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/dns.html#dns_dns_resolve_hostname_rrtype_callbackMy Personal Notes arrow_drop_upSave error: It specifies error if generated. records: It’s string or object that signifies the returned record. Return Value: This method returns error, records through callback function, These data are passed as parameters to the callback function. Below examples illustrate the use of dns.resolve() Method in Node.js: Example 1: // Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="A"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records)); Output: records: ["34.218.62.116"] Example 2: // Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="MX"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records)); Output: records: [ {"exchange":"alt1.aspmx.l.google.com", "priority":5}, {"exchange":"alt2.aspmx.l.google.com", "priority":5}, {"exchange":"aspmx.l.google.com", "priority":1}, {"exchange":"alt3.aspmx.l.google.com", "priority":10}, {"exchange":"alt4.aspmx.l.google.com", "priority":10} ] Example 3: // Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="TXT"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records)); Output: records: [ ["v=spf1 include:amazonses.com include:_spf.google.com -all"], ["fob1m1abcdp777bf2ncvnjm08n"] ] Example 4: // Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype="NS"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records)); Output: records: [ "ns-1520.awsdns-62.org", "ns-1569.awsdns-04.co.uk", "ns-245.awsdns-30.com", "ns-869.awsdns-44.net" ] Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/api/dns.html#dns_dns_resolve_hostname_rrtype_callback Node.js-dns-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method How to update NPM ? Node.js fs.writeFile() Method Difference between promise and async await in Node.js Top 10 Front End Developer Skills That You Need in 2022 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 36865, "s": 36837, "text": "\n13 Oct, 2021" }, { "code": null, "e": 37029, "s": 36865, "text": "The dns.resolve() method is an inbuilt application programming interface of the dns module which is used to resolve hostname into an array of the resource records." }, { "code": null, "e": 37037, "s": 37029, "text": "Syntax:" }, { "code": null, "e": 37079, "s": 37037, "text": "dns.resolve( hostname, rrtype, callback )" }, { "code": null, "e": 37167, "s": 37079, "text": "Parameters: This method accept three parameters as mentioned above and described below:" }, { "code": null, "e": 37254, "s": 37167, "text": "hostname: This parameter specifies a string which denotes the hostname to be resolved." }, { "code": null, "e": 37698, "s": 37254, "text": "rrtype: It specifies the resource record type. Its default value is ‘A’. The list of records (‘A’, ‘AAAA’, ‘ANY’, ‘CNAME’, ‘MX’, ‘TXT’, ‘NS’, ‘NAPTR’, ‘PTR’, ‘SOA’, ‘SRV’) are described below:A: IPv4 addressAAAA: IPv6 addressANY: Any recordsCNAME: canonical name recordsMX: mail exchange recordsNAPTR: name authority pointer recordsNS: name server recordsPTR: pointer recordsSOA: start of authority recordsSRV: service recordsTXT: text records" }, { "code": null, "e": 37714, "s": 37698, "text": "A: IPv4 address" }, { "code": null, "e": 37733, "s": 37714, "text": "AAAA: IPv6 address" }, { "code": null, "e": 37750, "s": 37733, "text": "ANY: Any records" }, { "code": null, "e": 37780, "s": 37750, "text": "CNAME: canonical name records" }, { "code": null, "e": 37806, "s": 37780, "text": "MX: mail exchange records" }, { "code": null, "e": 37844, "s": 37806, "text": "NAPTR: name authority pointer records" }, { "code": null, "e": 37868, "s": 37844, "text": "NS: name server records" }, { "code": null, "e": 37889, "s": 37868, "text": "PTR: pointer records" }, { "code": null, "e": 37921, "s": 37889, "text": "SOA: start of authority records" }, { "code": null, "e": 37942, "s": 37921, "text": "SRV: service records" }, { "code": null, "e": 37960, "s": 37942, "text": "TXT: text records" }, { "code": null, "e": 40749, "s": 37960, "text": "callback: It specifies a function which to be called after DNS resolution of the hostname.error: It specifies error if generated.records: It’s string or object that signifies the returned record.Return Value: This method returns error, records through callback function, These data are passed as parameters to the callback function.Below examples illustrate the use of dns.resolve() Method in Node.js:Example 1:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"A\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: [\"34.218.62.116\"]Example 2:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"MX\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: [\n {\"exchange\":\"alt1.aspmx.l.google.com\", \"priority\":5},\n {\"exchange\":\"alt2.aspmx.l.google.com\", \"priority\":5},\n {\"exchange\":\"aspmx.l.google.com\", \"priority\":1},\n {\"exchange\":\"alt3.aspmx.l.google.com\", \"priority\":10},\n {\"exchange\":\"alt4.aspmx.l.google.com\", \"priority\":10}\n]\nExample 3:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"TXT\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: [\n [\"v=spf1 include:amazonses.com include:_spf.google.com -all\"],\n [\"fob1m1abcdp777bf2ncvnjm08n\"]\n]\nExample 4:// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"NS\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));Output:records: [\n \"ns-1520.awsdns-62.org\", \n \"ns-1569.awsdns-04.co.uk\",\n \"ns-245.awsdns-30.com\",\n \"ns-869.awsdns-44.net\"\n]\nNote: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/dns.html#dns_dns_resolve_hostname_rrtype_callbackMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 40789, "s": 40749, "text": "error: It specifies error if generated." }, { "code": null, "e": 40856, "s": 40789, "text": "records: It’s string or object that signifies the returned record." }, { "code": null, "e": 40994, "s": 40856, "text": "Return Value: This method returns error, records through callback function, These data are passed as parameters to the callback function." }, { "code": null, "e": 41064, "s": 40994, "text": "Below examples illustrate the use of dns.resolve() Method in Node.js:" }, { "code": null, "e": 41075, "s": 41064, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"A\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));", "e": 41464, "s": 41075, "text": null }, { "code": null, "e": 41472, "s": 41464, "text": "Output:" }, { "code": null, "e": 41499, "s": 41472, "text": "records: [\"34.218.62.116\"]" }, { "code": null, "e": 41510, "s": 41499, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"MX\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));", "e": 41904, "s": 41510, "text": null }, { "code": null, "e": 41912, "s": 41904, "text": "Output:" }, { "code": null, "e": 42212, "s": 41912, "text": "records: [\n {\"exchange\":\"alt1.aspmx.l.google.com\", \"priority\":5},\n {\"exchange\":\"alt2.aspmx.l.google.com\", \"priority\":5},\n {\"exchange\":\"aspmx.l.google.com\", \"priority\":1},\n {\"exchange\":\"alt3.aspmx.l.google.com\", \"priority\":10},\n {\"exchange\":\"alt4.aspmx.l.google.com\", \"priority\":10}\n]\n" }, { "code": null, "e": 42223, "s": 42212, "text": "Example 3:" }, { "code": "// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"TXT\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));", "e": 42610, "s": 42223, "text": null }, { "code": null, "e": 42618, "s": 42610, "text": "Output:" }, { "code": null, "e": 42734, "s": 42618, "text": "records: [\n [\"v=spf1 include:amazonses.com include:_spf.google.com -all\"],\n [\"fob1m1abcdp777bf2ncvnjm08n\"]\n]\n" }, { "code": null, "e": 42745, "s": 42734, "text": "Example 4:" }, { "code": "// Node.js program to demonstrate the // dns.resolve() method // Accessing dns moduleconst dns = require('dns'); // Set the rrtype for dns.resolve() methodconst rrtype=\"NS\"; // Calling dns.resolve() method for hostname// geeksforgeeks.org and print them in// console as a callbackdns.resolve('geeksforgeeks.org', rrtype, (err, records) => console.log('records: %j', records));", "e": 43131, "s": 42745, "text": null }, { "code": null, "e": 43139, "s": 43131, "text": "Output:" }, { "code": null, "e": 43269, "s": 43139, "text": "records: [\n \"ns-1520.awsdns-62.org\", \n \"ns-1569.awsdns-04.co.uk\",\n \"ns-245.awsdns-30.com\",\n \"ns-869.awsdns-44.net\"\n]\n" }, { "code": null, "e": 43350, "s": 43269, "text": "Note: The above program will compile and run by using the node index.js command." }, { "code": null, "e": 43434, "s": 43350, "text": "Reference: https://nodejs.org/api/dns.html#dns_dns_resolve_hostname_rrtype_callback" }, { "code": null, "e": 43453, "s": 43434, "text": "Node.js-dns-module" }, { "code": null, "e": 43461, "s": 43453, "text": "Node.js" }, { "code": null, "e": 43478, "s": 43461, "text": "Web Technologies" }, { "code": null, "e": 43576, "s": 43478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43585, "s": 43576, "text": "Comments" }, { "code": null, "e": 43598, "s": 43585, "text": "Old Comments" }, { "code": null, "e": 43646, "s": 43598, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 43679, "s": 43646, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 43699, "s": 43679, "text": "How to update NPM ?" }, { "code": null, "e": 43729, "s": 43699, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 43783, "s": 43729, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 43839, "s": 43783, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 43901, "s": 43839, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 43944, "s": 43901, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 43994, "s": 43944, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Fetch records from comma separated values using MySQL IN()?
Use FIND_IN_SET() instead of MySQL IN(). Let us first create a − mysql> create table DemoTable1423 -> ( -> CountryName varchar(100) -> ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert − mysql> insert into DemoTable1423 values('AUS,UK'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1423 values('US'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1423 values('AUS,UK,US'); Query OK, 1 row affected (0.13 sec) Display all records from the table using select − mysql> select * from DemoTable1423; This will produce the following output − +-------------+ | CountryName | +-------------+ | AUS,UK | | US | | AUS,UK,US | +-------------+ 3 rows in set (0.00 sec) Here is the query to fetch records using FIND_IN_SET()− mysql> select * from DemoTable1423 where find_in_set('US',CountryName); This will produce the following output − +-------------+ | CountryName | +-------------+ | US | | AUS,UK,US | +-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1127, "s": 1062, "text": "Use FIND_IN_SET() instead of MySQL IN(). Let us first create a −" }, { "code": null, "e": 1246, "s": 1127, "text": "mysql> create table DemoTable1423\n -> (\n -> CountryName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1294, "s": 1246, "text": "Insert some records in the table using insert −" }, { "code": null, "e": 1554, "s": 1294, "text": "mysql> insert into DemoTable1423 values('AUS,UK');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable1423 values('US');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable1423 values('AUS,UK,US');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 1604, "s": 1554, "text": "Display all records from the table using select −" }, { "code": null, "e": 1640, "s": 1604, "text": "mysql> select * from DemoTable1423;" }, { "code": null, "e": 1681, "s": 1640, "text": "This will produce the following output −" }, { "code": null, "e": 1818, "s": 1681, "text": "+-------------+\n| CountryName |\n+-------------+\n| AUS,UK |\n| US |\n| AUS,UK,US |\n+-------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1874, "s": 1818, "text": "Here is the query to fetch records using FIND_IN_SET()−" }, { "code": null, "e": 1946, "s": 1874, "text": "mysql> select * from DemoTable1423 where find_in_set('US',CountryName);" }, { "code": null, "e": 1987, "s": 1946, "text": "This will produce the following output −" }, { "code": null, "e": 2108, "s": 1987, "text": "+-------------+\n| CountryName |\n+-------------+\n| US |\n| AUS,UK,US |\n+-------------+\n2 rows in set (0.00 sec)" } ]
Number of nodes greater than a given value in n-ary tree - GeeksforGeeks
04 Aug, 2021 Given a n-ary tree and a number x, find and return the number of nodes which are greater than x. Example: In the given tree, x = 7 Number of nodes greater than x are 4. Approach : The idea is maintain a count variable initialize to 0. Traverse the tree and compare root data with x. If root data is greater than x, increment the count variable and recursively call for all its children. Below is the implementation of idea. C++ Java Python3 C# // C++ program to find number of nodes// greater than x#include <bits/stdc++.h>using namespace std; // Structure of a node of n-ary treestruct Node { int 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 find number of nodes// greater than xint nodesGreaterThanX(Node* root, int x){ if (root == NULL) return 0; int count = 0; // if current root is greater // than x increment count if (root->key > x) count++; // Number of children of root int numChildren = root->child.size(); // recursively calling for every child for (int i = 0; i < numChildren; i++) { Node* child = root->child[i]; count += nodesGreaterThanX(child, x); } // return the count return count;} // Driver programint main(){ /* Let us create below tree* 5* / | \* 1 2 3* / / \ \* 15 4 5 6*/ Node* root = newNode(5); (root->child).push_back(newNode(1)); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(3)); (root->child[0]->child).push_back(newNode(15)); (root->child[1]->child).push_back(newNode(4)); (root->child[1]->child).push_back(newNode(5)); (root->child[2]->child).push_back(newNode(6)); int x = 5; cout << "Number of nodes greater than " << x << " are "; cout << nodesGreaterThanX(root, x) << endl; return 0;} // Java program to find number of nodes// greater than ximport java.util.*; // Class representing a Node of an N-ary treeclass Node{ int key; ArrayList<Node> child; // Constructor to create a Node Node(int val) { key = val; child = new ArrayList<>(); }} class GFG{ // Recursive function to find number// of nodes greater than xpublic static int nodesGreaterThanX(Node root, int x){ if (root == null) return 0; int count = 0; // If current root is greater // than x increment count if (root.key > x) count++; // Recursively calling for every // child of current root for(Node child : root.child) { count += nodesGreaterThanX(child, x); } // Return the count return count;} // Driver codepublic static void main(String[] args){ /* Let us create below tree 5 / | \ 1 2 3 / / \ \ 15 4 5 6 */ Node root = new Node(5); root.child.add(new Node(1)); root.child.add(new Node(2)); root.child.add(new Node(3)); root.child.get(0).child.add(new Node(15)); root.child.get(1).child.add(new Node(4)); root.child.get(1).child.add(new Node(5)); root.child.get(2).child.add(new Node(6)); int x = 5; System.out.print("Number of nodes greater than " + x + " are "); System.out.println(nodesGreaterThanX(root, x));}} // This code is contributed by jrishabh99 # Python3 program to find number of nodes# greater than x # Structure of a node of n-ary treeclass Node: def __init__(self, data): self.key = data self.child = [] # Function to find number of nodes# greater than xdef nodesGreaterThanX(root: Node, x: int) -> int: if root is None: return 0 count = 0 # if current root is greater # than x increment count if root.key > x: count += 1 # Number of children of root numChildren = len(root.child) # recursively calling for every child for i in range(numChildren): child = root.child[i] count += nodesGreaterThanX(child, x) # return the count return count # Driver Codeif __name__ == "__main__": ans = 0 k = 25 # Let us create below tree # 5 # / | \ # 1 2 3 # / / \ \ # 15 4 5 6 root = Node(5) (root.child).append(Node(1)) (root.child).append(Node(2)) (root.child).append(Node(3)) (root.child[0].child).append(Node(15)) (root.child[1].child).append(Node(4)) (root.child[1].child).append(Node(5)) (root.child[2].child).append(Node(6)) x = 5 print("Number of nodes greater than % d are % d" % (x, nodesGreaterThanX(root, x))) # This code is contributed by# sanjeev2552 // C# program to find number of nodes// greater than xusing System;using System.Collections.Generic; // Class representing a Node of an N-ary treepublic class Node{ public int key; public List<Node> child; // Constructor to create a Node public Node(int val) { key = val; child = new List<Node>(); }} class GFG{ // Recursive function to find number// of nodes greater than xpublic static int nodesGreaterThanX(Node root, int x){ if (root == null) return 0; int count = 0; // If current root is greater // than x increment count if (root.key > x) count++; // Recursively calling for every // child of current root foreach(Node child in root.child) { count += nodesGreaterThanX(child, x); } // Return the count return count;} // Driver codepublic static void Main(String[] args){ /* Let us create below tree 5 / | \ 1 2 3 / / \ \ 15 4 5 6 */ Node root = new Node(5); root.child.Add(new Node(1)); root.child.Add(new Node(2)); root.child.Add(new Node(3)); root.child[0].child.Add(new Node(15)); root.child[1].child.Add(new Node(4)); root.child[1].child.Add(new Node(5)); root.child[2].child.Add(new Node(6)); int x = 5; Console.Write("Number of nodes greater than " + x + " are "); Console.WriteLine(nodesGreaterThanX(root, x));}} // This code is contributed by Amit Katiyar Output: Number of nodes greater than 5 are 2 YouTubeGeeksforGeeks500K subscribersNumber of nodes greater than a given value in n-ary tree | 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 / 6:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OpYZ8fbF61g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 jrishabh99 amit143katiyar AshokJaiswal anikaseth98 arorakashish0911 n-ary-tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not Decision Tree Inorder Tree Traversal without recursion and without stack! Construct Tree from given Inorder and Preorder traversals Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1
[ { "code": null, "e": 24821, "s": 24793, "text": "\n04 Aug, 2021" }, { "code": null, "e": 24919, "s": 24821, "text": "Given a n-ary tree and a number x, find and return the number of nodes which are greater than x. " }, { "code": null, "e": 24929, "s": 24919, "text": "Example: " }, { "code": null, "e": 24954, "s": 24929, "text": "In the given tree, x = 7" }, { "code": null, "e": 24992, "s": 24954, "text": "Number of nodes greater than x are 4." }, { "code": null, "e": 25211, "s": 24992, "text": "Approach : The idea is maintain a count variable initialize to 0. Traverse the tree and compare root data with x. If root data is greater than x, increment the count variable and recursively call for all its children. " }, { "code": null, "e": 25249, "s": 25211, "text": "Below is the implementation of idea. " }, { "code": null, "e": 25253, "s": 25249, "text": "C++" }, { "code": null, "e": 25258, "s": 25253, "text": "Java" }, { "code": null, "e": 25266, "s": 25258, "text": "Python3" }, { "code": null, "e": 25269, "s": 25266, "text": "C#" }, { "code": "// C++ program to find number of nodes// greater than x#include <bits/stdc++.h>using namespace std; // Structure of a node of n-ary treestruct Node { int 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 find number of nodes// greater than xint nodesGreaterThanX(Node* root, int x){ if (root == NULL) return 0; int count = 0; // if current root is greater // than x increment count if (root->key > x) count++; // Number of children of root int numChildren = root->child.size(); // recursively calling for every child for (int i = 0; i < numChildren; i++) { Node* child = root->child[i]; count += nodesGreaterThanX(child, x); } // return the count return count;} // Driver programint main(){ /* Let us create below tree* 5* / | \\* 1 2 3* / / \\ \\* 15 4 5 6*/ Node* root = newNode(5); (root->child).push_back(newNode(1)); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(3)); (root->child[0]->child).push_back(newNode(15)); (root->child[1]->child).push_back(newNode(4)); (root->child[1]->child).push_back(newNode(5)); (root->child[2]->child).push_back(newNode(6)); int x = 5; cout << \"Number of nodes greater than \" << x << \" are \"; cout << nodesGreaterThanX(root, x) << endl; return 0;}", "e": 26761, "s": 25269, "text": null }, { "code": "// Java program to find number of nodes// greater than ximport java.util.*; // Class representing a Node of an N-ary treeclass Node{ int key; ArrayList<Node> child; // Constructor to create a Node Node(int val) { key = val; child = new ArrayList<>(); }} class GFG{ // Recursive function to find number// of nodes greater than xpublic static int nodesGreaterThanX(Node root, int x){ if (root == null) return 0; int count = 0; // If current root is greater // than x increment count if (root.key > x) count++; // Recursively calling for every // child of current root for(Node child : root.child) { count += nodesGreaterThanX(child, x); } // Return the count return count;} // Driver codepublic static void main(String[] args){ /* Let us create below tree 5 / | \\ 1 2 3 / / \\ \\ 15 4 5 6 */ Node root = new Node(5); root.child.add(new Node(1)); root.child.add(new Node(2)); root.child.add(new Node(3)); root.child.get(0).child.add(new Node(15)); root.child.get(1).child.add(new Node(4)); root.child.get(1).child.add(new Node(5)); root.child.get(2).child.add(new Node(6)); int x = 5; System.out.print(\"Number of nodes greater than \" + x + \" are \"); System.out.println(nodesGreaterThanX(root, x));}} // This code is contributed by jrishabh99", "e": 28212, "s": 26761, "text": null }, { "code": "# Python3 program to find number of nodes# greater than x # Structure of a node of n-ary treeclass Node: def __init__(self, data): self.key = data self.child = [] # Function to find number of nodes# greater than xdef nodesGreaterThanX(root: Node, x: int) -> int: if root is None: return 0 count = 0 # if current root is greater # than x increment count if root.key > x: count += 1 # Number of children of root numChildren = len(root.child) # recursively calling for every child for i in range(numChildren): child = root.child[i] count += nodesGreaterThanX(child, x) # return the count return count # Driver Codeif __name__ == \"__main__\": ans = 0 k = 25 # Let us create below tree # 5 # / | \\ # 1 2 3 # / / \\ \\ # 15 4 5 6 root = Node(5) (root.child).append(Node(1)) (root.child).append(Node(2)) (root.child).append(Node(3)) (root.child[0].child).append(Node(15)) (root.child[1].child).append(Node(4)) (root.child[1].child).append(Node(5)) (root.child[2].child).append(Node(6)) x = 5 print(\"Number of nodes greater than % d are % d\" % (x, nodesGreaterThanX(root, x))) # This code is contributed by# sanjeev2552", "e": 29482, "s": 28212, "text": null }, { "code": "// C# program to find number of nodes// greater than xusing System;using System.Collections.Generic; // Class representing a Node of an N-ary treepublic class Node{ public int key; public List<Node> child; // Constructor to create a Node public Node(int val) { key = val; child = new List<Node>(); }} class GFG{ // Recursive function to find number// of nodes greater than xpublic static int nodesGreaterThanX(Node root, int x){ if (root == null) return 0; int count = 0; // If current root is greater // than x increment count if (root.key > x) count++; // Recursively calling for every // child of current root foreach(Node child in root.child) { count += nodesGreaterThanX(child, x); } // Return the count return count;} // Driver codepublic static void Main(String[] args){ /* Let us create below tree 5 / | \\ 1 2 3 / / \\ \\ 15 4 5 6 */ Node root = new Node(5); root.child.Add(new Node(1)); root.child.Add(new Node(2)); root.child.Add(new Node(3)); root.child[0].child.Add(new Node(15)); root.child[1].child.Add(new Node(4)); root.child[1].child.Add(new Node(5)); root.child[2].child.Add(new Node(6)); int x = 5; Console.Write(\"Number of nodes greater than \" + x + \" are \"); Console.WriteLine(nodesGreaterThanX(root, x));}} // This code is contributed by Amit Katiyar", "e": 30963, "s": 29482, "text": null }, { "code": null, "e": 30972, "s": 30963, "text": "Output: " }, { "code": null, "e": 31009, "s": 30972, "text": "Number of nodes greater than 5 are 2" }, { "code": null, "e": 31864, "s": 31009, "text": "YouTubeGeeksforGeeks500K subscribersNumber of nodes greater than a given value in n-ary tree | 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 / 6:07•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=OpYZ8fbF61g\" 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": 32279, "s": 31864, "text": "This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32291, "s": 32279, "text": "sanjeev2552" }, { "code": null, "e": 32302, "s": 32291, "text": "jrishabh99" }, { "code": null, "e": 32317, "s": 32302, "text": "amit143katiyar" }, { "code": null, "e": 32330, "s": 32317, "text": "AshokJaiswal" }, { "code": null, "e": 32342, "s": 32330, "text": "anikaseth98" }, { "code": null, "e": 32359, "s": 32342, "text": "arorakashish0911" }, { "code": null, "e": 32370, "s": 32359, "text": "n-ary-tree" }, { "code": null, "e": 32375, "s": 32370, "text": "Tree" }, { "code": null, "e": 32380, "s": 32375, "text": "Tree" }, { "code": null, "e": 32478, "s": 32380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32487, "s": 32478, "text": "Comments" }, { "code": null, "e": 32500, "s": 32487, "text": "Old Comments" }, { "code": null, "e": 32541, "s": 32500, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 32584, "s": 32541, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 32617, "s": 32584, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 32667, "s": 32617, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 32681, "s": 32667, "text": "Decision Tree" }, { "code": null, "e": 32741, "s": 32681, "text": "Inorder Tree Traversal without recursion and without stack!" }, { "code": null, "e": 32799, "s": 32741, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 32882, "s": 32799, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 32918, "s": 32882, "text": "Introduction to Tree Data Structure" } ]
How to set Proxy in Firefox using Selenium WebDriver?
We can set a proxy in Firefox using Selenium webdriver. A proxy server enables users to access an URL of an application for testing purposes even with the presence of several layers of network. The setting up of proxy in Firefox can be done with the help of the FirefoxOptions class. The port information and the proxy server host are added to this class. The setting up of the proxy server can also be done by configuring the Firefox Profile in the FirefoxProfile class. Code Implementation with the FirefoxOptions import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; public class ConfigureProxy { public static void main(String[] args) { //object of Proxy Proxy p = new Proxy(); //adding host and port p.setHttpProxy("<HOST:PORT>"); p.setSslProxy("<HOST:PORT>"); p.setSslProxy("<HOST:PORT>"); p.setFtpProxy("<HOST:PORT>"); //object of FirefoxOptions FirefoxOptions o = new FirefoxOptions(); o.setCapability("proxy", p); //passing Firefox option to webdriver object WebDriver driver = new FirefoxDriver(o); //url launch driver.get("https://www.tutorialspoint.com/index.htm"); //browser close driver.close(); } } Code Implementation with the FirefoxOptions import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; public class ConfigureProxyProfile { public static void main(String[] args) { //object of Proxy Proxy p = new Proxy(); //adding host and port p.setHttpProxy("<HOST:PORT>"); p.setSslProxy("<HOST:PORT>"); p.setSslProxy("<HOST:PORT>"); p.setFtpProxy("<HOST:PORT>"); //object of FirefoxProfile FirefoxProfile pl = new FirefoxProfile(); pl.setProxyPreferences(p); //passing Firefox profile to webdriver object WebDriver driver = new FirefoxDriver(pl); //url launch driver.get("https://www.tutorialspoint.com/index.htm"); //browser close driver.close(); } }
[ { "code": null, "e": 1256, "s": 1062, "text": "We can set a proxy in Firefox using Selenium webdriver. A proxy server enables users to access an URL of an application for testing purposes even with the presence of several layers of network." }, { "code": null, "e": 1534, "s": 1256, "text": "The setting up of proxy in Firefox can be done with the help of the FirefoxOptions class. The port information and the proxy server host are added to this class. The setting up of the proxy server can also be done by configuring the Firefox Profile in the FirefoxProfile class." }, { "code": null, "e": 1578, "s": 1534, "text": "Code Implementation with the FirefoxOptions" }, { "code": null, "e": 2397, "s": 1578, "text": "import org.openqa.selenium.Proxy;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.firefox.FirefoxOptions;\npublic class ConfigureProxy {\n public static void main(String[] args) {\n //object of Proxy\n Proxy p = new Proxy();\n //adding host and port\n p.setHttpProxy(\"<HOST:PORT>\");\n p.setSslProxy(\"<HOST:PORT>\");\n p.setSslProxy(\"<HOST:PORT>\");\n p.setFtpProxy(\"<HOST:PORT>\");\n //object of FirefoxOptions\n FirefoxOptions o = new FirefoxOptions();\n o.setCapability(\"proxy\", p);\n //passing Firefox option to webdriver object\n WebDriver driver = new FirefoxDriver(o);\n //url launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n //browser close\n driver.close();\n }\n}" }, { "code": null, "e": 2441, "s": 2397, "text": "Code Implementation with the FirefoxOptions" }, { "code": null, "e": 3268, "s": 2441, "text": "import org.openqa.selenium.Proxy;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.firefox.FirefoxProfile;\npublic class ConfigureProxyProfile {\n public static void main(String[] args) {\n //object of Proxy\n Proxy p = new Proxy();\n //adding host and port\n p.setHttpProxy(\"<HOST:PORT>\");\n p.setSslProxy(\"<HOST:PORT>\");\n p.setSslProxy(\"<HOST:PORT>\");\n p.setFtpProxy(\"<HOST:PORT>\");\n //object of FirefoxProfile\n FirefoxProfile pl = new FirefoxProfile();\n pl.setProxyPreferences(p);\n //passing Firefox profile to webdriver object\n WebDriver driver = new FirefoxDriver(pl);\n //url launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n //browser close\n driver.close();\n }\n}" } ]
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method - GeeksforGeeks
06 Dec, 2021 Given a list of integers, now our task is to sort the given list of integers. So we use the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. This method is overloaded in two different ways: OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>): It is used to sort the items of the given sequence in ascending order according to the key and performs a stable sort on the given sequence or list. OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>): It is used to sort the items of the given sequence in ascending order by using a given comparer and also performs a stable sort on the given sequence. Example: Input : [90, 87, 34, 23, 22, 56, 21, 89] Output : [21, 22, 23, 34, 56, 87, 89, 90] Input : [10, 11, 2, 3, 18, 5,] Output : [2, 3, 5, 10, 11, 18] Approach: 1. Create and initialize a list of integer types. For example nums. 2. Sorting the list(named nums) using OrderBy() method var result_set = nums.OrderBy(num => num); 3. Display the result using the foreach loop. Example: C# // C# program to sort a list of integers // Using OrderBy() methodusing System;using System.Linq;using System.Collections.Generic; class GFG{ static void Main(string[] args){ // Creating and initializing list of integers List<int> nums = new List<int>() { 50, 20, 40, 60, 33, 70 }; // Using order by method we sort the list var result_set = nums.OrderBy(num => num); // Display the list Console.WriteLine("Sorted in Ascending order:"); foreach (int value in result_set) { Console.Write(value + " "); }}} Sorted in Ascending order: 20 33 40 50 60 70 CSharp LINQ Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Getting a Month Name Using Month Number in C# Socket Programming in C# Program to Print a New Line in C# Program to find absolute value of a given number
[ { "code": null, "e": 23911, "s": 23883, "text": "\n06 Dec, 2021" }, { "code": null, "e": 24157, "s": 23911, "text": "Given a list of integers, now our task is to sort the given list of integers. So we use the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. This method is overloaded in two different ways:" }, { "code": null, "e": 24373, "s": 24157, "text": "OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>): It is used to sort the items of the given sequence in ascending order according to the key and performs a stable sort on the given sequence or list." }, { "code": null, "e": 24608, "s": 24373, "text": "OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>): It is used to sort the items of the given sequence in ascending order by using a given comparer and also performs a stable sort on the given sequence." }, { "code": null, "e": 24618, "s": 24608, "text": "Example: " }, { "code": null, "e": 24768, "s": 24618, "text": "Input : [90, 87, 34, 23, 22, 56, 21, 89]\nOutput : [21, 22, 23, 34, 56, 87, 89, 90] \n\nInput : [10, 11, 2, 3, 18, 5,]\nOutput : [2, 3, 5, 10, 11, 18] " }, { "code": null, "e": 24778, "s": 24768, "text": "Approach:" }, { "code": null, "e": 24846, "s": 24778, "text": "1. Create and initialize a list of integer types. For example nums." }, { "code": null, "e": 24901, "s": 24846, "text": "2. Sorting the list(named nums) using OrderBy() method" }, { "code": null, "e": 24944, "s": 24901, "text": "var result_set = nums.OrderBy(num => num);" }, { "code": null, "e": 24990, "s": 24944, "text": "3. Display the result using the foreach loop." }, { "code": null, "e": 24999, "s": 24990, "text": "Example:" }, { "code": null, "e": 25002, "s": 24999, "text": "C#" }, { "code": "// C# program to sort a list of integers // Using OrderBy() methodusing System;using System.Linq;using System.Collections.Generic; class GFG{ static void Main(string[] args){ // Creating and initializing list of integers List<int> nums = new List<int>() { 50, 20, 40, 60, 33, 70 }; // Using order by method we sort the list var result_set = nums.OrderBy(num => num); // Display the list Console.WriteLine(\"Sorted in Ascending order:\"); foreach (int value in result_set) { Console.Write(value + \" \"); }}}", "e": 25558, "s": 25002, "text": null }, { "code": null, "e": 25604, "s": 25558, "text": "Sorted in Ascending order:\n20 33 40 50 60 70 " }, { "code": null, "e": 25616, "s": 25604, "text": "CSharp LINQ" }, { "code": null, "e": 25623, "s": 25616, "text": "Picked" }, { "code": null, "e": 25626, "s": 25623, "text": "C#" }, { "code": null, "e": 25638, "s": 25626, "text": "C# Programs" }, { "code": null, "e": 25736, "s": 25638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25745, "s": 25736, "text": "Comments" }, { "code": null, "e": 25758, "s": 25745, "text": "Old Comments" }, { "code": null, "e": 25798, "s": 25758, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 25821, "s": 25798, "text": "Extension Method in C#" }, { "code": null, "e": 25849, "s": 25821, "text": "HashSet in C# with Examples" }, { "code": null, "e": 25871, "s": 25849, "text": "Partial Classes in C#" }, { "code": null, "e": 25888, "s": 25871, "text": "C# | Inheritance" }, { "code": null, "e": 25928, "s": 25888, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 25974, "s": 25928, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 25999, "s": 25974, "text": "Socket Programming in C#" }, { "code": null, "e": 26033, "s": 25999, "text": "Program to Print a New Line in C#" } ]