title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach )
01 Nov, 2021 Giving k sorted arrays, each of size N, the task is to merge them into a single sorted array. Examples: Input: arr[][] = {{5, 7, 15, 18}, {1, 8, 9, 17}, {1, 4, 7, 7}} Output: {1, 1, 4, 5, 7, 7, 7, 8, 9, 15, 17, 18} Input: arr[][] = {{3, 2, 1} {6, 5, 4}} Output: {1, 2, 3, 4, 5, 6} Prerequisite: Merge SortSimple Approach: A simple solution is to append all the arrays one after another and sort them. C++14 Java Python3 C# Javascript // C++ program to merge K// sorted arrays#include <bits/stdc++.h>using namespace std;#define N 4 // Merge and sort k arraysvoid merge_and_sort( vector<int> &output, vector<vector<int>> arr, int n, int k){ // Put the elements in sorted array. for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { output[(i * n) + j] = arr[i][j]; } } // Sort the output array sort(output.begin(), output.end());} // Driver Functionint main(){ // Input 2D-array vector<vector<int>> arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; int n = N; // Number of arrays int k = arr.size(); // Output array vector<int> output(n*k); merge_and_sort(output, arr, n, k); // Print merged array for (int i = 0; i < n * k; i++) cout << output[i] << " "; return 0;} // Java program to merge K// sorted arraysimport java.util.*;class GFG{ static int N = 4; // Merge and sort k arrays static void merge_and_sort(int output[], int arr[][], int n, int k) { // Put the elements in sorted array. for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { output[i * n + j] = arr[i][j]; } } // Sort the output array Arrays.sort(output); } // Driver code public static void main(String[] args) { // Input 2D-array int arr[][] = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; int n = N; // Number of arrays int k = arr.length; // Output array int output[] = new int[n * k]; merge_and_sort(output, arr, n, k); // Print merged array for (int i = 0; i < n * k; i++) System.out.print(output[i] + " "); }} // This code is contributed by divyesh072019 # Python3 program to merge K# sorted arraysN = 4 # Merge and sort k arraysdef merge_and_sort(output, arr, n, k): # Put the elements in sorted array. for i in range(k): for j in range(n): output[i * n + j] = arr[i][j]; # Sort the output array output.sort() # Driver Functionif __name__=='__main__': # Input 2D-array arr = [ [ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ] ]; n = N; # Number of arrays k = len(arr) # Output array output = [0 for i in range(n * k)] merge_and_sort(output, arr, n, k); # Print merged array for i in range(n * k): print(output[i], end = ' ') # This code is contributed by rutvik_56. // C# program to merge K// sorted arraysusing System;class GFG{ static int N = 4; // Merge and sort k arrays static void merge_and_sort(int[] output, int[,] arr, int n, int k) { // Put the elements in sorted array. for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { output[i * n + j] = arr[i,j]; } } // Sort the output array Array.Sort(output); } // Driver code static void Main() { // Input 2D-array int[,] arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; int n = N; // Number of arrays int k = arr.GetLength(0); // Output array int[] output = new int[n * k]; merge_and_sort(output, arr, n, k); // Print merged array for (int i = 0; i < n * k; i++) Console.Write(output[i] + " "); }} // This code is contributed by divyeshrabadiya07 <script> // Javascript program to merge K // sorted arrays let N = 4; // Merge and sort k arrays function merge_and_sort(output, arr, n, k) { // Put the elements in sorted array. for (let i = 0; i < k; i++) { for (let j = 0; j < n; j++) { output[i * n + j] = arr[i][j]; } } // Sort the output array output.sort(function(a, b){return a - b}); } // Input 2D-array let arr = [ [ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ] ]; let n = N; // Number of arrays let k = 3; // Output array let output = new Array(n * k); merge_and_sort(output, arr, n, k); // Print merged array for (let i = 0; i < n * k; i++) document.write(output[i] + " "); // This code is contributed by mukesh07.</script> 1 1 4 5 7 7 7 8 9 15 17 18 Complexity Analysis: Time Complexity: O(N*k*log(N*k)). The size of all elements is n*k so the time complexity is O(N*k * log(N*k)) Space Complexity: O(N*k). To store the output array O(N*k) space is required. Efficient Solution: Approach: The idea becomes clear once we start looking at the k arrays as the intermediate state of the merge sort algorithm. Since there are k arrays that are already sorted, merge the k arrays. Create a recursive function which will take k arrays and divide them into two parts and call the function recursively with each half. The base cases are when the value of k is less than 3. See this article to merge two arrays in O(n) time. Algorithm: Initialize the output array with the size N*k.Call the function divide. Let and represent the range of arrays that are to be merged and thus vary between 0 to k-1.At each step, we call the left and right half of the range recursively so that, they will be sorted and stored in the output array.After that, we merge the left and right half. For merging, we need to determine the range of indexes for the left and right halves in the output array. We can easily find that. Left part will start from the index l * n of the output array.Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array. Initialize the output array with the size N*k. Call the function divide. Let and represent the range of arrays that are to be merged and thus vary between 0 to k-1. At each step, we call the left and right half of the range recursively so that, they will be sorted and stored in the output array. After that, we merge the left and right half. For merging, we need to determine the range of indexes for the left and right halves in the output array. We can easily find that. Left part will start from the index l * n of the output array.Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array. Left part will start from the index l * n of the output array.Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array. Left part will start from the index l * n of the output array. Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array. C++ Java Python3 C# PHP Javascript // C++ program to merge K// sorted arrays #include<bits/stdc++.h>#define n 4 using namespace std; // Function to perform merge operationvoid merge(int l, int r, vector<int>& output){ // to store the starting point // of left and right array int l_in = l * n, r_in = ((l + r) / 2 + 1) * n; // To store the size of left and // right array int l_c = ((l + r) / 2 - l + 1) * n; int r_c = (r - (l + r) / 2) * n; // array to temporarily store left // and right array int l_arr[l_c], r_arr[r_c]; // storing data in left array for (int i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data in right array for (int i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array int l_curr = 0, r_curr = 0; // to store the current index // for output array int in = l_in; // two pointer merge for // two sorted arrays while ( l_curr + r_curr < l_c + r_c) { if ( r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) output[in] = l_arr[l_curr], l_curr++, in++; else output[in] = r_arr[r_curr], r_curr++, in++; }} // Code to drive merge-sort and// create recursion treevoid divide(int l, int r, vector<int>& output, vector<vector<int>> arr){ if (l == r) { /* base step to initialize the output array before performing merge operation */ for (int i = 0; i < n; i++) output[l * n + i] = arr[l][i]; return; } // To sort left half divide(l, (l + r) / 2, output, arr); // To sort right half divide((l + r) / 2 + 1, r, output, arr); // Merge the left and right half merge(l, r, output);} // Driver Functionint main(){ // input 2D-array vector<vector<int>> arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; // Number of arrays int k = arr.size(); // Output array vector<int> output(n*k); divide(0, k - 1, output, arr); // Print merged array for (int i = 0; i < n * k; i++) cout << output[i] << " "; return 0;} // Java program to merge// K sorted arraysimport java.util.*; class GFG { static int n = 4; // Function to perform // merge operation static void merge( int l, int r, int[] output) { // To store the starting point // of left and right array int l_in = l * n, r_in = ((l + r) / 2 + 1) * n; // to store the size of left and // right array int l_c = ((l + r) / 2 - l + 1) * n; int r_c = (r - (l + r) / 2) * n; // array to temporarily store left // and right array int l_arr[] = new int[l_c], r_arr[] = new int[r_c]; // storing data in left array for (int i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data in right array for (int i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array int l_curr = 0, r_curr = 0; // to store the current index // for output array int in = l_in; // two pointer merge for two sorted arrays while (l_curr + r_curr < l_c + r_c) { if ( r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) { output[in] = l_arr[l_curr]; l_curr++; in++; } else { output[in] = r_arr[r_curr]; r_curr++; in++; } } } // Code to drive merge-sort and // create recursion tree static void divide(int l, int r, int[] output, int arr[][]) { if (l == r) { /* base step to initialize the output array before performing merge operation */ for (int i = 0; i < n; i++) output[l * n + i] = arr[l][i]; return; } // to sort left half divide(l, (l + r) / 2, output, arr); // to sort right half divide((l + r) / 2 + 1, r, output, arr); // merge the left and right half merge(l, r, output); } // Driver Code public static void main(String[] args) { // input 2D-array int arr[][] = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; // Number of arrays int k = arr.length; // Output array int[] output = new int[n * k]; divide(0, k - 1, output, arr); // Print merged array for (int i = 0; i < n * k; i++) System.out.print(output[i] + " "); }} /* This code contributed by PrinciRaj1992 */ # Python3 program to merge K sorted arraysn = 4 ; # Function to perform merge operationdef merge(l, r, output) : # to store the starting point of # left and right array l_in = l * n ; r_in = ((l + r) // 2 + 1) * n; # to store the size of left and # right array l_c = ((l + r) // 2 - l + 1) * n; r_c = (r - (l + r) // 2) * n; # array to temporarily store left # and right array l_arr = [0] * l_c; r_arr = [0] * r_c; # storing data in left array for i in range(l_c) : l_arr[i] = output[l_in + i]; # storing data in right array for i in range(r_c) : r_arr[i] = output[r_in + i]; # to store the current index of # temporary left and right array l_curr = 0 ; r_curr = 0; # to store the current index # for output array in1 = l_in; # two pointer merge for two sorted arrays while (l_curr + r_curr < l_c + r_c) : if (r_curr == r_c or (l_curr != l_c and l_arr[l_curr] < r_arr[r_curr])) : output[in1] = l_arr[l_curr]; l_curr += 1; in1 += 1; else : output[in1] = r_arr[r_curr]; r_curr += 1; in1 += 1; # Code to drive merge-sort and# create recursion treedef divide(l, r, output, arr) : if (l == r) : # base step to initialize the output # array before performing merge # operation for i in range(n) : output[l * n + i] = arr[l][i]; return; # to sort left half divide(l, (l + r) // 2, output, arr); # to sort right half divide((l + r) // 2 + 1, r, output, arr); # merge the left and right half merge(l, r, output); # Driver codeif __name__ == "__main__" : # input 2D-array arr = [[ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ]]; # Number of arrays k = len(arr); # Output array output = [0] * (n * k); divide(0, k - 1, output, arr); # Print merged array for i in range(n * k) : print(output[i], end = " "); # This code is contributed by Ryuga // C# program to merge K sorted arraysusing System; class GFG { static int n = 4; // Function to perform merge operation static void merge(int l, int r, int[] output) { // to store the starting point of left // and right array int l_in = l * n, r_in = ((l + r) / 2 + 1) * n; // to store the size of left and // right array int l_c = ((l + r) / 2 - l + 1) * n; int r_c = (r - (l + r) / 2) * n; // array to temporarily store left // and right array int[] l_arr = new int[l_c]; int[] r_arr = new int[r_c]; // storing data in left array for (int i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data in right array for (int i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array int l_curr = 0, r_curr = 0; // to store the current index // for output array int index = l_in; // two pointer merge for two sorted arrays while (l_curr + r_curr < l_c + r_c) { if (r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) { output[index] = l_arr[l_curr]; l_curr++; index++; } else { output[index] = r_arr[r_curr]; r_curr++; index++; } } } // Code to drive merge-sort and // create recursion tree static void divide(int l, int r, int[] output, int[, ] arr) { if (l == r) { /* base step to initialize the output array before performing merge operation */ for (int i = 0; i < n; i++) output[l * n + i] = arr[l, i]; return; } // to sort left half divide(l, (l + r) / 2, output, arr); // to sort right half divide((l + r) / 2 + 1, r, output, arr); // merge the left and right half merge(l, r, output); } // Driver Code public static void Main(String[] args) { // input 2D-array int[, ] arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; // Number of arrays int k = arr.GetLength(0); // Output array int[] output = new int[n * k]; divide(0, k - 1, output, arr); // Print merged array for (int i = 0; i < n * k; i++) Console.Write(output[i] + " "); }} // This code has been contributed by 29AjayKumar <?php// PHP program to merge K sorted arrays$n = 4; // Function to perform merge operationfunction merge($l, $r, &$output){ global $n; // to store the starting point of left // and right array $l_in = $l * $n; $r_in = ((int)(($l + $r) / 2) + 1) * $n; // to store the size of left and // right array $l_c = (int)(((($l + $r) / 2) - $l + 1) * $n); $r_c = ($r - (int)(($l + $r) / 2)) * $n; // array to temporarily store left // and right array $l_arr = array_fill(0, $l_c, 0); $r_arr = array_fill(0, $r_c, 0); // storing data in left array for ($i = 0; $i < $l_c; $i++) $l_arr[$i] = $output[$l_in + $i]; // storing data in right array for ($i = 0; $i < $r_c; $i++) $r_arr[$i] = $output[$r_in + $i]; // to store the current index of // temporary left and right array $l_curr = 0; $r_curr = 0; // to store the current index // for output array $in = $l_in; // two pointer merge for two sorted arrays while ($l_curr + $r_curr < $l_c + $r_c) { if ($r_curr == $r_c || ($l_curr != $l_c && $l_arr[$l_curr] < $r_arr[$r_curr])) { $output[$in] = $l_arr[$l_curr]; $l_curr++; $in++; } else { $output[$in] = $r_arr[$r_curr]; $r_curr++; $in++; } }} // Code to drive merge-sort and// create recursion treefunction divide($l, $r, &$output, $arr){ global $n; if ($l == $r) { /* base step to initialize the output array before performing merge operation */ for ($i = 0; $i < $n; $i++) $output[$l * $n + $i] = $arr[$l][$i]; return; } // to sort left half divide($l, (int)(($l + $r) / 2), $output, $arr); // to sort right half divide((int)(($l + $r) / 2) + 1, $r, $output, $arr); // merge the left and right half merge($l, $r, $output);} // Driver Code // input 2D-array$arr = array(array( 5, 7, 15, 18 ), array( 1, 8, 9, 17 ), array( 1, 4, 7, 7 )); // Number of arrays$k = count($arr); // Output array$output = array_fill(0, $n * $k, 0); divide(0, $k - 1, $output, $arr); // Print merged arrayfor ($i = 0; $i < $n * $k; $i++) print($output[$i] . " "); // This code is contributed by mits?> <script> // Javascript program to merge K// sorted arraysvar n = 4; // Function to perform merge operationfunction merge(l, r, output){ // To store the starting point // of left and right array var l_in = l * n, r_in = (parseInt((l + r) / 2) + 1) * n; // To store the size of left and // right array var l_c = (parseInt((l + r) / 2) - l + 1) * n; var r_c = (r - parseInt((l + r) / 2)) * n; // array to temporarily store left // and right array var l_arr = Array(l_c), r_arr = Array(r_c); // storing data par left array for(var i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data par right array for(var i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array var l_curr = 0, r_curr = 0; // to store the current index // for output array var par = l_in; // two pointer merge for // two sorted arrays while (l_curr + r_curr < l_c + r_c) { if (r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) { output[par] = l_arr[l_curr]; l_curr++, par++; } else { output[par] = r_arr[r_curr]; r_curr++, par++; } }} // Code to drive merge-sort and// create recursion treefunction divide(l, r, output, arr){ if (l == r) { /* base step to initialize the output array before performing merge operation */ for(var i = 0; i < n; i++) output[l * n + i] = arr[l][i]; return; } // To sort left half divide(l, parseInt((l + r) / 2), output, arr); // To sort right half divide(parseInt((l + r) / 2) + 1, r, output, arr); // Merge the left and right half merge(l, r, output);} // Driver code // Input 2D-arrayvar arr = [ [ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ] ]; // Number of arraysvar k = arr.length; // Output arrayvar output = Array(n * k);divide(0, k - 1, output, arr); // Print merged arrayfor(var i = 0; i < n * k; i++) document.write(output[i] + " "); // This code is contributed by rrrtnx </script> 1 1 4 5 7 7 7 8 9 15 17 18 Complexity Analysis: Time Complexity: O(N*k*log(k)). In each level the array of size N*k is traversed once, and the number of levels are log(k). Space Complexity: O(N*k). To store the output array O(N*k) space is required. We can also solve this problem by using min-heap. DivyanshuShekhar1 ankthon princiraj1992 29AjayKumar Mithun Kumar andrew1234 divyesh072019 divyeshrabadiya07 rutvik_56 mukesh07 rrrtnx surindertarika1234 ashutoshsinghgeeksforgeeks Merge Sort Algorithms Arrays Divide and Conquer Sorting Arrays Divide and Conquer Sorting Merge Sort Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete 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": "\n01 Nov, 2021" }, { "code": null, "e": 146, "s": 52, "text": "Giving k sorted arrays, each of size N, the task is to merge them into a single sorted array." }, { "code": null, "e": 157, "s": 146, "text": "Examples: " }, { "code": null, "e": 393, "s": 157, "text": "Input: arr[][] = {{5, 7, 15, 18},\n {1, 8, 9, 17},\n {1, 4, 7, 7}}\nOutput: {1, 1, 4, 5, 7, 7, 7, 8, 9, 15, 17, 18}\n\nInput: arr[][] = {{3, 2, 1}\n {6, 5, 4}}\nOutput: {1, 2, 3, 4, 5, 6}" }, { "code": null, "e": 515, "s": 393, "text": "Prerequisite: Merge SortSimple Approach: A simple solution is to append all the arrays one after another and sort them. " }, { "code": null, "e": 521, "s": 515, "text": "C++14" }, { "code": null, "e": 526, "s": 521, "text": "Java" }, { "code": null, "e": 534, "s": 526, "text": "Python3" }, { "code": null, "e": 537, "s": 534, "text": "C#" }, { "code": null, "e": 548, "s": 537, "text": "Javascript" }, { "code": "// C++ program to merge K// sorted arrays#include <bits/stdc++.h>using namespace std;#define N 4 // Merge and sort k arraysvoid merge_and_sort( vector<int> &output, vector<vector<int>> arr, int n, int k){ // Put the elements in sorted array. for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { output[(i * n) + j] = arr[i][j]; } } // Sort the output array sort(output.begin(), output.end());} // Driver Functionint main(){ // Input 2D-array vector<vector<int>> arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; int n = N; // Number of arrays int k = arr.size(); // Output array vector<int> output(n*k); merge_and_sort(output, arr, n, k); // Print merged array for (int i = 0; i < n * k; i++) cout << output[i] << \" \"; return 0;}", "e": 1432, "s": 548, "text": null }, { "code": "// Java program to merge K// sorted arraysimport java.util.*;class GFG{ static int N = 4; // Merge and sort k arrays static void merge_and_sort(int output[], int arr[][], int n, int k) { // Put the elements in sorted array. for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { output[i * n + j] = arr[i][j]; } } // Sort the output array Arrays.sort(output); } // Driver code public static void main(String[] args) { // Input 2D-array int arr[][] = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; int n = N; // Number of arrays int k = arr.length; // Output array int output[] = new int[n * k]; merge_and_sort(output, arr, n, k); // Print merged array for (int i = 0; i < n * k; i++) System.out.print(output[i] + \" \"); }} // This code is contributed by divyesh072019", "e": 2533, "s": 1432, "text": null }, { "code": "# Python3 program to merge K# sorted arraysN = 4 # Merge and sort k arraysdef merge_and_sort(output, arr, n, k): # Put the elements in sorted array. for i in range(k): for j in range(n): output[i * n + j] = arr[i][j]; # Sort the output array output.sort() # Driver Functionif __name__=='__main__': # Input 2D-array arr = [ [ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ] ]; n = N; # Number of arrays k = len(arr) # Output array output = [0 for i in range(n * k)] merge_and_sort(output, arr, n, k); # Print merged array for i in range(n * k): print(output[i], end = ' ') # This code is contributed by rutvik_56.", "e": 3265, "s": 2533, "text": null }, { "code": "// C# program to merge K// sorted arraysusing System;class GFG{ static int N = 4; // Merge and sort k arrays static void merge_and_sort(int[] output, int[,] arr, int n, int k) { // Put the elements in sorted array. for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { output[i * n + j] = arr[i,j]; } } // Sort the output array Array.Sort(output); } // Driver code static void Main() { // Input 2D-array int[,] arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; int n = N; // Number of arrays int k = arr.GetLength(0); // Output array int[] output = new int[n * k]; merge_and_sort(output, arr, n, k); // Print merged array for (int i = 0; i < n * k; i++) Console.Write(output[i] + \" \"); }} // This code is contributed by divyeshrabadiya07", "e": 4276, "s": 3265, "text": null }, { "code": "<script> // Javascript program to merge K // sorted arrays let N = 4; // Merge and sort k arrays function merge_and_sort(output, arr, n, k) { // Put the elements in sorted array. for (let i = 0; i < k; i++) { for (let j = 0; j < n; j++) { output[i * n + j] = arr[i][j]; } } // Sort the output array output.sort(function(a, b){return a - b}); } // Input 2D-array let arr = [ [ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ] ]; let n = N; // Number of arrays let k = 3; // Output array let output = new Array(n * k); merge_and_sort(output, arr, n, k); // Print merged array for (let i = 0; i < n * k; i++) document.write(output[i] + \" \"); // This code is contributed by mukesh07.</script>", "e": 5200, "s": 4276, "text": null }, { "code": null, "e": 5227, "s": 5200, "text": "1 1 4 5 7 7 7 8 9 15 17 18" }, { "code": null, "e": 5251, "s": 5229, "text": "Complexity Analysis: " }, { "code": null, "e": 5361, "s": 5251, "text": "Time Complexity: O(N*k*log(N*k)). The size of all elements is n*k so the time complexity is O(N*k * log(N*k))" }, { "code": null, "e": 5439, "s": 5361, "text": "Space Complexity: O(N*k). To store the output array O(N*k) space is required." }, { "code": null, "e": 5895, "s": 5439, "text": "Efficient Solution: Approach: The idea becomes clear once we start looking at the k arrays as the intermediate state of the merge sort algorithm. Since there are k arrays that are already sorted, merge the k arrays. Create a recursive function which will take k arrays and divide them into two parts and call the function recursively with each half. The base cases are when the value of k is less than 3. See this article to merge two arrays in O(n) time." }, { "code": null, "e": 5908, "s": 5895, "text": "Algorithm: " }, { "code": null, "e": 6532, "s": 5908, "text": "Initialize the output array with the size N*k.Call the function divide. Let and represent the range of arrays that are to be merged and thus vary between 0 to k-1.At each step, we call the left and right half of the range recursively so that, they will be sorted and stored in the output array.After that, we merge the left and right half. For merging, we need to determine the range of indexes for the left and right halves in the output array. We can easily find that. Left part will start from the index l * n of the output array.Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array." }, { "code": null, "e": 6579, "s": 6532, "text": "Initialize the output array with the size N*k." }, { "code": null, "e": 6697, "s": 6579, "text": "Call the function divide. Let and represent the range of arrays that are to be merged and thus vary between 0 to k-1." }, { "code": null, "e": 6829, "s": 6697, "text": "At each step, we call the left and right half of the range recursively so that, they will be sorted and stored in the output array." }, { "code": null, "e": 7159, "s": 6829, "text": "After that, we merge the left and right half. For merging, we need to determine the range of indexes for the left and right halves in the output array. We can easily find that. Left part will start from the index l * n of the output array.Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array." }, { "code": null, "e": 7312, "s": 7159, "text": "Left part will start from the index l * n of the output array.Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array." }, { "code": null, "e": 7375, "s": 7312, "text": "Left part will start from the index l * n of the output array." }, { "code": null, "e": 7466, "s": 7375, "text": "Similarly, right part will start from the index ((l + r) / 2 + 1) * n of the output array." }, { "code": null, "e": 7470, "s": 7466, "text": "C++" }, { "code": null, "e": 7475, "s": 7470, "text": "Java" }, { "code": null, "e": 7483, "s": 7475, "text": "Python3" }, { "code": null, "e": 7486, "s": 7483, "text": "C#" }, { "code": null, "e": 7490, "s": 7486, "text": "PHP" }, { "code": null, "e": 7501, "s": 7490, "text": "Javascript" }, { "code": "// C++ program to merge K// sorted arrays #include<bits/stdc++.h>#define n 4 using namespace std; // Function to perform merge operationvoid merge(int l, int r, vector<int>& output){ // to store the starting point // of left and right array int l_in = l * n, r_in = ((l + r) / 2 + 1) * n; // To store the size of left and // right array int l_c = ((l + r) / 2 - l + 1) * n; int r_c = (r - (l + r) / 2) * n; // array to temporarily store left // and right array int l_arr[l_c], r_arr[r_c]; // storing data in left array for (int i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data in right array for (int i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array int l_curr = 0, r_curr = 0; // to store the current index // for output array int in = l_in; // two pointer merge for // two sorted arrays while ( l_curr + r_curr < l_c + r_c) { if ( r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) output[in] = l_arr[l_curr], l_curr++, in++; else output[in] = r_arr[r_curr], r_curr++, in++; }} // Code to drive merge-sort and// create recursion treevoid divide(int l, int r, vector<int>& output, vector<vector<int>> arr){ if (l == r) { /* base step to initialize the output array before performing merge operation */ for (int i = 0; i < n; i++) output[l * n + i] = arr[l][i]; return; } // To sort left half divide(l, (l + r) / 2, output, arr); // To sort right half divide((l + r) / 2 + 1, r, output, arr); // Merge the left and right half merge(l, r, output);} // Driver Functionint main(){ // input 2D-array vector<vector<int>> arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; // Number of arrays int k = arr.size(); // Output array vector<int> output(n*k); divide(0, k - 1, output, arr); // Print merged array for (int i = 0; i < n * k; i++) cout << output[i] << \" \"; return 0;}", "e": 9830, "s": 7501, "text": null }, { "code": "// Java program to merge// K sorted arraysimport java.util.*; class GFG { static int n = 4; // Function to perform // merge operation static void merge( int l, int r, int[] output) { // To store the starting point // of left and right array int l_in = l * n, r_in = ((l + r) / 2 + 1) * n; // to store the size of left and // right array int l_c = ((l + r) / 2 - l + 1) * n; int r_c = (r - (l + r) / 2) * n; // array to temporarily store left // and right array int l_arr[] = new int[l_c], r_arr[] = new int[r_c]; // storing data in left array for (int i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data in right array for (int i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array int l_curr = 0, r_curr = 0; // to store the current index // for output array int in = l_in; // two pointer merge for two sorted arrays while (l_curr + r_curr < l_c + r_c) { if ( r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) { output[in] = l_arr[l_curr]; l_curr++; in++; } else { output[in] = r_arr[r_curr]; r_curr++; in++; } } } // Code to drive merge-sort and // create recursion tree static void divide(int l, int r, int[] output, int arr[][]) { if (l == r) { /* base step to initialize the output array before performing merge operation */ for (int i = 0; i < n; i++) output[l * n + i] = arr[l][i]; return; } // to sort left half divide(l, (l + r) / 2, output, arr); // to sort right half divide((l + r) / 2 + 1, r, output, arr); // merge the left and right half merge(l, r, output); } // Driver Code public static void main(String[] args) { // input 2D-array int arr[][] = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; // Number of arrays int k = arr.length; // Output array int[] output = new int[n * k]; divide(0, k - 1, output, arr); // Print merged array for (int i = 0; i < n * k; i++) System.out.print(output[i] + \" \"); }} /* This code contributed by PrinciRaj1992 */", "e": 12532, "s": 9830, "text": null }, { "code": "# Python3 program to merge K sorted arraysn = 4 ; # Function to perform merge operationdef merge(l, r, output) : # to store the starting point of # left and right array l_in = l * n ; r_in = ((l + r) // 2 + 1) * n; # to store the size of left and # right array l_c = ((l + r) // 2 - l + 1) * n; r_c = (r - (l + r) // 2) * n; # array to temporarily store left # and right array l_arr = [0] * l_c; r_arr = [0] * r_c; # storing data in left array for i in range(l_c) : l_arr[i] = output[l_in + i]; # storing data in right array for i in range(r_c) : r_arr[i] = output[r_in + i]; # to store the current index of # temporary left and right array l_curr = 0 ; r_curr = 0; # to store the current index # for output array in1 = l_in; # two pointer merge for two sorted arrays while (l_curr + r_curr < l_c + r_c) : if (r_curr == r_c or (l_curr != l_c and l_arr[l_curr] < r_arr[r_curr])) : output[in1] = l_arr[l_curr]; l_curr += 1; in1 += 1; else : output[in1] = r_arr[r_curr]; r_curr += 1; in1 += 1; # Code to drive merge-sort and# create recursion treedef divide(l, r, output, arr) : if (l == r) : # base step to initialize the output # array before performing merge # operation for i in range(n) : output[l * n + i] = arr[l][i]; return; # to sort left half divide(l, (l + r) // 2, output, arr); # to sort right half divide((l + r) // 2 + 1, r, output, arr); # merge the left and right half merge(l, r, output); # Driver codeif __name__ == \"__main__\" : # input 2D-array arr = [[ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ]]; # Number of arrays k = len(arr); # Output array output = [0] * (n * k); divide(0, k - 1, output, arr); # Print merged array for i in range(n * k) : print(output[i], end = \" \"); # This code is contributed by Ryuga", "e": 14586, "s": 12532, "text": null }, { "code": "// C# program to merge K sorted arraysusing System; class GFG { static int n = 4; // Function to perform merge operation static void merge(int l, int r, int[] output) { // to store the starting point of left // and right array int l_in = l * n, r_in = ((l + r) / 2 + 1) * n; // to store the size of left and // right array int l_c = ((l + r) / 2 - l + 1) * n; int r_c = (r - (l + r) / 2) * n; // array to temporarily store left // and right array int[] l_arr = new int[l_c]; int[] r_arr = new int[r_c]; // storing data in left array for (int i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data in right array for (int i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array int l_curr = 0, r_curr = 0; // to store the current index // for output array int index = l_in; // two pointer merge for two sorted arrays while (l_curr + r_curr < l_c + r_c) { if (r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) { output[index] = l_arr[l_curr]; l_curr++; index++; } else { output[index] = r_arr[r_curr]; r_curr++; index++; } } } // Code to drive merge-sort and // create recursion tree static void divide(int l, int r, int[] output, int[, ] arr) { if (l == r) { /* base step to initialize the output array before performing merge operation */ for (int i = 0; i < n; i++) output[l * n + i] = arr[l, i]; return; } // to sort left half divide(l, (l + r) / 2, output, arr); // to sort right half divide((l + r) / 2 + 1, r, output, arr); // merge the left and right half merge(l, r, output); } // Driver Code public static void Main(String[] args) { // input 2D-array int[, ] arr = { { 5, 7, 15, 18 }, { 1, 8, 9, 17 }, { 1, 4, 7, 7 } }; // Number of arrays int k = arr.GetLength(0); // Output array int[] output = new int[n * k]; divide(0, k - 1, output, arr); // Print merged array for (int i = 0; i < n * k; i++) Console.Write(output[i] + \" \"); }} // This code has been contributed by 29AjayKumar", "e": 17211, "s": 14586, "text": null }, { "code": "<?php// PHP program to merge K sorted arrays$n = 4; // Function to perform merge operationfunction merge($l, $r, &$output){ global $n; // to store the starting point of left // and right array $l_in = $l * $n; $r_in = ((int)(($l + $r) / 2) + 1) * $n; // to store the size of left and // right array $l_c = (int)(((($l + $r) / 2) - $l + 1) * $n); $r_c = ($r - (int)(($l + $r) / 2)) * $n; // array to temporarily store left // and right array $l_arr = array_fill(0, $l_c, 0); $r_arr = array_fill(0, $r_c, 0); // storing data in left array for ($i = 0; $i < $l_c; $i++) $l_arr[$i] = $output[$l_in + $i]; // storing data in right array for ($i = 0; $i < $r_c; $i++) $r_arr[$i] = $output[$r_in + $i]; // to store the current index of // temporary left and right array $l_curr = 0; $r_curr = 0; // to store the current index // for output array $in = $l_in; // two pointer merge for two sorted arrays while ($l_curr + $r_curr < $l_c + $r_c) { if ($r_curr == $r_c || ($l_curr != $l_c && $l_arr[$l_curr] < $r_arr[$r_curr])) { $output[$in] = $l_arr[$l_curr]; $l_curr++; $in++; } else { $output[$in] = $r_arr[$r_curr]; $r_curr++; $in++; } }} // Code to drive merge-sort and// create recursion treefunction divide($l, $r, &$output, $arr){ global $n; if ($l == $r) { /* base step to initialize the output array before performing merge operation */ for ($i = 0; $i < $n; $i++) $output[$l * $n + $i] = $arr[$l][$i]; return; } // to sort left half divide($l, (int)(($l + $r) / 2), $output, $arr); // to sort right half divide((int)(($l + $r) / 2) + 1, $r, $output, $arr); // merge the left and right half merge($l, $r, $output);} // Driver Code // input 2D-array$arr = array(array( 5, 7, 15, 18 ), array( 1, 8, 9, 17 ), array( 1, 4, 7, 7 )); // Number of arrays$k = count($arr); // Output array$output = array_fill(0, $n * $k, 0); divide(0, $k - 1, $output, $arr); // Print merged arrayfor ($i = 0; $i < $n * $k; $i++) print($output[$i] . \" \"); // This code is contributed by mits?>", "e": 19506, "s": 17211, "text": null }, { "code": "<script> // Javascript program to merge K// sorted arraysvar n = 4; // Function to perform merge operationfunction merge(l, r, output){ // To store the starting point // of left and right array var l_in = l * n, r_in = (parseInt((l + r) / 2) + 1) * n; // To store the size of left and // right array var l_c = (parseInt((l + r) / 2) - l + 1) * n; var r_c = (r - parseInt((l + r) / 2)) * n; // array to temporarily store left // and right array var l_arr = Array(l_c), r_arr = Array(r_c); // storing data par left array for(var i = 0; i < l_c; i++) l_arr[i] = output[l_in + i]; // storing data par right array for(var i = 0; i < r_c; i++) r_arr[i] = output[r_in + i]; // to store the current index of // temporary left and right array var l_curr = 0, r_curr = 0; // to store the current index // for output array var par = l_in; // two pointer merge for // two sorted arrays while (l_curr + r_curr < l_c + r_c) { if (r_curr == r_c || (l_curr != l_c && l_arr[l_curr] < r_arr[r_curr])) { output[par] = l_arr[l_curr]; l_curr++, par++; } else { output[par] = r_arr[r_curr]; r_curr++, par++; } }} // Code to drive merge-sort and// create recursion treefunction divide(l, r, output, arr){ if (l == r) { /* base step to initialize the output array before performing merge operation */ for(var i = 0; i < n; i++) output[l * n + i] = arr[l][i]; return; } // To sort left half divide(l, parseInt((l + r) / 2), output, arr); // To sort right half divide(parseInt((l + r) / 2) + 1, r, output, arr); // Merge the left and right half merge(l, r, output);} // Driver code // Input 2D-arrayvar arr = [ [ 5, 7, 15, 18 ], [ 1, 8, 9, 17 ], [ 1, 4, 7, 7 ] ]; // Number of arraysvar k = arr.length; // Output arrayvar output = Array(n * k);divide(0, k - 1, output, arr); // Print merged arrayfor(var i = 0; i < n * k; i++) document.write(output[i] + \" \"); // This code is contributed by rrrtnx </script>", "e": 21759, "s": 19506, "text": null }, { "code": null, "e": 21786, "s": 21759, "text": "1 1 4 5 7 7 7 8 9 15 17 18" }, { "code": null, "e": 21810, "s": 21788, "text": "Complexity Analysis: " }, { "code": null, "e": 21934, "s": 21810, "text": "Time Complexity: O(N*k*log(k)). In each level the array of size N*k is traversed once, and the number of levels are log(k)." }, { "code": null, "e": 22012, "s": 21934, "text": "Space Complexity: O(N*k). To store the output array O(N*k) space is required." }, { "code": null, "e": 22063, "s": 22012, "text": "We can also solve this problem by using min-heap. " }, { "code": null, "e": 22081, "s": 22063, "text": "DivyanshuShekhar1" }, { "code": null, "e": 22089, "s": 22081, "text": "ankthon" }, { "code": null, "e": 22103, "s": 22089, "text": "princiraj1992" }, { "code": null, "e": 22115, "s": 22103, "text": "29AjayKumar" }, { "code": null, "e": 22128, "s": 22115, "text": "Mithun Kumar" }, { "code": null, "e": 22139, "s": 22128, "text": "andrew1234" }, { "code": null, "e": 22153, "s": 22139, "text": "divyesh072019" }, { "code": null, "e": 22171, "s": 22153, "text": "divyeshrabadiya07" }, { "code": null, "e": 22181, "s": 22171, "text": "rutvik_56" }, { "code": null, "e": 22190, "s": 22181, "text": "mukesh07" }, { "code": null, "e": 22197, "s": 22190, "text": "rrrtnx" }, { "code": null, "e": 22216, "s": 22197, "text": "surindertarika1234" }, { "code": null, "e": 22243, "s": 22216, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 22254, "s": 22243, "text": "Merge Sort" }, { "code": null, "e": 22265, "s": 22254, "text": "Algorithms" }, { "code": null, "e": 22272, "s": 22265, "text": "Arrays" }, { "code": null, "e": 22291, "s": 22272, "text": "Divide and Conquer" }, { "code": null, "e": 22299, "s": 22291, "text": "Sorting" }, { "code": null, "e": 22306, "s": 22299, "text": "Arrays" }, { "code": null, "e": 22325, "s": 22306, "text": "Divide and Conquer" }, { "code": null, "e": 22333, "s": 22325, "text": "Sorting" }, { "code": null, "e": 22344, "s": 22333, "text": "Merge Sort" }, { "code": null, "e": 22355, "s": 22344, "text": "Algorithms" }, { "code": null, "e": 22453, "s": 22355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 22491, "s": 22453, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 22559, "s": 22491, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 22586, "s": 22559, "text": "How to Start Learning DSA?" }, { "code": null, "e": 22629, "s": 22586, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 22696, "s": 22629, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 22711, "s": 22696, "text": "Arrays in Java" }, { "code": null, "e": 22757, "s": 22711, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 22825, "s": 22757, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 22857, "s": 22825, "text": "Largest Sum Contiguous Subarray" } ]
Sorting objects using In-Place sorting algorithm
15 Jun, 2022 Given an array of red, blue and yellow objects, the task is to use an in-place sorting algorithm to sort the array in such a way that all the blue objects appear before all the red objects and all the red objects appear before all the yellow objects.Examples: Input: arr[] = {“blue”, “red”, “yellow”, “blue”, “yellow”} Output: blue blue red yellow yellowInput: arr[] = {“red”, “blue”, “red”, “yellow”, “blue”} Output: blue blue red red yellow Approach: First of all map the values of blue, red and yellow objects to 1, 2 and 3 respectively using a hash table. Now use these mapped values whenever a comparison of two objects is required. So, the algorithm will sort the array of objects such that all blue objects ( mapping to value 1 ) will appear first, then all red objects ( mapping to value 2 ) and then all yellow objects ( mapping to value 3 ).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Partition function which will partition// the array and into two partsint partition(vector<string>& objects, int l, int r, unordered_map<string, int>& hash){ int j = l - 1; int last_element = hash[objects[r]]; for (int i = l; i < r; i++) { // Compare hash values of objects if (hash[objects[i]] <= last_element) { j++; swap(objects[i], objects[j]); } } j++; swap(objects[j], objects[r]); return j;} // Classic quicksort algorithmvoid quicksort(vector<string>& objects, int l, int r, unordered_map<string, int>& hash){ if (l < r) { int mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsvoid sortObj(vector<string>& objects){ // Create a hash table unordered_map<string, int> hash; // As the sorting order is blue objects, // red objects and then yellow objects hash["blue"] = 1; hash["red"] = 2; hash["yellow"] = 3; // Quick sort function quicksort(objects, 0, int(objects.size() - 1), hash); // Printing the sorted array for (int i = 0; i < objects.size(); i++) cout << objects[i] << " ";} // Driver codeint main(){ // Let's represent objects as strings vector<string> objects{ "red", "blue", "red", "yellow", "blue" }; sortObj(objects); return 0;} // Java implementation of the approachimport java.util.*;class GFG{ // Partition function which will partition// the array and into two partsstatic int partition(Vector<String> objects, int l, int r, Map<String, Integer> hash){ int j = l - 1; int last_element = hash.get(objects.get(r)); for (int i = l; i < r; i++) { // Compare hash values of objects if (hash.get(objects.get(i)) <= last_element) { j++; Collections.swap(objects, i, j); } } j++; Collections.swap(objects, j, r); return j;} // Classic quicksort algorithmstatic void quicksort(Vector<String> objects, int l, int r, Map<String, Integer> hash){ if (l < r) { int mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsstatic void sortObj(Vector<String> objects){ // Create a hash table Map<String, Integer> hash = new HashMap<>(); // As the sorting order is blue objects, // red objects and then yellow objects hash. put("blue", 1); hash. put("red", 2); hash. put("yellow", 3); // Quick sort function quicksort(objects, 0, objects.size() - 1, hash); // Printing the sorted array for (int i = 0; i < objects.size(); i++) System.out.print(objects.get(i) + " ");} // Driver codepublic static void main(String []args){ // Let's represent objects as strings Vector<String> objects = new Vector<>(Arrays.asList( "red", "blue", "red", "yellow", "blue" )); sortObj(objects);}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approach # Partition function which will partition# the array and into two partsobjects = []hash = dict() def partition(l, r): global objects, hash j = l - 1 last_element = hash[objects[r]] for i in range(l, r): # Compare hash values of objects if (hash[objects[i]] <= last_element): j += 1 (objects[i], objects[j]) = (objects[j], objects[i]) j += 1 (objects[j], objects[r]) = (objects[r], objects[j]) return j # Classic quicksort algorithmdef quicksort(l, r): if (l < r): mid = partition(l, r) quicksort(l, mid - 1) quicksort(mid + 1, r) # Function to sort and print the objectsdef sortObj(): global objects, hash # As the sorting order is blue objects, # red objects and then yellow objects hash["blue"] = 1 hash["red"] = 2 hash["yellow"] = 3 # Quick sort function quicksort(0, int(len(objects) - 1)) # Printing the sorted array for i in objects: print(i, end = " ") # Driver code # Let's represent objects as stringsobjects = ["red", "blue", "red", "yellow", "blue"] sortObj() # This code is contributed# by Mohit Kumar // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Partition function which will partition// the array and into two partsstatic int partition(List<String> objects, int l, int r, Dictionary<String, int> hash){ int j = l - 1; String temp; int last_element = hash[objects[r]]; for (int i = l; i < r; i++) { // Compare hash values of objects if (hash[objects[i]] <= last_element) { j++; temp = objects[i]; objects[i] = objects[j]; objects[j] = temp; } } j++; temp = objects[r]; objects[r] = objects[j]; objects[j] = temp; return j;} // Classic quicksort algorithmstatic void quicksort(List<String> objects, int l, int r, Dictionary<String, int> hash){ if (l < r) { int mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsstatic void sortObj(List<String> objects){ // Create a hash table Dictionary<String, int> hash = new Dictionary<String, int>(); // As the sorting order is blue objects, // red objects and then yellow objects hash.Add("blue", 1); hash.Add("red", 2); hash.Add("yellow", 3); // Quick sort function quicksort(objects, 0, objects.Count - 1, hash); // Printing the sorted array for (int i = 0; i < objects.Count; i++) Console.Write(objects[i] + " ");} // Driver codepublic static void Main(String []args){ // Let's represent objects as strings List<String> objects = new List<String>{"red", "blue", "red", "yellow", "blue"}; sortObj(objects);}} // This code is contributed by Rajput-Ji <script>// Javascript implementation of the approach // Partition function which will partition// the array and into two partsfunction partition(objects, l, r, hash){ let j = l - 1; let last_element = hash.get(objects[r]); for (let i = l; i < r; i++) { // Compare hash values of objects if (hash.get(objects[i]) <= last_element) { j++; let temp = objects[i]; objects[i] = objects[j]; objects[j] = temp; } } j++; let temp = objects[r]; objects[r] = objects[j]; objects[j] = temp; return j;} // Classic quicksort algorithmfunction quicksort(objects, l, r, hash){ if (l < r) { let mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsfunction sortObj(objects){ // Create a hash table let hash = new Map(); // As the sorting order is blue objects, // red objects and then yellow objects hash. set("blue", 1); hash. set("red", 2); hash. set("yellow", 3); // Quick sort function quicksort(objects, 0, objects.length - 1, hash); // Printing the sorted array for (let i = 0; i < objects.length; i++) document.write(objects[i] + " ");} // Driver codelet objects = ["red", "blue","red", "yellow", "blue"];sortObj(objects); // This code is contributed by patel2127</script> blue blue red red yellow Time complexity: O(n^2) since using qucksort princiraj1992 Rajput-Ji mohit kumar 29 Code_Mech patel2127 polymatir3j Quick Sort Algorithms Competitive Programming Sorting Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jun, 2022" }, { "code": null, "e": 290, "s": 28, "text": "Given an array of red, blue and yellow objects, the task is to use an in-place sorting algorithm to sort the array in such a way that all the blue objects appear before all the red objects and all the red objects appear before all the yellow objects.Examples: " }, { "code": null, "e": 475, "s": 290, "text": "Input: arr[] = {“blue”, “red”, “yellow”, “blue”, “yellow”} Output: blue blue red yellow yellowInput: arr[] = {“red”, “blue”, “red”, “yellow”, “blue”} Output: blue blue red red yellow " }, { "code": null, "e": 938, "s": 477, "text": "Approach: First of all map the values of blue, red and yellow objects to 1, 2 and 3 respectively using a hash table. Now use these mapped values whenever a comparison of two objects is required. So, the algorithm will sort the array of objects such that all blue objects ( mapping to value 1 ) will appear first, then all red objects ( mapping to value 2 ) and then all yellow objects ( mapping to value 3 ).Below is the implementation of the above approach: " }, { "code": null, "e": 942, "s": 938, "text": "C++" }, { "code": null, "e": 947, "s": 942, "text": "Java" }, { "code": null, "e": 955, "s": 947, "text": "Python3" }, { "code": null, "e": 958, "s": 955, "text": "C#" }, { "code": null, "e": 969, "s": 958, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Partition function which will partition// the array and into two partsint partition(vector<string>& objects, int l, int r, unordered_map<string, int>& hash){ int j = l - 1; int last_element = hash[objects[r]]; for (int i = l; i < r; i++) { // Compare hash values of objects if (hash[objects[i]] <= last_element) { j++; swap(objects[i], objects[j]); } } j++; swap(objects[j], objects[r]); return j;} // Classic quicksort algorithmvoid quicksort(vector<string>& objects, int l, int r, unordered_map<string, int>& hash){ if (l < r) { int mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsvoid sortObj(vector<string>& objects){ // Create a hash table unordered_map<string, int> hash; // As the sorting order is blue objects, // red objects and then yellow objects hash[\"blue\"] = 1; hash[\"red\"] = 2; hash[\"yellow\"] = 3; // Quick sort function quicksort(objects, 0, int(objects.size() - 1), hash); // Printing the sorted array for (int i = 0; i < objects.size(); i++) cout << objects[i] << \" \";} // Driver codeint main(){ // Let's represent objects as strings vector<string> objects{ \"red\", \"blue\", \"red\", \"yellow\", \"blue\" }; sortObj(objects); return 0;}", "e": 2524, "s": 969, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{ // Partition function which will partition// the array and into two partsstatic int partition(Vector<String> objects, int l, int r, Map<String, Integer> hash){ int j = l - 1; int last_element = hash.get(objects.get(r)); for (int i = l; i < r; i++) { // Compare hash values of objects if (hash.get(objects.get(i)) <= last_element) { j++; Collections.swap(objects, i, j); } } j++; Collections.swap(objects, j, r); return j;} // Classic quicksort algorithmstatic void quicksort(Vector<String> objects, int l, int r, Map<String, Integer> hash){ if (l < r) { int mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsstatic void sortObj(Vector<String> objects){ // Create a hash table Map<String, Integer> hash = new HashMap<>(); // As the sorting order is blue objects, // red objects and then yellow objects hash. put(\"blue\", 1); hash. put(\"red\", 2); hash. put(\"yellow\", 3); // Quick sort function quicksort(objects, 0, objects.size() - 1, hash); // Printing the sorted array for (int i = 0; i < objects.size(); i++) System.out.print(objects.get(i) + \" \");} // Driver codepublic static void main(String []args){ // Let's represent objects as strings Vector<String> objects = new Vector<>(Arrays.asList( \"red\", \"blue\", \"red\", \"yellow\", \"blue\" )); sortObj(objects);}} // This code is contributed by PrinciRaj1992", "e": 4327, "s": 2524, "text": null }, { "code": "# Python3 implementation of the approach # Partition function which will partition# the array and into two partsobjects = []hash = dict() def partition(l, r): global objects, hash j = l - 1 last_element = hash[objects[r]] for i in range(l, r): # Compare hash values of objects if (hash[objects[i]] <= last_element): j += 1 (objects[i], objects[j]) = (objects[j], objects[i]) j += 1 (objects[j], objects[r]) = (objects[r], objects[j]) return j # Classic quicksort algorithmdef quicksort(l, r): if (l < r): mid = partition(l, r) quicksort(l, mid - 1) quicksort(mid + 1, r) # Function to sort and print the objectsdef sortObj(): global objects, hash # As the sorting order is blue objects, # red objects and then yellow objects hash[\"blue\"] = 1 hash[\"red\"] = 2 hash[\"yellow\"] = 3 # Quick sort function quicksort(0, int(len(objects) - 1)) # Printing the sorted array for i in objects: print(i, end = \" \") # Driver code # Let's represent objects as stringsobjects = [\"red\", \"blue\", \"red\", \"yellow\", \"blue\"] sortObj() # This code is contributed# by Mohit Kumar", "e": 5585, "s": 4327, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Partition function which will partition// the array and into two partsstatic int partition(List<String> objects, int l, int r, Dictionary<String, int> hash){ int j = l - 1; String temp; int last_element = hash[objects[r]]; for (int i = l; i < r; i++) { // Compare hash values of objects if (hash[objects[i]] <= last_element) { j++; temp = objects[i]; objects[i] = objects[j]; objects[j] = temp; } } j++; temp = objects[r]; objects[r] = objects[j]; objects[j] = temp; return j;} // Classic quicksort algorithmstatic void quicksort(List<String> objects, int l, int r, Dictionary<String, int> hash){ if (l < r) { int mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsstatic void sortObj(List<String> objects){ // Create a hash table Dictionary<String, int> hash = new Dictionary<String, int>(); // As the sorting order is blue objects, // red objects and then yellow objects hash.Add(\"blue\", 1); hash.Add(\"red\", 2); hash.Add(\"yellow\", 3); // Quick sort function quicksort(objects, 0, objects.Count - 1, hash); // Printing the sorted array for (int i = 0; i < objects.Count; i++) Console.Write(objects[i] + \" \");} // Driver codepublic static void Main(String []args){ // Let's represent objects as strings List<String> objects = new List<String>{\"red\", \"blue\", \"red\", \"yellow\", \"blue\"}; sortObj(objects);}} // This code is contributed by Rajput-Ji", "e": 7522, "s": 5585, "text": null }, { "code": "<script>// Javascript implementation of the approach // Partition function which will partition// the array and into two partsfunction partition(objects, l, r, hash){ let j = l - 1; let last_element = hash.get(objects[r]); for (let i = l; i < r; i++) { // Compare hash values of objects if (hash.get(objects[i]) <= last_element) { j++; let temp = objects[i]; objects[i] = objects[j]; objects[j] = temp; } } j++; let temp = objects[r]; objects[r] = objects[j]; objects[j] = temp; return j;} // Classic quicksort algorithmfunction quicksort(objects, l, r, hash){ if (l < r) { let mid = partition(objects, l, r, hash); quicksort(objects, l, mid - 1, hash); quicksort(objects, mid + 1, r, hash); }} // Function to sort and print the objectsfunction sortObj(objects){ // Create a hash table let hash = new Map(); // As the sorting order is blue objects, // red objects and then yellow objects hash. set(\"blue\", 1); hash. set(\"red\", 2); hash. set(\"yellow\", 3); // Quick sort function quicksort(objects, 0, objects.length - 1, hash); // Printing the sorted array for (let i = 0; i < objects.length; i++) document.write(objects[i] + \" \");} // Driver codelet objects = [\"red\", \"blue\",\"red\", \"yellow\", \"blue\"];sortObj(objects); // This code is contributed by patel2127</script>", "e": 9006, "s": 7522, "text": null }, { "code": null, "e": 9031, "s": 9006, "text": "blue blue red red yellow" }, { "code": null, "e": 9078, "s": 9033, "text": "Time complexity: O(n^2) since using qucksort" }, { "code": null, "e": 9092, "s": 9078, "text": "princiraj1992" }, { "code": null, "e": 9102, "s": 9092, "text": "Rajput-Ji" }, { "code": null, "e": 9117, "s": 9102, "text": "mohit kumar 29" }, { "code": null, "e": 9127, "s": 9117, "text": "Code_Mech" }, { "code": null, "e": 9137, "s": 9127, "text": "patel2127" }, { "code": null, "e": 9149, "s": 9137, "text": "polymatir3j" }, { "code": null, "e": 9160, "s": 9149, "text": "Quick Sort" }, { "code": null, "e": 9171, "s": 9160, "text": "Algorithms" }, { "code": null, "e": 9195, "s": 9171, "text": "Competitive Programming" }, { "code": null, "e": 9203, "s": 9195, "text": "Sorting" }, { "code": null, "e": 9211, "s": 9203, "text": "Sorting" }, { "code": null, "e": 9222, "s": 9211, "text": "Algorithms" } ]
Python | Convert list of strings and characters to list of characters
23 Jan, 2019 Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Let’s discuss certain ways in which this is achieved. Method #1 : Using List comprehensionIn this method, we just consider each list element as string and iterate their each character and append each character to the newly created target list. # Python3 code to demonstrate # to convert list of string and characters# to list of characters# using list comprehension # initializing list test_list = [ 'gfg', 'i', 's', 'be', 's', 't'] # printing original listprint ("The original list is : " + str(test_list)) # using list comprehension# to convert list of string and characters# to list of charactersres = [i for ele in test_list for i in ele] # printing result print ("The list after conversion is : " + str(res)) The original list is : ['gfg', 'i', 's', 'be', 's', 't'] The list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't'] Method #2 : Using join() join function can be used to open the string and then join each letter with empty string resulting in a single character extraction. The end result has to be type casted to list for desired result. # Python3 code to demonstrate # to convert list of string and characters# to list of characters# using join() # initializing list test_list = [ 'gfg', 'i', 's', 'be', 's', 't'] # printing original listprint ("The original list is : " + str(test_list)) # using join()# to convert list of string and characters# to list of charactersres = list(''.join(test_list)) # printing result print ("The list after conversion is : " + str(res)) The original list is : ['gfg', 'i', 's', 'be', 's', 't'] The list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't'] Method #3 : Using chain.from_iterable() from_iterable function performs the similar task of firstly opening each string and then joining the characters one by one. This is the most pythonic way to perform this particular task. # Python3 code to demonstrate # to convert list of string and characters# to list of characters# using chain.from_iterable()from itertools import chain # initializing list test_list = [ 'gfg', 'i', 's', 'be', 's', 't'] # printing original listprint ("The original list is : " + str(test_list)) # using chain.from_iterable()# to convert list of string and characters# to list of charactersres = list(chain.from_iterable(test_list)) # printing result print ("The list after conversion is : " + str(res)) The original list is : ['gfg', 'i', 's', 'be', 's', 't'] The list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't'] Python list-programs python-string Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2019" }, { "code": null, "e": 303, "s": 28, "text": "Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Let’s discuss certain ways in which this is achieved." }, { "code": null, "e": 493, "s": 303, "text": "Method #1 : Using List comprehensionIn this method, we just consider each list element as string and iterate their each character and append each character to the newly created target list." }, { "code": "# Python3 code to demonstrate # to convert list of string and characters# to list of characters# using list comprehension # initializing list test_list = [ 'gfg', 'i', 's', 'be', 's', 't'] # printing original listprint (\"The original list is : \" + str(test_list)) # using list comprehension# to convert list of string and characters# to list of charactersres = [i for ele in test_list for i in ele] # printing result print (\"The list after conversion is : \" + str(res))", "e": 969, "s": 493, "text": null }, { "code": null, "e": 1104, "s": 969, "text": "The original list is : ['gfg', 'i', 's', 'be', 's', 't']\nThe list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']\n" }, { "code": null, "e": 1130, "s": 1104, "text": " Method #2 : Using join()" }, { "code": null, "e": 1328, "s": 1130, "text": "join function can be used to open the string and then join each letter with empty string resulting in a single character extraction. The end result has to be type casted to list for desired result." }, { "code": "# Python3 code to demonstrate # to convert list of string and characters# to list of characters# using join() # initializing list test_list = [ 'gfg', 'i', 's', 'be', 's', 't'] # printing original listprint (\"The original list is : \" + str(test_list)) # using join()# to convert list of string and characters# to list of charactersres = list(''.join(test_list)) # printing result print (\"The list after conversion is : \" + str(res))", "e": 1767, "s": 1328, "text": null }, { "code": null, "e": 1902, "s": 1767, "text": "The original list is : ['gfg', 'i', 's', 'be', 's', 't']\nThe list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']\n" }, { "code": null, "e": 1943, "s": 1902, "text": " Method #3 : Using chain.from_iterable()" }, { "code": null, "e": 2130, "s": 1943, "text": "from_iterable function performs the similar task of firstly opening each string and then joining the characters one by one. This is the most pythonic way to perform this particular task." }, { "code": "# Python3 code to demonstrate # to convert list of string and characters# to list of characters# using chain.from_iterable()from itertools import chain # initializing list test_list = [ 'gfg', 'i', 's', 'be', 's', 't'] # printing original listprint (\"The original list is : \" + str(test_list)) # using chain.from_iterable()# to convert list of string and characters# to list of charactersres = list(chain.from_iterable(test_list)) # printing result print (\"The list after conversion is : \" + str(res))", "e": 2638, "s": 2130, "text": null }, { "code": null, "e": 2773, "s": 2638, "text": "The original list is : ['gfg', 'i', 's', 'be', 's', 't']\nThe list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']\n" }, { "code": null, "e": 2794, "s": 2773, "text": "Python list-programs" }, { "code": null, "e": 2808, "s": 2794, "text": "python-string" }, { "code": null, "e": 2815, "s": 2808, "text": "Python" }, { "code": null, "e": 2831, "s": 2815, "text": "Python Programs" }, { "code": null, "e": 2929, "s": 2831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2961, "s": 2929, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2988, "s": 2961, "text": "Python Classes and Objects" }, { "code": null, "e": 3009, "s": 2988, "text": "Python OOPs Concepts" }, { "code": null, "e": 3032, "s": 3009, "text": "Introduction To PYTHON" }, { "code": null, "e": 3088, "s": 3032, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3110, "s": 3088, "text": "Defaultdict in Python" }, { "code": null, "e": 3149, "s": 3110, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3187, "s": 3149, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3224, "s": 3187, "text": "Python Program for Fibonacci numbers" } ]
How to share a captured Image to another App in Android
04 Mar, 2020 Pre-requisite: How to open Camera through Intent and capture an image In this article, we will try to send the captured image (from this article) to other apps using Android Studio. Approach: The image captured gets stored on the external storage. Hence we need to request permission to access the files from the user. So take permission to access external storage permission in the manifest file.Here pictureDir(File) is pointing to the directory of external storage named DIRECTORY_PICTURESFile pictureDir = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "CameraDemo"); In onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code belowif(!pictureDir.exists()){ pictureDir.mkdirs(); } Create another method called callCameraApp() to get the clicked image from external storage.Capture the image using IntentCreate a file to store the image in the pictureDir directory.Get the URI object of this image filePut the image on the Intent storage to be accessed from other modules of the app.Pass the image through intent to startActivityForResult()Share this image to other app using intent.Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); For the sake of this article, we will be selecting Gmail and will be sending this image as an attachment in a mail.startActivity(Intent.createChooser(emailIntent, "Send mail...")); The image captured gets stored on the external storage. Hence we need to request permission to access the files from the user. So take permission to access external storage permission in the manifest file. Here pictureDir(File) is pointing to the directory of external storage named DIRECTORY_PICTURESFile pictureDir = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "CameraDemo"); File pictureDir = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "CameraDemo"); In onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code belowif(!pictureDir.exists()){ pictureDir.mkdirs(); } if(!pictureDir.exists()){ pictureDir.mkdirs(); } Create another method called callCameraApp() to get the clicked image from external storage.Capture the image using IntentCreate a file to store the image in the pictureDir directory.Get the URI object of this image filePut the image on the Intent storage to be accessed from other modules of the app.Pass the image through intent to startActivityForResult() Capture the image using Intent Create a file to store the image in the pictureDir directory. Get the URI object of this image file Put the image on the Intent storage to be accessed from other modules of the app. Pass the image through intent to startActivityForResult() Share this image to other app using intent.Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); For the sake of this article, we will be selecting Gmail and will be sending this image as an attachment in a mail.startActivity(Intent.createChooser(emailIntent, "Send mail...")); startActivity(Intent.createChooser(emailIntent, "Send mail...")); Below is the complete implementation of the above approach: activity_main.xml MainActivity.java AndroidManifest.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"> <!--Textview with title "Camera_Demo!" is given by --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Camera Demo!" android:id="@+id/tv" android:textSize="20sp" android:textStyle="bold" android:layout_centerHorizontal="true" /> <!-- Add button to take a picture--> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/tv" android:layout_marginTop="50dp" android:text="Take Picture" android:textSize="20sp" android:textStyle="bold" /> <!-- Add ImageView to display the captured image--> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageView1" android:layout_below="@id/button1" /></RelativeLayout> package com.example.camera_mail; import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Environment;import android.provider.MediaStore;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import java.io.File; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final int CAMERA_PIC_REQUEST = 1337; private static final int REQUEST_EXTERNAL_STORAGE_RESULT = 1; private static final String FILE_NAME = "image01.jpg"; private Button b1; private ImageView img1; File pictureDir = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "CameraDemo"); private Uri fileUri; // The onCreate() method @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button)findViewById(R.id.button1); img1 = (ImageView)findViewById(R.id.imageView1); b1.setOnClickListener(this); if (!pictureDir.exists()) { pictureDir.mkdirs(); } } // Open the camera app to capture the image public void callCameraApp() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = new File(pictureDir, FILE_NAME); fileUri = Uri.fromFile(image); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(intent, CAMERA_PIC_REQUEST); } public void onClick(View arg0) { if ( ContextCompat.checkSelfPermission( this, Manifest .permission .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { callCameraApp(); } else { if ( ActivityCompat .shouldShowRequestPermissionRationale( this, Manifest .permission .WRITE_EXTERNAL_STORAGE)) { Toast.makeText( this, "External storage permission" + " required to save images", Toast.LENGTH_SHORT) .show(); } ActivityCompat .requestPermissions( this, new String[] { Manifest .permission .WRITE_EXTERNAL_STORAGE }, REQUEST_EXTERNAL_STORAGE_RESULT); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) { ImageView imageView = (android.widget.ImageView) findViewById(R.id.imageView1); File image = new File(pictureDir, FILE_NAME); fileUri = Uri.fromFile(image); imageView.setImageURI(fileUri); emailPicture(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText( this, "You did not click the photo", Toast.LENGTH_SHORT) .show(); } } @Override public void onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_EXTERNAL_STORAGE_RESULT) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { callCameraApp(); } else { Toast.makeText( this, "External write permission" + " has not been granted, " + " cannot saved images", Toast.LENGTH_SHORT) .show(); } } else { super.onRequestPermissionsResult( requestCode, permissions, grantResults); } } // Function to send the image through mail public void emailPicture() { Toast.makeText( this, "Now, sending the mail", Toast.LENGTH_LONG) .show(); Intent emailIntent = new Intent( android.content.Intent.ACTION_SEND); emailIntent.setType("application/image"); emailIntent.putExtra( android.content.Intent.EXTRA_EMAIL, new String[] { // default receiver id "[email protected]" }); // Subject of the mail emailIntent.putExtra( android.content.Intent.EXTRA_SUBJECT, "New photo"); // Body of the mail emailIntent.putExtra( android.content.Intent.EXTRA_TEXT, "Here's a captured image"); // Set the location of the image file // to be added as an attachment emailIntent.putExtra(Intent.EXTRA_STREAM, fileUri); // Start the email activity // to with the prefilled information startActivity( Intent.createChooser(emailIntent, "Send mail...")); }} <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.camera_mail"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <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> Launch the appLaunch the appCapture the imageImage captured and two options given to userSelect the app to be share the captured image. Here GMail is selectedSend the captured image through mailSend the captured image through mailImage receivedImage received through mail Launch the appLaunch the app Launch the app Capture the imageImage captured and two options given to user Image captured and two options given to user Select the app to be share the captured image. Here GMail is selected Send the captured image through mailSend the captured image through mail Send the captured image through mail Image receivedImage received through mail Image received through mail android 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": "\n04 Mar, 2020" }, { "code": null, "e": 124, "s": 54, "text": "Pre-requisite: How to open Camera through Intent and capture an image" }, { "code": null, "e": 236, "s": 124, "text": "In this article, we will try to send the captured image (from this article) to other apps using Android Studio." }, { "code": null, "e": 246, "s": 236, "text": "Approach:" }, { "code": null, "e": 1538, "s": 246, "text": "The image captured gets stored on the external storage. Hence we need to request permission to access the files from the user. So take permission to access external storage permission in the manifest file.Here pictureDir(File) is pointing to the directory of external storage named DIRECTORY_PICTURESFile pictureDir\n = new File(\n Environment.getExternalStoragePublicDirectory(\n Environment.DIRECTORY_PICTURES),\n \"CameraDemo\");\nIn onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code belowif(!pictureDir.exists()){\n pictureDir.mkdirs();\n}\nCreate another method called callCameraApp() to get the clicked image from external storage.Capture the image using IntentCreate a file to store the image in the pictureDir directory.Get the URI object of this image filePut the image on the Intent storage to be accessed from other modules of the app.Pass the image through intent to startActivityForResult()Share this image to other app using intent.Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);\nFor the sake of this article, we will be selecting Gmail and will be sending this image as an attachment in a mail.startActivity(Intent.createChooser(emailIntent, \"Send mail...\"));\n" }, { "code": null, "e": 1744, "s": 1538, "text": "The image captured gets stored on the external storage. Hence we need to request permission to access the files from the user. So take permission to access external storage permission in the manifest file." }, { "code": null, "e": 1995, "s": 1744, "text": "Here pictureDir(File) is pointing to the directory of external storage named DIRECTORY_PICTURESFile pictureDir\n = new File(\n Environment.getExternalStoragePublicDirectory(\n Environment.DIRECTORY_PICTURES),\n \"CameraDemo\");\n" }, { "code": null, "e": 2151, "s": 1995, "text": "File pictureDir\n = new File(\n Environment.getExternalStoragePublicDirectory(\n Environment.DIRECTORY_PICTURES),\n \"CameraDemo\");\n" }, { "code": null, "e": 2337, "s": 2151, "text": "In onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code belowif(!pictureDir.exists()){\n pictureDir.mkdirs();\n}\n" }, { "code": null, "e": 2391, "s": 2337, "text": "if(!pictureDir.exists()){\n pictureDir.mkdirs();\n}\n" }, { "code": null, "e": 2750, "s": 2391, "text": "Create another method called callCameraApp() to get the clicked image from external storage.Capture the image using IntentCreate a file to store the image in the pictureDir directory.Get the URI object of this image filePut the image on the Intent storage to be accessed from other modules of the app.Pass the image through intent to startActivityForResult()" }, { "code": null, "e": 2781, "s": 2750, "text": "Capture the image using Intent" }, { "code": null, "e": 2843, "s": 2781, "text": "Create a file to store the image in the pictureDir directory." }, { "code": null, "e": 2881, "s": 2843, "text": "Get the URI object of this image file" }, { "code": null, "e": 2963, "s": 2881, "text": "Put the image on the Intent storage to be accessed from other modules of the app." }, { "code": null, "e": 3021, "s": 2963, "text": "Pass the image through intent to startActivityForResult()" }, { "code": null, "e": 3134, "s": 3021, "text": "Share this image to other app using intent.Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);\n" }, { "code": null, "e": 3204, "s": 3134, "text": "Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);\n" }, { "code": null, "e": 3386, "s": 3204, "text": "For the sake of this article, we will be selecting Gmail and will be sending this image as an attachment in a mail.startActivity(Intent.createChooser(emailIntent, \"Send mail...\"));\n" }, { "code": null, "e": 3453, "s": 3386, "text": "startActivity(Intent.createChooser(emailIntent, \"Send mail...\"));\n" }, { "code": null, "e": 3513, "s": 3453, "text": "Below is the complete implementation of the above approach:" }, { "code": null, "e": 3531, "s": 3513, "text": "activity_main.xml" }, { "code": null, "e": 3549, "s": 3531, "text": "MainActivity.java" }, { "code": null, "e": 3569, "s": 3549, "text": "AndroidManifest.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\"> <!--Textview with title \"Camera_Demo!\" is given by --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Camera Demo!\" android:id=\"@+id/tv\" android:textSize=\"20sp\" android:textStyle=\"bold\" android:layout_centerHorizontal=\"true\" /> <!-- Add button to take a picture--> <Button android:id=\"@+id/button1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/tv\" android:layout_marginTop=\"50dp\" android:text=\"Take Picture\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!-- Add ImageView to display the captured image--> <ImageView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/imageView1\" android:layout_below=\"@id/button1\" /></RelativeLayout>", "e": 4866, "s": 3569, "text": null }, { "code": "package com.example.camera_mail; import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Environment;import android.provider.MediaStore;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import java.io.File; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final int CAMERA_PIC_REQUEST = 1337; private static final int REQUEST_EXTERNAL_STORAGE_RESULT = 1; private static final String FILE_NAME = \"image01.jpg\"; private Button b1; private ImageView img1; File pictureDir = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), \"CameraDemo\"); private Uri fileUri; // The onCreate() method @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button)findViewById(R.id.button1); img1 = (ImageView)findViewById(R.id.imageView1); b1.setOnClickListener(this); if (!pictureDir.exists()) { pictureDir.mkdirs(); } } // Open the camera app to capture the image public void callCameraApp() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = new File(pictureDir, FILE_NAME); fileUri = Uri.fromFile(image); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(intent, CAMERA_PIC_REQUEST); } public void onClick(View arg0) { if ( ContextCompat.checkSelfPermission( this, Manifest .permission .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { callCameraApp(); } else { if ( ActivityCompat .shouldShowRequestPermissionRationale( this, Manifest .permission .WRITE_EXTERNAL_STORAGE)) { Toast.makeText( this, \"External storage permission\" + \" required to save images\", Toast.LENGTH_SHORT) .show(); } ActivityCompat .requestPermissions( this, new String[] { Manifest .permission .WRITE_EXTERNAL_STORAGE }, REQUEST_EXTERNAL_STORAGE_RESULT); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) { ImageView imageView = (android.widget.ImageView) findViewById(R.id.imageView1); File image = new File(pictureDir, FILE_NAME); fileUri = Uri.fromFile(image); imageView.setImageURI(fileUri); emailPicture(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText( this, \"You did not click the photo\", Toast.LENGTH_SHORT) .show(); } } @Override public void onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_EXTERNAL_STORAGE_RESULT) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { callCameraApp(); } else { Toast.makeText( this, \"External write permission\" + \" has not been granted, \" + \" cannot saved images\", Toast.LENGTH_SHORT) .show(); } } else { super.onRequestPermissionsResult( requestCode, permissions, grantResults); } } // Function to send the image through mail public void emailPicture() { Toast.makeText( this, \"Now, sending the mail\", Toast.LENGTH_LONG) .show(); Intent emailIntent = new Intent( android.content.Intent.ACTION_SEND); emailIntent.setType(\"application/image\"); emailIntent.putExtra( android.content.Intent.EXTRA_EMAIL, new String[] { // default receiver id \"[email protected]\" }); // Subject of the mail emailIntent.putExtra( android.content.Intent.EXTRA_SUBJECT, \"New photo\"); // Body of the mail emailIntent.putExtra( android.content.Intent.EXTRA_TEXT, \"Here's a captured image\"); // Set the location of the image file // to be added as an attachment emailIntent.putExtra(Intent.EXTRA_STREAM, fileUri); // Start the email activity // to with the prefilled information startActivity( Intent.createChooser(emailIntent, \"Send mail...\")); }}", "e": 10681, "s": 4866, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.camera_mail\"> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 11480, "s": 10681, "text": null }, { "code": null, "e": 11752, "s": 11480, "text": "Launch the appLaunch the appCapture the imageImage captured and two options given to userSelect the app to be share the captured image. Here GMail is selectedSend the captured image through mailSend the captured image through mailImage receivedImage received through mail" }, { "code": null, "e": 11781, "s": 11752, "text": "Launch the appLaunch the app" }, { "code": null, "e": 11796, "s": 11781, "text": "Launch the app" }, { "code": null, "e": 11858, "s": 11796, "text": "Capture the imageImage captured and two options given to user" }, { "code": null, "e": 11903, "s": 11858, "text": "Image captured and two options given to user" }, { "code": null, "e": 11973, "s": 11903, "text": "Select the app to be share the captured image. Here GMail is selected" }, { "code": null, "e": 12046, "s": 11973, "text": "Send the captured image through mailSend the captured image through mail" }, { "code": null, "e": 12083, "s": 12046, "text": "Send the captured image through mail" }, { "code": null, "e": 12125, "s": 12083, "text": "Image receivedImage received through mail" }, { "code": null, "e": 12153, "s": 12125, "text": "Image received through mail" }, { "code": null, "e": 12161, "s": 12153, "text": "android" }, { "code": null, "e": 12166, "s": 12161, "text": "Java" }, { "code": null, "e": 12171, "s": 12166, "text": "Java" } ]
LEN() Function in SQL Server
27 Nov, 2020 LEN() function calculates the number of characters of an input string, excluding the trailing spaces. Syntax : LEN(input_string) Parameter –This method accepts a single-parameter as mentioned above and described below : input_string –It is an expression that can be a constant, variable, or column of either character or binary data. Returns : It returns the number of characters of an input string, excluding the trailing spaces. Example-1: Return the length of a string SELECT LEN('Geeksforgeeks'); Output : 13 Example-2: Check LEN() Function count trailing spaces or not SELECT LEN('GFG ') As Length_with_trailing_spaces; Output : Example-3: Check LEN() Function count leading spaces or not SELECT LEN(' GFG') As Length_with_leading_spaces; Output: Example-4: Using LEN() function with a column Table — Player_Details SELECT PlayerName, LEN(PlayerName) PlayerName_Length FROM Player_Details Output : DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Nov, 2020" }, { "code": null, "e": 130, "s": 28, "text": "LEN() function calculates the number of characters of an input string, excluding the trailing spaces." }, { "code": null, "e": 139, "s": 130, "text": "Syntax :" }, { "code": null, "e": 157, "s": 139, "text": "LEN(input_string)" }, { "code": null, "e": 250, "s": 157, "text": "Parameter –This method accepts a single-parameter as mentioned above and described below : " }, { "code": null, "e": 364, "s": 250, "text": "input_string –It is an expression that can be a constant, variable, or column of either character or binary data." }, { "code": null, "e": 374, "s": 364, "text": "Returns :" }, { "code": null, "e": 461, "s": 374, "text": "It returns the number of characters of an input string, excluding the trailing spaces." }, { "code": null, "e": 502, "s": 461, "text": "Example-1: Return the length of a string" }, { "code": null, "e": 531, "s": 502, "text": "SELECT LEN('Geeksforgeeks');" }, { "code": null, "e": 540, "s": 531, "text": "Output :" }, { "code": null, "e": 543, "s": 540, "text": "13" }, { "code": null, "e": 604, "s": 543, "text": "Example-2: Check LEN() Function count trailing spaces or not" }, { "code": null, "e": 662, "s": 604, "text": "SELECT LEN('GFG ') \nAs Length_with_trailing_spaces;" }, { "code": null, "e": 671, "s": 662, "text": "Output :" }, { "code": null, "e": 731, "s": 671, "text": "Example-3: Check LEN() Function count leading spaces or not" }, { "code": null, "e": 788, "s": 731, "text": "SELECT LEN(' GFG') \nAs Length_with_leading_spaces;" }, { "code": null, "e": 796, "s": 788, "text": "Output:" }, { "code": null, "e": 842, "s": 796, "text": "Example-4: Using LEN() function with a column" }, { "code": null, "e": 865, "s": 842, "text": "Table — Player_Details" }, { "code": null, "e": 950, "s": 865, "text": "SELECT\n PlayerName,\n LEN(PlayerName) PlayerName_Length\nFROM\n Player_Details" }, { "code": null, "e": 959, "s": 950, "text": "Output :" }, { "code": null, "e": 968, "s": 959, "text": "DBMS-SQL" }, { "code": null, "e": 979, "s": 968, "text": "SQL-Server" }, { "code": null, "e": 983, "s": 979, "text": "SQL" }, { "code": null, "e": 987, "s": 983, "text": "SQL" }, { "code": null, "e": 1085, "s": 987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1151, "s": 1085, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1175, "s": 1151, "text": "Window functions in SQL" }, { "code": null, "e": 1207, "s": 1175, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1240, "s": 1207, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1257, "s": 1240, "text": "SQL using Python" }, { "code": null, "e": 1287, "s": 1257, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1365, "s": 1287, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1401, "s": 1365, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 1432, "s": 1401, "text": "SQL Query to Compare Two Dates" } ]
Print alternate nodes of a linked list using recursion
17 Feb, 2022 Given a linked list, print alternate nodes of this linked list.Examples : Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 Output : 1 -> 3 -> 5 -> 7 -> 9 Input : 10 -> 9 Output : 10 Recursive Approach : 1. Initialize a static variable(say flag) 2. If flag is odd print the node 3. increase head and flag by 1, and recurse for next nodes. C++ Java Python3 C# Javascript // CPP code to print alternate nodes// of a linked list using recursion#include <bits/stdc++.h>using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; // Inserting node at the beginningvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to print alternate nodes of linked list.// The boolean flag isOdd is used to find if the current// node is even or odd.void printAlternate(struct Node* node, bool isOdd=true){ if (node == NULL) return; if (isOdd == true) cout << node->data << " "; printAlternate(node->next, !isOdd);} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; // construct below list // 1->2->3->4->5->6->7->8->9->10 push(&head, 10); push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printAlternate(head); return 0;} // Java code to print alternate nodes// of a linked list using recursionclass GFG{ // A linked list nodestatic class Node{ int data; Node next;}; // Inserting node at the beginningstatic Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print alternate nodes of linked list.// The boolean flag isOdd is used to find if the current// node is even or odd.static void printAlternate( Node node, boolean isOdd){ if (node == null) return; if (isOdd == true) System.out.print( node.data + " "); printAlternate(node.next, !isOdd);} // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = null; // construct below list // 1.2.3.4.5.6.7.8.9.10 head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printAlternate(head,true); }} // This code is contributed by Arnab Kundu # Python3 code to print alternate nodes# of a linked list using recursion # A linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Inserting node at the beginningdef push( head_ref, new_data): new_node = Node(new_data); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; # Function to print alternate nodes of# linked list. The boolean flag isOdd# is used to find if the current node# is even or odd.def printAlternate( node, isOdd): if (node == None): return; if (isOdd == True): print( node.data, end = " "); if (isOdd == True): isOdd = False; else: isOdd = True; printAlternate(node.next, isOdd); # Driver code # Start with the empty listhead = None; # construct below list# 1->2->3->4->5->6->7->8->9->10head = push(head, 10);head = push(head, 9);head = push(head, 8);head = push(head, 7);head = push(head, 6);head = push(head, 5);head = push(head, 4);head = push(head, 3);head = push(head, 2);head = push(head, 1); printAlternate(head, True); # This code is contributed by 29AjayKumar // C# code to print alternate nodes// of a linked list using recursionusing System; class GFG{ // A linked list nodepublic class Node{ public int data; public Node next;}; // Inserting node at the beginningstatic Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print alternate nodes of linked list.// The boolean flag isOdd is used to find if the current// node is even or odd.static void printAlternate( Node node, bool isOdd){ if (node == null) return; if (isOdd == true) Console.Write( node.data + " "); printAlternate(node.next, !isOdd);} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = null; // construct below list // 1.2.3.4.5.6.7.8.9.10 head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printAlternate(head,true); }} // This code has been contributed by 29AjayKumar <script>// javascript code to print alternate nodes// of a linked list using recursion // A linked list nodeclass Node { constructor(val) { this.data = val; this.next = null; }} // Inserting node at the beginning function push(head_ref , new_data) {var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Function to print alternate nodes of linked list. // The boolean flag isOdd is used to find if the current // node is even or odd. function printAlternate(node, isOdd) { if (node == null) return; if (isOdd == true) document.write(node.data + " "); printAlternate(node.next, !isOdd); } // Driver code // Start with the empty listvar head = null; // construct below list // 1.2.3.4.5.6.7.8.9.10 head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printAlternate(head, true); // This code contributed by umadevi9616</script> 1 3 5 7 9 Print alternate nodes of a linked list using recursion | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPrint alternate nodes of a linked list using recursion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ksyUny54Avk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> andrew1234 29AjayKumar umadevi9616 ankita_saini simmytarika5 Linked List Recursion Linked List Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Feb, 2022" }, { "code": null, "e": 129, "s": 53, "text": "Given a linked list, print alternate nodes of this linked list.Examples : " }, { "code": null, "e": 246, "s": 129, "text": "Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10\nOutput : 1 -> 3 -> 5 -> 7 -> 9 \n\nInput : 10 -> 9\nOutput : 10" }, { "code": null, "e": 405, "s": 248, "text": "Recursive Approach : 1. Initialize a static variable(say flag) 2. If flag is odd print the node 3. increase head and flag by 1, and recurse for next nodes. " }, { "code": null, "e": 409, "s": 405, "text": "C++" }, { "code": null, "e": 414, "s": 409, "text": "Java" }, { "code": null, "e": 422, "s": 414, "text": "Python3" }, { "code": null, "e": 425, "s": 422, "text": "C#" }, { "code": null, "e": 436, "s": 425, "text": "Javascript" }, { "code": "// CPP code to print alternate nodes// of a linked list using recursion#include <bits/stdc++.h>using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; // Inserting node at the beginningvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to print alternate nodes of linked list.// The boolean flag isOdd is used to find if the current// node is even or odd.void printAlternate(struct Node* node, bool isOdd=true){ if (node == NULL) return; if (isOdd == true) cout << node->data << \" \"; printAlternate(node->next, !isOdd);} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; // construct below list // 1->2->3->4->5->6->7->8->9->10 push(&head, 10); push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printAlternate(head); return 0;}", "e": 1577, "s": 436, "text": null }, { "code": "// Java code to print alternate nodes// of a linked list using recursionclass GFG{ // A linked list nodestatic class Node{ int data; Node next;}; // Inserting node at the beginningstatic Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print alternate nodes of linked list.// The boolean flag isOdd is used to find if the current// node is even or odd.static void printAlternate( Node node, boolean isOdd){ if (node == null) return; if (isOdd == true) System.out.print( node.data + \" \"); printAlternate(node.next, !isOdd);} // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = null; // construct below list // 1.2.3.4.5.6.7.8.9.10 head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printAlternate(head,true); }} // This code is contributed by Arnab Kundu", "e": 2762, "s": 1577, "text": null }, { "code": "# Python3 code to print alternate nodes# of a linked list using recursion # A linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Inserting node at the beginningdef push( head_ref, new_data): new_node = Node(new_data); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; # Function to print alternate nodes of# linked list. The boolean flag isOdd# is used to find if the current node# is even or odd.def printAlternate( node, isOdd): if (node == None): return; if (isOdd == True): print( node.data, end = \" \"); if (isOdd == True): isOdd = False; else: isOdd = True; printAlternate(node.next, isOdd); # Driver code # Start with the empty listhead = None; # construct below list# 1->2->3->4->5->6->7->8->9->10head = push(head, 10);head = push(head, 9);head = push(head, 8);head = push(head, 7);head = push(head, 6);head = push(head, 5);head = push(head, 4);head = push(head, 3);head = push(head, 2);head = push(head, 1); printAlternate(head, True); # This code is contributed by 29AjayKumar", "e": 3903, "s": 2762, "text": null }, { "code": "// C# code to print alternate nodes// of a linked list using recursionusing System; class GFG{ // A linked list nodepublic class Node{ public int data; public Node next;}; // Inserting node at the beginningstatic Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print alternate nodes of linked list.// The boolean flag isOdd is used to find if the current// node is even or odd.static void printAlternate( Node node, bool isOdd){ if (node == null) return; if (isOdd == true) Console.Write( node.data + \" \"); printAlternate(node.next, !isOdd);} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = null; // construct below list // 1.2.3.4.5.6.7.8.9.10 head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printAlternate(head,true); }} // This code has been contributed by 29AjayKumar", "e": 5122, "s": 3903, "text": null }, { "code": "<script>// javascript code to print alternate nodes// of a linked list using recursion // A linked list nodeclass Node { constructor(val) { this.data = val; this.next = null; }} // Inserting node at the beginning function push(head_ref , new_data) {var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Function to print alternate nodes of linked list. // The boolean flag isOdd is used to find if the current // node is even or odd. function printAlternate(node, isOdd) { if (node == null) return; if (isOdd == true) document.write(node.data + \" \"); printAlternate(node.next, !isOdd); } // Driver code // Start with the empty listvar head = null; // construct below list // 1.2.3.4.5.6.7.8.9.10 head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printAlternate(head, true); // This code contributed by umadevi9616</script>", "e": 6421, "s": 5122, "text": null }, { "code": null, "e": 6431, "s": 6421, "text": "1 3 5 7 9" }, { "code": null, "e": 7359, "s": 6433, "text": "Print alternate nodes of a linked list using recursion | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPrint alternate nodes of a linked list using recursion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:52•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ksyUny54Avk\" 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": 7370, "s": 7359, "text": "andrew1234" }, { "code": null, "e": 7382, "s": 7370, "text": "29AjayKumar" }, { "code": null, "e": 7394, "s": 7382, "text": "umadevi9616" }, { "code": null, "e": 7407, "s": 7394, "text": "ankita_saini" }, { "code": null, "e": 7420, "s": 7407, "text": "simmytarika5" }, { "code": null, "e": 7432, "s": 7420, "text": "Linked List" }, { "code": null, "e": 7442, "s": 7432, "text": "Recursion" }, { "code": null, "e": 7454, "s": 7442, "text": "Linked List" }, { "code": null, "e": 7464, "s": 7454, "text": "Recursion" } ]
Angular Material 7 - Card
The <mat-card>, an Angular Directive, is used to create a card with material design styling and animation capabilities. It provides preset styles for the common card sections. <mat-card-title> − Represents the section for title. <mat-card-title> − Represents the section for title. <mat-card-subtitle> − Represents the section for subtitle. <mat-card-subtitle> − Represents the section for subtitle. <mat-card-content> − Represents the section for content. <mat-card-content> − Represents the section for content. <mat-card-actions> − Represents the section for actions. <mat-card-actions> − Represents the section for actions. <mat-card-footer> − Represents the section for footer. <mat-card-footer> − Represents the section for footer. In this chapter, we will showcase the configuration required to draw a card control using Angular Material. Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter − Following is the content of the modified module descriptor app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatCardModule, MatButtonModule} from '@angular/material' import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatCardModule, MatButtonModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Following is the content of the modified CSS file app.component.css. .tp-card { max-width: 400px; } .tp-header-image { background-image: url('https://www.tutorialspoint.com/materialize/src/html5-mini-logo.jpg'); background-size: cover; } Following is the content of the modified HTML host file app.component.html. <mat-card class = "tp-card"> <mat-card-header> <div mat-card-avatar class = "tp-header-image"></div> <mat-card-title>HTML5</mat-card-title> <mat-card-subtitle>HTML Basics</mat-card-subtitle> </mat-card-header> <img mat-card-image src = "https://www.tutorialspoint.com/materialize/src/html5-mini-logo.jpg" alt = "Learn HTML5"> <mat-card-content> <p> HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web. </p> </mat-card-content> <mat-card-actions> <button mat-button>LIKE</button> <button mat-button>SHARE</button> </mat-card-actions> </mat-card> Verify the result. Here, we've created a card using mat-card.
[ { "code": null, "e": 3065, "s": 2889, "text": "The <mat-card>, an Angular Directive, is used to create a card with material design styling and animation capabilities. It provides preset styles for the common card sections." }, { "code": null, "e": 3118, "s": 3065, "text": "<mat-card-title> − Represents the section for title." }, { "code": null, "e": 3171, "s": 3118, "text": "<mat-card-title> − Represents the section for title." }, { "code": null, "e": 3230, "s": 3171, "text": "<mat-card-subtitle> − Represents the section for subtitle." }, { "code": null, "e": 3289, "s": 3230, "text": "<mat-card-subtitle> − Represents the section for subtitle." }, { "code": null, "e": 3346, "s": 3289, "text": "<mat-card-content> − Represents the section for content." }, { "code": null, "e": 3403, "s": 3346, "text": "<mat-card-content> − Represents the section for content." }, { "code": null, "e": 3460, "s": 3403, "text": "<mat-card-actions> − Represents the section for actions." }, { "code": null, "e": 3517, "s": 3460, "text": "<mat-card-actions> − Represents the section for actions." }, { "code": null, "e": 3572, "s": 3517, "text": "<mat-card-footer> − Represents the section for footer." }, { "code": null, "e": 3627, "s": 3572, "text": "<mat-card-footer> − Represents the section for footer." }, { "code": null, "e": 3735, "s": 3627, "text": "In this chapter, we will showcase the configuration required to draw a card control using Angular Material." }, { "code": null, "e": 3846, "s": 3735, "text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −" }, { "code": null, "e": 3920, "s": 3846, "text": "Following is the content of the modified module descriptor app.module.ts." }, { "code": null, "e": 4565, "s": 3920, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatCardModule, MatButtonModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatCardModule, MatButtonModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 4634, "s": 4565, "text": "Following is the content of the modified CSS file app.component.css." }, { "code": null, "e": 4812, "s": 4634, "text": ".tp-card {\n max-width: 400px;\n}\n.tp-header-image {\n background-image: url('https://www.tutorialspoint.com/materialize/src/html5-mini-logo.jpg');\n background-size: cover;\n}" }, { "code": null, "e": 4888, "s": 4812, "text": "Following is the content of the modified HTML host file app.component.html." }, { "code": null, "e": 5655, "s": 4888, "text": "<mat-card class = \"tp-card\">\n <mat-card-header>\n <div mat-card-avatar class = \"tp-header-image\"></div>\n <mat-card-title>HTML5</mat-card-title>\n <mat-card-subtitle>HTML Basics</mat-card-subtitle>\n </mat-card-header>\n <img mat-card-image src = \"https://www.tutorialspoint.com/materialize/src/html5-mini-logo.jpg\" alt = \"Learn HTML5\">\n <mat-card-content>\n <p>\n HTML5 is the next major revision of the HTML standard superseding\n HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for\n structuring and presenting content on the World Wide Web.\n </p>\n </mat-card-content>\n <mat-card-actions>\n <button mat-button>LIKE</button>\n <button mat-button>SHARE</button>\n </mat-card-actions>\n</mat-card>" }, { "code": null, "e": 5674, "s": 5655, "text": "Verify the result." } ]
JDBC - Database Connections
After you've installed the appropriate driver, it is time to establish a database connection using JDBC. The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps − Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code. Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code. Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests. Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests. Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect. Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect. Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection. Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection. The Import statements tell the Java compiler where to find the classes you reference in your code and are placed at the very beginning of your source code. To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL tables, add the following imports to your source code − import java.sql.* ; // for standard JDBC programs import java.math.* ; // for BigDecimal and BigInteger support You must register the driver in your program before you use it. Registering the driver is the process by which the Oracle driver's class file is loaded into the memory, so it can be utilized as an implementation of the JDBC interfaces. You need to do this registration only once in your program. You can register a driver in one of two ways. The most common approach to register a driver is to use Java's Class.forName() method, to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable. The following example uses Class.forName( ) to register the Oracle driver − try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(ClassNotFoundException ex) { System.out.println("Error: unable to load driver class!"); System.exit(1); } You can use getInstance() method to work around noncompliant JVMs, but then you'll have to code for two extra Exceptions as follows − try { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); } catch(ClassNotFoundException ex) { System.out.println("Error: unable to load driver class!"); System.exit(1); catch(IllegalAccessException ex) { System.out.println("Error: access problem while loading!"); System.exit(2); catch(InstantiationException ex) { System.out.println("Error: unable to instantiate driver!"); System.exit(3); } The second approach you can use to register a driver, is to use the static DriverManager.registerDriver() method. You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the one provided by Microsoft. The following example uses registerDriver() to register the Oracle driver − try { Driver myDriver = new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver( myDriver ); } catch(ClassNotFoundException ex) { System.out.println("Error: unable to load driver class!"); System.exit(1); } After you've loaded the driver, you can establish a connection using the DriverManager.getConnection() method. For easy reference, let me list the three overloaded DriverManager.getConnection() methods − getConnection(String url) getConnection(String url) getConnection(String url, Properties prop) getConnection(String url, Properties prop) getConnection(String url, String user, String password) getConnection(String url, String user, String password) Here each form requires a database URL. A database URL is an address that points to your database. Formulating a database URL is where most of the problems associated with establishing a connection occurs. Following table lists down the popular JDBC driver names and database URL. All the highlighted part in URL format is static and you need to change only the remaining part as per your database setup. We have listed down three forms of DriverManager.getConnection() method to create a connection object. The most commonly used form of getConnection() requires you to pass a database URL, a username, and a password − Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for the database portion of the URL. If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle listener is configured to listen on port 1521, and your database name is EMP, then complete database URL would be − jdbc:oracle:thin:@amrood:1521:EMP Now you have to call getConnection() method with appropriate username and password to get a Connection object as follows − String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; String USER = "username"; String PASS = "password" Connection conn = DriverManager.getConnection(URL, USER, PASS); A second form of the DriverManager.getConnection( ) method requires only a database URL − DriverManager.getConnection(String url); However, in this case, the database URL includes the username and password and has the following general form − jdbc:oracle:driver:username/password@database So, the above connection can be created as follows − String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP"; Connection conn = DriverManager.getConnection(URL); A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties object − DriverManager.getConnection(String url, Properties info); A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to the driver during a call to the getConnection() method. To make the same connection made by the previous examples, use the following code − import java.util.*; String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; Properties info = new Properties( ); info.put( "user", "username" ); info.put( "password", "password" ); Connection conn = DriverManager.getConnection(URL, info); At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects. Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object. To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not. To close the above opened connection, you should call close() method as follows − conn.close(); Explicitly closing a connection conserves DBMS resources, which will make your database administrator happy. For a better understanding, we suggest you to study our JDBC - Sample Code tutorial.
[ { "code": null, "e": 2401, "s": 2296, "text": "After you've installed the appropriate driver, it is time to establish a database connection using JDBC." }, { "code": null, "e": 2510, "s": 2401, "text": "The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps −" }, { "code": null, "e": 2622, "s": 2510, "text": "Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code." }, { "code": null, "e": 2734, "s": 2622, "text": "Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code." }, { "code": null, "e": 2874, "s": 2734, "text": "Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests." }, { "code": null, "e": 3014, "s": 2874, "text": "Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests." }, { "code": null, "e": 3146, "s": 3014, "text": "Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect." }, { "code": null, "e": 3278, "s": 3146, "text": "Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect." }, { "code": null, "e": 3421, "s": 3278, "text": "Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection." }, { "code": null, "e": 3564, "s": 3421, "text": "Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection." }, { "code": null, "e": 3720, "s": 3564, "text": "The Import statements tell the Java compiler where to find the classes you reference in your code and are placed at the very beginning of your source code." }, { "code": null, "e": 3877, "s": 3720, "text": "To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL tables, add the following imports to your source code −" }, { "code": null, "e": 3990, "s": 3877, "text": "import java.sql.* ; // for standard JDBC programs\nimport java.math.* ; // for BigDecimal and BigInteger support" }, { "code": null, "e": 4226, "s": 3990, "text": "You must register the driver in your program before you use it. Registering the driver is the process by which the Oracle driver's class file is loaded into the memory,\nso it can be utilized as an implementation of the JDBC interfaces." }, { "code": null, "e": 4332, "s": 4226, "text": "You need to do this registration only once in your program. You can register a driver in one of two ways." }, { "code": null, "e": 4617, "s": 4332, "text": "The most common approach to register a driver is to use Java's Class.forName() method, to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable." }, { "code": null, "e": 4693, "s": 4617, "text": "The following example uses Class.forName( ) to register the Oracle driver −" }, { "code": null, "e": 4872, "s": 4693, "text": "try {\n Class.forName(\"oracle.jdbc.driver.OracleDriver\");\n}\ncatch(ClassNotFoundException ex) {\n System.out.println(\"Error: unable to load driver class!\");\n System.exit(1);\n}" }, { "code": null, "e": 5006, "s": 4872, "text": "You can use getInstance() method to work around noncompliant JVMs, but then you'll have to code for two extra Exceptions as follows −" }, { "code": null, "e": 5433, "s": 5006, "text": "try {\n Class.forName(\"oracle.jdbc.driver.OracleDriver\").newInstance();\n}\ncatch(ClassNotFoundException ex) {\n System.out.println(\"Error: unable to load driver class!\");\n System.exit(1);\ncatch(IllegalAccessException ex) {\n System.out.println(\"Error: access problem while loading!\");\n System.exit(2);\ncatch(InstantiationException ex) {\n System.out.println(\"Error: unable to instantiate driver!\");\n System.exit(3);\n}" }, { "code": null, "e": 5547, "s": 5433, "text": "The second approach you can use to register a driver, is to use the static DriverManager.registerDriver() method." }, { "code": null, "e": 5671, "s": 5547, "text": "You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the one provided by Microsoft." }, { "code": null, "e": 5747, "s": 5671, "text": "The following example uses registerDriver() to register the Oracle driver −" }, { "code": null, "e": 5978, "s": 5747, "text": "try {\n Driver myDriver = new oracle.jdbc.driver.OracleDriver();\n DriverManager.registerDriver( myDriver );\n}\ncatch(ClassNotFoundException ex) {\n System.out.println(\"Error: unable to load driver class!\");\n System.exit(1);\n}" }, { "code": null, "e": 6182, "s": 5978, "text": "After you've loaded the driver, you can establish a connection using the DriverManager.getConnection() method. For easy reference, let me list the three\noverloaded DriverManager.getConnection() methods −" }, { "code": null, "e": 6208, "s": 6182, "text": "getConnection(String url)" }, { "code": null, "e": 6234, "s": 6208, "text": "getConnection(String url)" }, { "code": null, "e": 6277, "s": 6234, "text": "getConnection(String url, Properties prop)" }, { "code": null, "e": 6320, "s": 6277, "text": "getConnection(String url, Properties prop)" }, { "code": null, "e": 6376, "s": 6320, "text": "getConnection(String url, String user, String password)" }, { "code": null, "e": 6432, "s": 6376, "text": "getConnection(String url, String user, String password)" }, { "code": null, "e": 6531, "s": 6432, "text": "Here each form requires a database URL. A database URL is an address that points to your database." }, { "code": null, "e": 6638, "s": 6531, "text": "Formulating a database URL is where most of the problems associated with establishing a connection occurs." }, { "code": null, "e": 6713, "s": 6638, "text": "Following table lists down the popular JDBC driver names and database URL." }, { "code": null, "e": 6837, "s": 6713, "text": "All the highlighted part in URL format is static and you need to change only the remaining part as per your database setup." }, { "code": null, "e": 6940, "s": 6837, "text": "We have listed down three forms of DriverManager.getConnection() method to create a connection object." }, { "code": null, "e": 7053, "s": 6940, "text": "The most commonly used form of getConnection() requires you to pass a database URL, a username, and a password −" }, { "code": null, "e": 7181, "s": 7053, "text": "Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for the database portion of the URL." }, { "code": null, "e": 7388, "s": 7181, "text": "If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle listener is configured to listen on port 1521, and your database name is EMP, then complete database URL would be −" }, { "code": null, "e": 7422, "s": 7388, "text": "jdbc:oracle:thin:@amrood:1521:EMP" }, { "code": null, "e": 7545, "s": 7422, "text": "Now you have to call getConnection() method with appropriate username and password to get a Connection object as follows −" }, { "code": null, "e": 7710, "s": 7545, "text": "String URL = \"jdbc:oracle:thin:@amrood:1521:EMP\";\nString USER = \"username\";\nString PASS = \"password\"\nConnection conn = DriverManager.getConnection(URL, USER, PASS);" }, { "code": null, "e": 7800, "s": 7710, "text": "A second form of the DriverManager.getConnection( ) method requires only a database URL −" }, { "code": null, "e": 7842, "s": 7800, "text": "DriverManager.getConnection(String url);\n" }, { "code": null, "e": 7954, "s": 7842, "text": "However, in this case, the database URL includes the username and password and has the following general form −" }, { "code": null, "e": 8000, "s": 7954, "text": "jdbc:oracle:driver:username/password@database" }, { "code": null, "e": 8053, "s": 8000, "text": "So, the above connection can be created as follows −" }, { "code": null, "e": 8172, "s": 8053, "text": "String URL = \"jdbc:oracle:thin:username/password@amrood:1521:EMP\";\nConnection conn = DriverManager.getConnection(URL);" }, { "code": null, "e": 8280, "s": 8172, "text": "A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties object −" }, { "code": null, "e": 8338, "s": 8280, "text": "DriverManager.getConnection(String url, Properties info);" }, { "code": null, "e": 8490, "s": 8338, "text": "A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to the driver during a call to the getConnection() method." }, { "code": null, "e": 8574, "s": 8490, "text": "To make the same connection made by the previous examples, use the following code −" }, { "code": null, "e": 8809, "s": 8574, "text": "import java.util.*;\n\nString URL = \"jdbc:oracle:thin:@amrood:1521:EMP\";\nProperties info = new Properties( );\ninfo.put( \"user\", \"username\" );\ninfo.put( \"password\", \"password\" );\n\nConnection conn = DriverManager.getConnection(URL, info);" }, { "code": null, "e": 9051, "s": 8809, "text": "At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if\nyou forget, Java's garbage collector will close the connection when it cleans up stale objects." }, { "code": null, "e": 9275, "s": 9051, "text": "Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object." }, { "code": null, "e": 9439, "s": 9275, "text": "To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not." }, { "code": null, "e": 9521, "s": 9439, "text": "To close the above opened connection, you should call close() method as follows −" }, { "code": null, "e": 9536, "s": 9521, "text": "conn.close();\n" }, { "code": null, "e": 9645, "s": 9536, "text": "Explicitly closing a connection conserves DBMS resources, which will make your database administrator happy." } ]
Matrix Chain Multiplication (A O(N^2) Solution)
24 May, 2021 Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: (ABC)D = (AB)(CD) = A(BCD) = .... However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrices. Then, (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations. Clearly, the first parenthesization requires less number of operations.Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. Input: p[] = {40, 20, 30, 10, 30} Output: 26000 There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30 Input: p[] = {10, 20, 30, 40, 30} Output: 30000 There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30 Input: p[] = {10, 20, 30} Output: 6000 There are only two matrices of dimensions 10x20 and 20x30. So there is only one way to multiply the matrices, cost of which is 10*20*30 We have discussed a O(n^3) solution for Matrix Chain Multiplication Problem. Note: Below solution does not work for many cases. For example: for input {2, 40, 2, 40, 5}, the correct answer is 580 but this method returns 720 There is another similar approach to solving this problem. More intuitive and recursive approach. Assume there are following available method minCost(M1, M2) -> returns min cost of multiplying matrices M1 and M2Then, for any chained product of matrices like, M1.M2.M3.M4...Mn min cost of chain = min(minCost(M1, M2.M3...Mn), minCost(M1.M2..Mn-1, Mn)) Now we have two subchains (sub problems) : M2.M3...Mn M1.M2..Mn-1 C++ Java Python3 C# PHP Javascript // CPP program to implement optimized matrix chain multiplication problem.#include<iostream>using namespace std; // Matrix Mi has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ int dp[n][n]; /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i=1; i<n; i++) dp[i][i] = 0; // Simply following above recursive formula. for (int L=1; L<n-1; L++) for (int i=1; i<n-L; i++) dp[i][i+L] = min(dp[i+1][i+L] + p[i-1]*p[i]*p[i+L], dp[i][i+L-1] + p[i-1]*p[i+L-1]*p[i+L]); return dp[1][n-1];} // Driver codeint main(){ int arr[] = {10, 20, 30, 40, 30} ; int size = sizeof(arr)/sizeof(arr[0]); printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, size)); return 0;} // Java program to implement optimized matrix chain multiplication problem.import java.util.*;import java.lang.*;import java.io.*; class GFG{// Matrix Mi has dimension p[i-1] x p[i] for i = 1..nstatic int MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ int [][]dp=new int[n][n]; /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i=1; i<n; i++) dp[i][i] = 0; // Simply following above recursive formula. for (int L=1; L<n-1; L++) for (int i=1; i<n-L; i++) dp[i][i+L] = Math.min(dp[i+1][i+L] + p[i-1]*p[i]*p[i+L], dp[i][i+L-1] + p[i-1]*p[i+L-1]*p[i+L]); return dp[1][n-1];} // Driver codepublic static void main(String args[]){ int arr[] = {10, 20, 30, 40, 30} ; int size = arr.length; System.out.print("Minimum number of multiplications is "+ MatrixChainOrder(arr, size)); }} # Python3 program to implement optimized# matrix chain multiplication problem. # Matrix Mi has dimension# p[i-1] x p[i] for i = 1..ndef MatrixChainOrder(p, n): # For simplicity of the program, one # extra row and one extra column are # allocated in dp[][]. 0th row and # 0th column of dp[][] are not used dp = [[0 for i in range(n)] for i in range(n)] # dp[i, j] = Minimum number of scalar # multiplications needed to compute # the matrix M[i]M[i+1]...M[j] = M[i..j] # where dimension of M[i] is p[i-1] x p[i] # cost is zero when multiplying one matrix. for i in range(1, n): dp[i][i] = 0 # Simply following above recursive formula. for L in range(1, n - 1): for i in range(n - L): dp[i][i + L] = min(dp[i + 1][i + L] + p[i - 1] * p[i] * p[i + L], dp[i][i + L - 1] + p[i - 1] * p[i + L - 1] * p[i + L]) return dp[1][n - 1] # Driver codearr = [10, 20, 30, 40, 30]size = len(arr)print("Minimum number of multiplications is", MatrixChainOrder(arr, size)) # This code is contributed# by sahishelangia // C# program to implement optimized// matrix chain multiplication problem.using System; class GFG{// Matrix Mi has dimension// p[i-1] x p[i] for i = 1..nstatic int MatrixChainOrder(int []p, int n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ int [,]dp = new int[n, n]; /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for (int i = 1; i < n; i++) dp[i, i] = 0; // Simply following above // recursive formula. for (int L = 1; L < n - 1; L++) for (int i = 1; i < n - L; i++) dp[i, i + L] = Math.Min(dp[i + 1, i + L] + p[i - 1] * p[i] * p[i + L], dp[i, i + L - 1] + p[i - 1] * p[i + L - 1] * p[i + L]); return dp[1, n - 1];} // Driver codepublic static void Main(){ int []arr = {10, 20, 30, 40, 30} ; int size = arr.Length; Console.WriteLine("Minimum number of multiplications is " + MatrixChainOrder(arr, size));}} // This code is contributed by anuj_67 <?php// PHP program to implement optimized// matrix chain multiplication problem. // Matrix Mi has dimension// p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder($p, $n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ $dp = array(); /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for ($i=1; $i<$n; $i++) $dp[$i][$i] = 0; // Simply following above // recursive formula. for ($L = 1; $L < $n - 1; $L++) for ($i = 1; $i < $n - $L; $i++) $dp[$i][$i + $L] = min($dp[$i + 1][$i + $L] + $p[$i - 1] * $p[$i] * $p[$i + $L], $dp[$i][$i + $L - 1] + $p[$i - 1] * $p[$i + $L - 1] * $p[$i + $L]); return $dp[1][$n - 1];} // Driver code$arr = array(10, 20, 30, 40, 30) ;$size = sizeof($arr); echo "Minimum number of multiplications is ". MatrixChainOrder($arr, $size); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to implement optimized// matrix chain multiplication problem. // Matrix Mi has dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(p, n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ var dp = Array.from(Array(n), ()=> Array(n)); /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (var i=1; i<n; i++) dp[i][i] = 0; // Simply following above recursive formula. for (var L=1; L<n-1; L++) for (var i=1; i<n-L; i++) dp[i][i+L] = Math.min(dp[i+1][i+L] + p[i-1]*p[i]*p[i+L], dp[i][i+L-1] + p[i-1]*p[i+L-1]*p[i+L]); return dp[1][n-1];} // Driver codevar arr = [10, 20, 30, 40, 30];var size = arr.length;document.write("Minimum number of multiplications is "+ MatrixChainOrder(arr, size)); </script> Minimum number of multiplications is 30000 Thanks to Rishi_Lazy for providing above optimized solution.Time Complexity : O(n2) Printing Brackets in Matrix Chain Multiplication tufan_gupta2000 vt_m Akanksha_Rai sahilshelangia 2019ucp1394 rutvik_56 matrix-chain-multiplication Dynamic Programming Matrix Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Count number of binary strings without consecutive 1's Tabulation vs Memoization Partition a set into two subsets such that the difference of subset sums is minimum Longest Common Substring | DP-29 Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 The Celebrity Problem
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2021" }, { "code": null, "e": 531, "s": 52, "text": "Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: " }, { "code": null, "e": 569, "s": 531, "text": " (ABC)D = (AB)(CD) = A(BCD) = ...." }, { "code": null, "e": 827, "s": 569, "text": "However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrices. Then, " }, { "code": null, "e": 963, "s": 827, "text": " (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations\n A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations." }, { "code": null, "e": 1287, "s": 963, "text": "Clearly, the first parenthesization requires less number of operations.Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. " }, { "code": null, "e": 2097, "s": 1287, "text": " Input: p[] = {40, 20, 30, 10, 30} \n Output: 26000 \n There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.\n Let the input 4 matrices be A, B, C and D. The minimum number of \n multiplications are obtained by putting parenthesis in following way\n (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30\n\n Input: p[] = {10, 20, 30, 40, 30} \n Output: 30000 \n There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. \n Let the input 4 matrices be A, B, C and D. The minimum number of \n multiplications are obtained by putting parenthesis in following way\n ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30\n\n Input: p[] = {10, 20, 30} \n Output: 6000 \n There are only two matrices of dimensions 10x20 and 20x30. So there \n is only one way to multiply the matrices, cost of which is 10*20*30" }, { "code": null, "e": 2422, "s": 2099, "text": "We have discussed a O(n^3) solution for Matrix Chain Multiplication Problem. Note: Below solution does not work for many cases. For example: for input {2, 40, 2, 40, 5}, the correct answer is 580 but this method returns 720 There is another similar approach to solving this problem. More intuitive and recursive approach. " }, { "code": null, "e": 2742, "s": 2422, "text": "Assume there are following available method minCost(M1, M2) -> returns min cost of multiplying matrices M1 and M2Then, for any chained product of matrices like, M1.M2.M3.M4...Mn min cost of chain = min(minCost(M1, M2.M3...Mn), minCost(M1.M2..Mn-1, Mn)) Now we have two subchains (sub problems) : M2.M3...Mn M1.M2..Mn-1 " }, { "code": null, "e": 2748, "s": 2744, "text": "C++" }, { "code": null, "e": 2753, "s": 2748, "text": "Java" }, { "code": null, "e": 2761, "s": 2753, "text": "Python3" }, { "code": null, "e": 2764, "s": 2761, "text": "C#" }, { "code": null, "e": 2768, "s": 2764, "text": "PHP" }, { "code": null, "e": 2779, "s": 2768, "text": "Javascript" }, { "code": "// CPP program to implement optimized matrix chain multiplication problem.#include<iostream>using namespace std; // Matrix Mi has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ int dp[n][n]; /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i=1; i<n; i++) dp[i][i] = 0; // Simply following above recursive formula. for (int L=1; L<n-1; L++) for (int i=1; i<n-L; i++) dp[i][i+L] = min(dp[i+1][i+L] + p[i-1]*p[i]*p[i+L], dp[i][i+L-1] + p[i-1]*p[i+L-1]*p[i+L]); return dp[1][n-1];} // Driver codeint main(){ int arr[] = {10, 20, 30, 40, 30} ; int size = sizeof(arr)/sizeof(arr[0]); printf(\"Minimum number of multiplications is %d \", MatrixChainOrder(arr, size)); return 0;}", "e": 3924, "s": 2779, "text": null }, { "code": "// Java program to implement optimized matrix chain multiplication problem.import java.util.*;import java.lang.*;import java.io.*; class GFG{// Matrix Mi has dimension p[i-1] x p[i] for i = 1..nstatic int MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ int [][]dp=new int[n][n]; /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i=1; i<n; i++) dp[i][i] = 0; // Simply following above recursive formula. for (int L=1; L<n-1; L++) for (int i=1; i<n-L; i++) dp[i][i+L] = Math.min(dp[i+1][i+L] + p[i-1]*p[i]*p[i+L], dp[i][i+L-1] + p[i-1]*p[i+L-1]*p[i+L]); return dp[1][n-1];} // Driver codepublic static void main(String args[]){ int arr[] = {10, 20, 30, 40, 30} ; int size = arr.length; System.out.print(\"Minimum number of multiplications is \"+ MatrixChainOrder(arr, size)); }}", "e": 5130, "s": 3924, "text": null }, { "code": "# Python3 program to implement optimized# matrix chain multiplication problem. # Matrix Mi has dimension# p[i-1] x p[i] for i = 1..ndef MatrixChainOrder(p, n): # For simplicity of the program, one # extra row and one extra column are # allocated in dp[][]. 0th row and # 0th column of dp[][] are not used dp = [[0 for i in range(n)] for i in range(n)] # dp[i, j] = Minimum number of scalar # multiplications needed to compute # the matrix M[i]M[i+1]...M[j] = M[i..j] # where dimension of M[i] is p[i-1] x p[i] # cost is zero when multiplying one matrix. for i in range(1, n): dp[i][i] = 0 # Simply following above recursive formula. for L in range(1, n - 1): for i in range(n - L): dp[i][i + L] = min(dp[i + 1][i + L] + p[i - 1] * p[i] * p[i + L], dp[i][i + L - 1] + p[i - 1] * p[i + L - 1] * p[i + L]) return dp[1][n - 1] # Driver codearr = [10, 20, 30, 40, 30]size = len(arr)print(\"Minimum number of multiplications is\", MatrixChainOrder(arr, size)) # This code is contributed# by sahishelangia", "e": 6343, "s": 5130, "text": null }, { "code": "// C# program to implement optimized// matrix chain multiplication problem.using System; class GFG{// Matrix Mi has dimension// p[i-1] x p[i] for i = 1..nstatic int MatrixChainOrder(int []p, int n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ int [,]dp = new int[n, n]; /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for (int i = 1; i < n; i++) dp[i, i] = 0; // Simply following above // recursive formula. for (int L = 1; L < n - 1; L++) for (int i = 1; i < n - L; i++) dp[i, i + L] = Math.Min(dp[i + 1, i + L] + p[i - 1] * p[i] * p[i + L], dp[i, i + L - 1] + p[i - 1] * p[i + L - 1] * p[i + L]); return dp[1, n - 1];} // Driver codepublic static void Main(){ int []arr = {10, 20, 30, 40, 30} ; int size = arr.Length; Console.WriteLine(\"Minimum number of multiplications is \" + MatrixChainOrder(arr, size));}} // This code is contributed by anuj_67", "e": 7705, "s": 6343, "text": null }, { "code": "<?php// PHP program to implement optimized// matrix chain multiplication problem. // Matrix Mi has dimension// p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder($p, $n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ $dp = array(); /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for ($i=1; $i<$n; $i++) $dp[$i][$i] = 0; // Simply following above // recursive formula. for ($L = 1; $L < $n - 1; $L++) for ($i = 1; $i < $n - $L; $i++) $dp[$i][$i + $L] = min($dp[$i + 1][$i + $L] + $p[$i - 1] * $p[$i] * $p[$i + $L], $dp[$i][$i + $L - 1] + $p[$i - 1] * $p[$i + $L - 1] * $p[$i + $L]); return $dp[1][$n - 1];} // Driver code$arr = array(10, 20, 30, 40, 30) ;$size = sizeof($arr); echo \"Minimum number of multiplications is \". MatrixChainOrder($arr, $size); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 9023, "s": 7705, "text": null }, { "code": "<script> // Javascript program to implement optimized// matrix chain multiplication problem. // Matrix Mi has dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(p, n){ /* For simplicity of the program, one extra row and one extra column are allocated in dp[][]. 0th row and 0th column of dp[][] are not used */ var dp = Array.from(Array(n), ()=> Array(n)); /* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j] = M[i..j] where dimension of M[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (var i=1; i<n; i++) dp[i][i] = 0; // Simply following above recursive formula. for (var L=1; L<n-1; L++) for (var i=1; i<n-L; i++) dp[i][i+L] = Math.min(dp[i+1][i+L] + p[i-1]*p[i]*p[i+L], dp[i][i+L-1] + p[i-1]*p[i+L-1]*p[i+L]); return dp[1][n-1];} // Driver codevar arr = [10, 20, 30, 40, 30];var size = arr.length;document.write(\"Minimum number of multiplications is \"+ MatrixChainOrder(arr, size)); </script>", "e": 10152, "s": 9023, "text": null }, { "code": null, "e": 10195, "s": 10152, "text": "Minimum number of multiplications is 30000" }, { "code": null, "e": 10331, "s": 10197, "text": "Thanks to Rishi_Lazy for providing above optimized solution.Time Complexity : O(n2) Printing Brackets in Matrix Chain Multiplication " }, { "code": null, "e": 10347, "s": 10331, "text": "tufan_gupta2000" }, { "code": null, "e": 10352, "s": 10347, "text": "vt_m" }, { "code": null, "e": 10365, "s": 10352, "text": "Akanksha_Rai" }, { "code": null, "e": 10380, "s": 10365, "text": "sahilshelangia" }, { "code": null, "e": 10392, "s": 10380, "text": "2019ucp1394" }, { "code": null, "e": 10402, "s": 10392, "text": "rutvik_56" }, { "code": null, "e": 10430, "s": 10402, "text": "matrix-chain-multiplication" }, { "code": null, "e": 10450, "s": 10430, "text": "Dynamic Programming" }, { "code": null, "e": 10457, "s": 10450, "text": "Matrix" }, { "code": null, "e": 10477, "s": 10457, "text": "Dynamic Programming" }, { "code": null, "e": 10484, "s": 10477, "text": "Matrix" }, { "code": null, "e": 10582, "s": 10484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10650, "s": 10582, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 10705, "s": 10650, "text": "Count number of binary strings without consecutive 1's" }, { "code": null, "e": 10731, "s": 10705, "text": "Tabulation vs Memoization" }, { "code": null, "e": 10815, "s": 10731, "text": "Partition a set into two subsets such that the difference of subset sums is minimum" }, { "code": null, "e": 10848, "s": 10815, "text": "Longest Common Substring | DP-29" }, { "code": null, "e": 10884, "s": 10848, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 10928, "s": 10884, "text": "Program to find largest element in an array" }, { "code": null, "e": 10959, "s": 10928, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 10983, "s": 10959, "text": "Sudoku | Backtracking-7" } ]
How to take column-slices of DataFrame in Pandas?
15 Mar, 2021 In this article, we will learn how to slice a DataFrame column-wise in Python. DataFrame is a two-dimensional tabular data structure with labeled axes .i.e. rows and columns. Slicing of a DataFrame can be done using the following two methods: Using loc, the loc is present in the pandas package loc can be used to slice a dataframe using indexing. Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame. Syntax: [ : , first : last : step] Approach: Here first indicates the name of the first column to be taken. Last indicates the name of the last column to be taken. The step indicates the number of indices to advance after each extraction. Example 1: Python3 # importing pandasimport pandas as pd # Using DataFrame() method from pandas moduledf1 = pd.DataFrame({"a": [1, 2, 3], "b": [2, 3, 4], "c": [3, 4, 5], "d": [4, 5, 6], "e": [5, 6, 7]}) df2 = df1.loc[:, "b":"d":2]print(df2) Output: Example 2: Python3 # importing pandasimport pandas as pd # Using DataFrame() method from pandas moduledf1 = pd.DataFrame({"a": [1, 2, 3, 4, 5, 6, 7], "b": [2, 3, 4, 2, 3, 4, 5], "c": [3, 4, 5, 2, 3, 4, 5], "d": [4, 5, 6, 2, 3, 4, 5], "e": [5, 6, 7, 2, 3, 4, 5]}) df2 = df1.loc[:, "c":"e":1]print(df2) Output: Using iloc, the iloc is present in the pandas package. The iloc can be used to slice a dataframe using indexing. Dataframe.iloc[] method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3....n or in case the user doesn’t know the index label. Rows can be extracted using an imaginary index position that isn’t visible in the data frame. Syntax: [ start : stop : step] Approach: Here Start indicates the index of the first column to be taken. Stop indicates the index of the last column to be taken. The step indicates the number of indices to advance after each extraction. Example 1: Python3 # importing pandasimport pandas as pd# Using DataFrame() method from pandas moduledf1 = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [2, 3, 4, 5, 6], "c": [3, 4, 5, 6, 7], "d": [4, 5, 7, 8, 9]}) df2 = df1.iloc[:, 1:3:1]print(df2) Output: Example 2: Python3 # importing pandasimport pandas as pd # Using DataFrame() method from pandas moduledf1 = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [2, 3, 4, 5, 6], "c": [3, 4, 5, 6, 7], "d": [4, 5, 7, 8, 9]}) df2 = df1.iloc[:, 0:3:2]print(df2) Output: Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Mar, 2021" }, { "code": null, "e": 271, "s": 28, "text": "In this article, we will learn how to slice a DataFrame column-wise in Python. DataFrame is a two-dimensional tabular data structure with labeled axes .i.e. rows and columns. Slicing of a DataFrame can be done using the following two methods:" }, { "code": null, "e": 497, "s": 271, "text": "Using loc, the loc is present in the pandas package loc can be used to slice a dataframe using indexing. Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame." }, { "code": null, "e": 506, "s": 497, "text": "Syntax: " }, { "code": null, "e": 533, "s": 506, "text": "[ : , first : last : step]" }, { "code": null, "e": 543, "s": 533, "text": "Approach:" }, { "code": null, "e": 606, "s": 543, "text": "Here first indicates the name of the first column to be taken." }, { "code": null, "e": 662, "s": 606, "text": "Last indicates the name of the last column to be taken." }, { "code": null, "e": 737, "s": 662, "text": "The step indicates the number of indices to advance after each extraction." }, { "code": null, "e": 748, "s": 737, "text": "Example 1:" }, { "code": null, "e": 756, "s": 748, "text": "Python3" }, { "code": "# importing pandasimport pandas as pd # Using DataFrame() method from pandas moduledf1 = pd.DataFrame({\"a\": [1, 2, 3], \"b\": [2, 3, 4], \"c\": [3, 4, 5], \"d\": [4, 5, 6], \"e\": [5, 6, 7]}) df2 = df1.loc[:, \"b\":\"d\":2]print(df2)", "e": 1020, "s": 756, "text": null }, { "code": null, "e": 1028, "s": 1020, "text": "Output:" }, { "code": null, "e": 1039, "s": 1028, "text": "Example 2:" }, { "code": null, "e": 1047, "s": 1039, "text": "Python3" }, { "code": "# importing pandasimport pandas as pd # Using DataFrame() method from pandas moduledf1 = pd.DataFrame({\"a\": [1, 2, 3, 4, 5, 6, 7], \"b\": [2, 3, 4, 2, 3, 4, 5], \"c\": [3, 4, 5, 2, 3, 4, 5], \"d\": [4, 5, 6, 2, 3, 4, 5], \"e\": [5, 6, 7, 2, 3, 4, 5]}) df2 = df1.loc[:, \"c\":\"e\":1]print(df2)", "e": 1411, "s": 1047, "text": null }, { "code": null, "e": 1419, "s": 1411, "text": "Output:" }, { "code": null, "e": 1803, "s": 1419, "text": "Using iloc, the iloc is present in the pandas package. The iloc can be used to slice a dataframe using indexing. Dataframe.iloc[] method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3....n or in case the user doesn’t know the index label. Rows can be extracted using an imaginary index position that isn’t visible in the data frame." }, { "code": null, "e": 1811, "s": 1803, "text": "Syntax:" }, { "code": null, "e": 1834, "s": 1811, "text": "[ start : stop : step]" }, { "code": null, "e": 1844, "s": 1834, "text": "Approach:" }, { "code": null, "e": 1908, "s": 1844, "text": "Here Start indicates the index of the first column to be taken." }, { "code": null, "e": 1965, "s": 1908, "text": "Stop indicates the index of the last column to be taken." }, { "code": null, "e": 2040, "s": 1965, "text": "The step indicates the number of indices to advance after each extraction." }, { "code": null, "e": 2051, "s": 2040, "text": "Example 1:" }, { "code": null, "e": 2059, "s": 2051, "text": "Python3" }, { "code": "# importing pandasimport pandas as pd# Using DataFrame() method from pandas moduledf1 = pd.DataFrame({\"a\": [1, 2, 3, 4, 5], \"b\": [2, 3, 4, 5, 6], \"c\": [3, 4, 5, 6, 7], \"d\": [4, 5, 7, 8, 9]}) df2 = df1.iloc[:, 1:3:1]print(df2)", "e": 2346, "s": 2059, "text": null }, { "code": null, "e": 2354, "s": 2346, "text": "Output:" }, { "code": null, "e": 2365, "s": 2354, "text": "Example 2:" }, { "code": null, "e": 2373, "s": 2365, "text": "Python3" }, { "code": "# importing pandasimport pandas as pd # Using DataFrame() method from pandas moduledf1 = pd.DataFrame({\"a\": [1, 2, 3, 4, 5], \"b\": [2, 3, 4, 5, 6], \"c\": [3, 4, 5, 6, 7], \"d\": [4, 5, 7, 8, 9]}) df2 = df1.iloc[:, 0:3:2]print(df2)", "e": 2662, "s": 2373, "text": null }, { "code": null, "e": 2670, "s": 2662, "text": "Output:" }, { "code": null, "e": 2677, "s": 2670, "text": "Picked" }, { "code": null, "e": 2701, "s": 2677, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2724, "s": 2701, "text": "Python Pandas-exercise" }, { "code": null, "e": 2738, "s": 2724, "text": "Python-pandas" }, { "code": null, "e": 2745, "s": 2738, "text": "Python" }, { "code": null, "e": 2843, "s": 2745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2875, "s": 2843, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2902, "s": 2875, "text": "Python Classes and Objects" }, { "code": null, "e": 2923, "s": 2902, "text": "Python OOPs Concepts" }, { "code": null, "e": 2946, "s": 2923, "text": "Introduction To PYTHON" }, { "code": null, "e": 2977, "s": 2946, "text": "Python | os.path.join() method" }, { "code": null, "e": 3033, "s": 2977, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3075, "s": 3033, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3117, "s": 3075, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3156, "s": 3117, "text": "Python | Get unique values from a list" } ]
What is the use of scope resolution operator in C++?
The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary You can use the single scope operator if a namespace scope or global scope name is hidden by a certain declaration of a similar name during a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator. For example, #include <iostream> using namespace std; int my_var = 0; int main(void) { int my_var = 0; ::my_var = 1; // set global my_var to 1 my_var = 2; // set local my_var to 2 cout << ::my_var << ", " << my_var; return 0; } This will give the output − 1, 2 The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope. You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example, #include <iostream> using namespace std; class X { public: static int count; }; int X::count = 10; // define static data member int main () { int X = 0; // hides class type X cout << X::count << endl; // use static member of class X } This will give the output − 10
[ { "code": null, "e": 1247, "s": 1062, "text": "The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary" }, { "code": null, "e": 1588, "s": 1247, "text": "You can use the single scope operator if a namespace scope or global scope name is hidden by a certain declaration of a similar name during a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator. For example," }, { "code": null, "e": 1828, "s": 1588, "text": "#include <iostream> \nusing namespace std; \n\nint my_var = 0;\nint main(void) {\n int my_var = 0;\n ::my_var = 1; // set global my_var to 1\n my_var = 2; // set local my_var to 2\n\n cout << ::my_var << \", \" << my_var;\n return 0;\n}" }, { "code": null, "e": 1856, "s": 1828, "text": "This will give the output −" }, { "code": null, "e": 1861, "s": 1856, "text": "1, 2" }, { "code": null, "e": 2082, "s": 1861, "text": "The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope." }, { "code": null, "e": 2299, "s": 2082, "text": "You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example," }, { "code": null, "e": 2564, "s": 2299, "text": "#include <iostream>\nusing namespace std;\n\nclass X {\n public:\n static int count;\n};\n\nint X::count = 10; // define static data member\nint main () {\n int X = 0; // hides class type X\n cout << X::count << endl; // use static member of class X\n}" }, { "code": null, "e": 2592, "s": 2564, "text": "This will give the output −" }, { "code": null, "e": 2595, "s": 2592, "text": "10" } ]
C# | Type.IsAssignableFrom(Type) Method - GeeksforGeeks
19 Dec, 2019 Type.IsAssignableFrom(Type) Method is used determine whether an instance of a specified type can be assigned to a variable of the current type. Syntax: public virtual bool IsAssignableFrom (Type c);Here, it takes the type to compare with the current type. Return Value: This method returns true if any of the following conditions is true: c and the current instance represent the same type. c is derived either directly or indirectly from the current instance. c is derived directly from the current instance if it inherits from the current instance; c is derived indirectly from the current instance if it inherits from a succession of one or more classes that inherit from the current instance. The current instance is an interface that c implements. c is a generic type parameter, and the current instance represents one of the constraints of c. Below programs illustrate the use of Type.IsAssignableFrom() Method: Example 1: // C# program to demonstrate the// Type.IsAssignableFrom() Methodusing System;using System.Globalization;using System.Reflection;using System.IO; // Defining MyClass extended// from TypeDelegatorpublic class MyClass : TypeDelegator { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(TypeDelegator); // Getting array of Properties by // using GetProperties() Method bool status = objType.IsAssignableFrom(typeof(MyClass)); // Display the Result if (status) Console.WriteLine("Instance of a specified type can be " + "assigned to a variable of the current type."); else Console.WriteLine("Instance of a specified type can't be " + "assigned to a variable of the current type."); }} Instance of a specified type can be assigned to a variable of the current type. Example 2: // C# program to demonstrate the// Type.IsAssignableFrom() Methodusing System;using System.Globalization;using System.Reflection;using System.IO; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(double); // Getting array of Properties by // using GetProperties() Method bool status = objType.IsAssignableFrom(typeof(int)); // Display the Result if (status) Console.WriteLine("Instance of a specified type can be " + "assigned to a variable of the current type."); else Console.WriteLine("Instance of a specified type can't be " + "assigned to a variable of the current type."); }} Instance of a specified type can't be assigned to a variable of the current type. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=netframework-4.8 shubham_singh CSharp-method CSharp-Type-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n19 Dec, 2019" }, { "code": null, "e": 24446, "s": 24302, "text": "Type.IsAssignableFrom(Type) Method is used determine whether an instance of a specified type can be assigned to a variable of the current type." }, { "code": null, "e": 24558, "s": 24446, "text": "Syntax: public virtual bool IsAssignableFrom (Type c);Here, it takes the type to compare with the current type." }, { "code": null, "e": 24641, "s": 24558, "text": "Return Value: This method returns true if any of the following conditions is true:" }, { "code": null, "e": 24693, "s": 24641, "text": "c and the current instance represent the same type." }, { "code": null, "e": 24999, "s": 24693, "text": "c is derived either directly or indirectly from the current instance. c is derived directly from the current instance if it inherits from the current instance; c is derived indirectly from the current instance if it inherits from a succession of one or more classes that inherit from the current instance." }, { "code": null, "e": 25055, "s": 24999, "text": "The current instance is an interface that c implements." }, { "code": null, "e": 25151, "s": 25055, "text": "c is a generic type parameter, and the current instance represents one of the constraints of c." }, { "code": null, "e": 25220, "s": 25151, "text": "Below programs illustrate the use of Type.IsAssignableFrom() Method:" }, { "code": null, "e": 25231, "s": 25220, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Type.IsAssignableFrom() Methodusing System;using System.Globalization;using System.Reflection;using System.IO; // Defining MyClass extended// from TypeDelegatorpublic class MyClass : TypeDelegator { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(TypeDelegator); // Getting array of Properties by // using GetProperties() Method bool status = objType.IsAssignableFrom(typeof(MyClass)); // Display the Result if (status) Console.WriteLine(\"Instance of a specified type can be \" + \"assigned to a variable of the current type.\"); else Console.WriteLine(\"Instance of a specified type can't be \" + \"assigned to a variable of the current type.\"); }}", "e": 26122, "s": 25231, "text": null }, { "code": null, "e": 26203, "s": 26122, "text": "Instance of a specified type can be assigned to a variable of the current type.\n" }, { "code": null, "e": 26214, "s": 26203, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// Type.IsAssignableFrom() Methodusing System;using System.Globalization;using System.Reflection;using System.IO; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(double); // Getting array of Properties by // using GetProperties() Method bool status = objType.IsAssignableFrom(typeof(int)); // Display the Result if (status) Console.WriteLine(\"Instance of a specified type can be \" + \"assigned to a variable of the current type.\"); else Console.WriteLine(\"Instance of a specified type can't be \" + \"assigned to a variable of the current type.\"); }}", "e": 27003, "s": 26214, "text": null }, { "code": null, "e": 27086, "s": 27003, "text": "Instance of a specified type can't be assigned to a variable of the current type.\n" }, { "code": null, "e": 27097, "s": 27086, "text": "Reference:" }, { "code": null, "e": 27192, "s": 27097, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=netframework-4.8" }, { "code": null, "e": 27206, "s": 27192, "text": "shubham_singh" }, { "code": null, "e": 27220, "s": 27206, "text": "CSharp-method" }, { "code": null, "e": 27238, "s": 27220, "text": "CSharp-Type-Class" }, { "code": null, "e": 27241, "s": 27238, "text": "C#" }, { "code": null, "e": 27339, "s": 27241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27362, "s": 27339, "text": "Extension Method in C#" }, { "code": null, "e": 27390, "s": 27362, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27430, "s": 27390, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27473, "s": 27430, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27489, "s": 27473, "text": "C# | List Class" }, { "code": null, "e": 27506, "s": 27489, "text": "C# | Inheritance" }, { "code": null, "e": 27528, "s": 27506, "text": "Partial Classes in C#" }, { "code": null, "e": 27568, "s": 27528, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27593, "s": 27568, "text": "Lambda Expressions in C#" } ]
How to stop C++ console application from exiting immediately?
Sometimes we have noticed that the console is being closed immediately after displaying the result. So we cannot see the result properly. Here we will see how we can stop the console from closing. The idea is very simple. We can use the getchar() function at the end. This will wait for one character. If one character is pressed, the console will exit. Live Demo #include <iostream> using namespace std; int main() { cout << "Hello World" << endl; getchar(); } Hello World 5 Here button 5 was pressed when it is waiting for a character.
[ { "code": null, "e": 1259, "s": 1062, "text": "Sometimes we have noticed that the console is being closed immediately after displaying the result. So we cannot see the result properly. Here we will see how we can stop the console from closing." }, { "code": null, "e": 1416, "s": 1259, "text": "The idea is very simple. We can use the getchar() function at the end. This will wait for one character. If one character is pressed, the console will exit." }, { "code": null, "e": 1427, "s": 1416, "text": " Live Demo" }, { "code": null, "e": 1531, "s": 1427, "text": "#include <iostream>\nusing namespace std;\nint main() {\n cout << \"Hello World\" << endl;\n getchar();\n}" }, { "code": null, "e": 1545, "s": 1531, "text": "Hello World\n5" }, { "code": null, "e": 1607, "s": 1545, "text": "Here button 5 was pressed when it is waiting for a character." } ]
Approaching Time-Series with a Tree-based Model | by Agnis Liukis | Towards Data Science
In this article, I’m going to show a generic way how to approach a time-series prediction problem with a machine learning model. I’m using a tree-based model LightGBM as an example here, but practically it could be almost any classical machine learning model, including linear regression or some other. I’ll cover needed data transformation, basic feature engineering and, modeling itself. Time series is basically a list of values at known points in time. Some examples: daily purchases at a store, the daily number of website visitors, hourly temperature measurements, etc. Often the interval between data points is fixed, but that is not a mandatory requirement. And the problem we want to solve in a time series is to predict the value at points in the future. There are many specialized ways how to approach this problem. Exponential smoothing, special models like ARIMA, Prophet, and of course Neural Networks (RNN, LSTM), just to name some. But in this article, I will focus on using generic tree-based models for time series forecasting. Tree models out of the box don’t support forecasting times series on raw data. Therefore data must be first pre-processed in a special way and corresponding features have to be generated. Typical raw time series data looks as follows. There is one value for each time series step. In this particular example, this step is a day, but it could be an hour, a month, or any other time interval. We have some known training data from the past (blue color in the graph above). And we have unknown data in the future we want to forecast (yellow color in the example). For tree-based models we need many training samples with target values, but here there’s only one long line with time-series data. In order to make it usable, let’s transform it by going through all the values and taking each of them as a target for one sample and prior data points as training data as in the visualization below. It is very important not to include future data points as training data, otherwise there will be data leak and model will perform poorly on future data. Sample Python code for the reference on how to do it: SIZE = 60 #we take 2 past months here for each time-series pointCOLUMNS = ['t{}'.format(x) for x in range(SIZE)] + ['target']df_train = []for i in range(SIZE, df.shape[0]): df_train.append(df.loc[i-SIZE:i, 'value'].tolist())df_train = pd.DataFrame(df_train, columns=COLUMNS) With this, we transform time series data line with length N into a data frame (table) with (N-M) rows and M columns. Where M is our chosen length of past data points to use for each training sample (60 points = 2 months in the example above). Data table now looks as follows: Basically now it is already in a format any classical model can take as an input and produce forecasts for the target variable (next data point of time series). However, on raw data like this tree-based models won’t be able to achieve good results. It is necessary to make special features, allowing tree model to capture different components of time series like trend and seasonality. To better understand, what features we need, let’s remember the main components of time series data: base level: this is the mean value of time-series data trend: this is the change of base-level over time seasonality: these are cyclic changes repeating over some time period (week, month, year) remainder: this is everything else not covered by 3 other components. The remainder may consist of the predictable part (when changes are triggered by some external irregular event which we can observe and use in our model) and non-predictable part (basically just noise or changes triggered by events we don’t have access to). Let’s further try to capture the first three time-series components in features usable for our tree-based model. We will create features in a window-based approach, looking at N successive data points at a time. First simplest case is for window size 1. This simply means that we are taking the last value or our available training data for each sample, which is data point right before target. There’s not much we can do with just one value, so let’s add it as a feature as-is. This is a good feature as this is the most recent known data point. Drawback is that this feature will be very noisy. df_feats['prev_1'] = df_train.iloc[:,-2] #Here -2 as -1 is a target Next we take window size 2, having 2 most recent data points before target. Then window size 3 and so on. Example code snippet: for win in [2, 3, 5, 7, 10, 14, 21, 28, 56]: tmp = df_train.iloc[:,-1-win:-1] #General statistics for base level df_feats['mean_prev_{}'.format(win)] = tmp.mean(axis=1) df_feats['median_prev_{}'.format(win)] = tmp.median(axis=1) df_feats['min_prev_{}'.format(win)] = tmp.min(axis=1) df_feats['max_prev_{}'.format(win)] = tmp.max(axis=1) df_feats['std_prev_{}'.format(win)] = tmp.std(axis=1) #Capturing trend df_feats['mean_ewm_prev_{}'.format(win)] = tmp.T.ewm(com=9.5).mean().T.mean(axis=1) df_feats['last_ewm_prev_{}'.format(win)] = tmp.T.ewm(com=9.5).mean().T.iloc[:,-1] df_feats['avg_diff_{}'.format(win)] = (tmp - tmp.shift(1, axis=1)).mean(axis=1) df_feats['avg_div_{}'.format(win)] = (tmp / tmp.shift(1, axis=1)).mean(axis=1) Let’s go through the code. The first line defines window sizes used. Next for each window size, we create temporary variable tmp, with selected data points in the current window. This variable is later used to create all the features. General statistics for base level The first 5 features are general statistics — mean, median, min, max, and std. This kind of feature will help to determine the base level of time-series for different window sizes. Depending on the characteristics of time-series, some window sizes may be more important. For example: for noisy data bigger intervals are better, as they won’t be influenced by the noise so much; for data with sharp trend, smaller intervals may be better, as they will capture the latest trend better. Not always it is obvious, which window sizes to use, so it is smart to include several of them and let the model to choose itself. Capturing trend The next two lines define Exponentially Weighted Mean (EWM) features. Weighted mean differs from simple mean by giving bigger weights to more recent data points allowing to capture trend better. And the last two features will also help in capturing trend — they compute the average difference of two following data points. This allows evaluating how fast data is changing and in what direction. As with previous features group, the window size is important for trend features, too. Small windows will be able to capture fast-changing short term trends. However, there is a risk of capturing noise. There are many other features which could be helpful in predicting trend. Some ideas to mention: computing weighted mean of the difference between data points (giving more impact on trend to more recent data points); taking min, max, std, and other statistics on differences between points. computing slope of each two following data points and take the average or other statistics on them; many more. Features for seasonality So far we generated features only for the first two components of time series — base value and trend. What about seasonality? There are special features to use for this component, too. Consider the following code example: for win in [2, 3, 4, 8]: tmp = df_train.iloc[:,-1-win*7:-1:7] #7 for week #Features for weekly seasonality df_feats[‘week_mean_prev_{}’.format(win)] = tmp.mean(axis=1) df_feats[‘week_median_prev_{}’.format(win)] = tmp.median(axis=1) df_feats[‘week_min_prev_{}’.format(win)] = tmp.min(axis=1) df_feats[‘week_max_prev_{}’.format(win)] = tmp.max(axis=1) df_feats[‘week_std_prev_{}’.format(win)] = tmp.std(axis=1) Notice tmp variable in this example takes only each 7th value, therefore it contains data only for the same weekdays as the target variable. This way we are calculating statistics features specific for given weekday. If given time-series has strong weekly seasonality component, such features will be very important. We now have prepared basic features, ready to be used in a tree-based machine learning model. LightGBM model will be used as an example and code for modeling is provided below for the reference: import lightgbm as lgbparams = { 'objective': 'regression', 'metric': 'mae', 'boosting': 'gbdt', 'learning_rate': 0.06, 'num_leaves': 64, 'bagging_fraction': 0.9, 'feature_fraction': 0.9}x_train = lgb.Dataset(df_feats, df_train['target'])model = lgb.train(params, x_train, num_boost_round=500)preds = model.predict(df_feats_validation) First we import LightGBM model and prepare couple of it’s most important parameters. Then model is trained on previously prepared features from df_feats variable. Similarly features for validation period are prepared in df_feats_validation variable, which is used for obtaining predictions in preds variable. We can now plot obtained predictions to see, if it works. Predictions are far from perfect, as we used only very basic features, but still, we can notice that predictions follow the trend of real data. With more similar features and model parameters tuning, results can be improved further. In this article, I showed a generic approach on how to transform time-series data and gave example features calculated for the main time-series components. Tree-based models are not the first choice for achieving state-of-the-art accuracy on time-series data, however, they have many other good characteristics, like interpretability, simplicity, which often dictates to choose exactly these models for real time-series predictions. Thanks for reading and stay tuned for more articles about Data Science and Machine Learning.
[ { "code": null, "e": 562, "s": 172, "text": "In this article, I’m going to show a generic way how to approach a time-series prediction problem with a machine learning model. I’m using a tree-based model LightGBM as an example here, but practically it could be almost any classical machine learning model, including linear regression or some other. I’ll cover needed data transformation, basic feature engineering and, modeling itself." }, { "code": null, "e": 937, "s": 562, "text": "Time series is basically a list of values at known points in time. Some examples: daily purchases at a store, the daily number of website visitors, hourly temperature measurements, etc. Often the interval between data points is fixed, but that is not a mandatory requirement. And the problem we want to solve in a time series is to predict the value at points in the future." }, { "code": null, "e": 1218, "s": 937, "text": "There are many specialized ways how to approach this problem. Exponential smoothing, special models like ARIMA, Prophet, and of course Neural Networks (RNN, LSTM), just to name some. But in this article, I will focus on using generic tree-based models for time series forecasting." }, { "code": null, "e": 1406, "s": 1218, "text": "Tree models out of the box don’t support forecasting times series on raw data. Therefore data must be first pre-processed in a special way and corresponding features have to be generated." }, { "code": null, "e": 1453, "s": 1406, "text": "Typical raw time series data looks as follows." }, { "code": null, "e": 1779, "s": 1453, "text": "There is one value for each time series step. In this particular example, this step is a day, but it could be an hour, a month, or any other time interval. We have some known training data from the past (blue color in the graph above). And we have unknown data in the future we want to forecast (yellow color in the example)." }, { "code": null, "e": 2110, "s": 1779, "text": "For tree-based models we need many training samples with target values, but here there’s only one long line with time-series data. In order to make it usable, let’s transform it by going through all the values and taking each of them as a target for one sample and prior data points as training data as in the visualization below." }, { "code": null, "e": 2317, "s": 2110, "text": "It is very important not to include future data points as training data, otherwise there will be data leak and model will perform poorly on future data. Sample Python code for the reference on how to do it:" }, { "code": null, "e": 2595, "s": 2317, "text": "SIZE = 60 #we take 2 past months here for each time-series pointCOLUMNS = ['t{}'.format(x) for x in range(SIZE)] + ['target']df_train = []for i in range(SIZE, df.shape[0]): df_train.append(df.loc[i-SIZE:i, 'value'].tolist())df_train = pd.DataFrame(df_train, columns=COLUMNS)" }, { "code": null, "e": 2871, "s": 2595, "text": "With this, we transform time series data line with length N into a data frame (table) with (N-M) rows and M columns. Where M is our chosen length of past data points to use for each training sample (60 points = 2 months in the example above). Data table now looks as follows:" }, { "code": null, "e": 3257, "s": 2871, "text": "Basically now it is already in a format any classical model can take as an input and produce forecasts for the target variable (next data point of time series). However, on raw data like this tree-based models won’t be able to achieve good results. It is necessary to make special features, allowing tree model to capture different components of time series like trend and seasonality." }, { "code": null, "e": 3358, "s": 3257, "text": "To better understand, what features we need, let’s remember the main components of time series data:" }, { "code": null, "e": 3413, "s": 3358, "text": "base level: this is the mean value of time-series data" }, { "code": null, "e": 3463, "s": 3413, "text": "trend: this is the change of base-level over time" }, { "code": null, "e": 3553, "s": 3463, "text": "seasonality: these are cyclic changes repeating over some time period (week, month, year)" }, { "code": null, "e": 3881, "s": 3553, "text": "remainder: this is everything else not covered by 3 other components. The remainder may consist of the predictable part (when changes are triggered by some external irregular event which we can observe and use in our model) and non-predictable part (basically just noise or changes triggered by events we don’t have access to)." }, { "code": null, "e": 3994, "s": 3881, "text": "Let’s further try to capture the first three time-series components in features usable for our tree-based model." }, { "code": null, "e": 4478, "s": 3994, "text": "We will create features in a window-based approach, looking at N successive data points at a time. First simplest case is for window size 1. This simply means that we are taking the last value or our available training data for each sample, which is data point right before target. There’s not much we can do with just one value, so let’s add it as a feature as-is. This is a good feature as this is the most recent known data point. Drawback is that this feature will be very noisy." }, { "code": null, "e": 4546, "s": 4478, "text": "df_feats['prev_1'] = df_train.iloc[:,-2] #Here -2 as -1 is a target" }, { "code": null, "e": 4674, "s": 4546, "text": "Next we take window size 2, having 2 most recent data points before target. Then window size 3 and so on. Example code snippet:" }, { "code": null, "e": 5492, "s": 4674, "text": "for win in [2, 3, 5, 7, 10, 14, 21, 28, 56]: tmp = df_train.iloc[:,-1-win:-1] #General statistics for base level df_feats['mean_prev_{}'.format(win)] = tmp.mean(axis=1) df_feats['median_prev_{}'.format(win)] = tmp.median(axis=1) df_feats['min_prev_{}'.format(win)] = tmp.min(axis=1) df_feats['max_prev_{}'.format(win)] = tmp.max(axis=1) df_feats['std_prev_{}'.format(win)] = tmp.std(axis=1) #Capturing trend df_feats['mean_ewm_prev_{}'.format(win)] = tmp.T.ewm(com=9.5).mean().T.mean(axis=1) df_feats['last_ewm_prev_{}'.format(win)] = tmp.T.ewm(com=9.5).mean().T.iloc[:,-1] df_feats['avg_diff_{}'.format(win)] = (tmp - tmp.shift(1, axis=1)).mean(axis=1) df_feats['avg_div_{}'.format(win)] = (tmp / tmp.shift(1, axis=1)).mean(axis=1)" }, { "code": null, "e": 5727, "s": 5492, "text": "Let’s go through the code. The first line defines window sizes used. Next for each window size, we create temporary variable tmp, with selected data points in the current window. This variable is later used to create all the features." }, { "code": null, "e": 5761, "s": 5727, "text": "General statistics for base level" }, { "code": null, "e": 6045, "s": 5761, "text": "The first 5 features are general statistics — mean, median, min, max, and std. This kind of feature will help to determine the base level of time-series for different window sizes. Depending on the characteristics of time-series, some window sizes may be more important. For example:" }, { "code": null, "e": 6139, "s": 6045, "text": "for noisy data bigger intervals are better, as they won’t be influenced by the noise so much;" }, { "code": null, "e": 6245, "s": 6139, "text": "for data with sharp trend, smaller intervals may be better, as they will capture the latest trend better." }, { "code": null, "e": 6376, "s": 6245, "text": "Not always it is obvious, which window sizes to use, so it is smart to include several of them and let the model to choose itself." }, { "code": null, "e": 6392, "s": 6376, "text": "Capturing trend" }, { "code": null, "e": 6587, "s": 6392, "text": "The next two lines define Exponentially Weighted Mean (EWM) features. Weighted mean differs from simple mean by giving bigger weights to more recent data points allowing to capture trend better." }, { "code": null, "e": 6787, "s": 6587, "text": "And the last two features will also help in capturing trend — they compute the average difference of two following data points. This allows evaluating how fast data is changing and in what direction." }, { "code": null, "e": 6990, "s": 6787, "text": "As with previous features group, the window size is important for trend features, too. Small windows will be able to capture fast-changing short term trends. However, there is a risk of capturing noise." }, { "code": null, "e": 7087, "s": 6990, "text": "There are many other features which could be helpful in predicting trend. Some ideas to mention:" }, { "code": null, "e": 7207, "s": 7087, "text": "computing weighted mean of the difference between data points (giving more impact on trend to more recent data points);" }, { "code": null, "e": 7281, "s": 7207, "text": "taking min, max, std, and other statistics on differences between points." }, { "code": null, "e": 7381, "s": 7281, "text": "computing slope of each two following data points and take the average or other statistics on them;" }, { "code": null, "e": 7392, "s": 7381, "text": "many more." }, { "code": null, "e": 7417, "s": 7392, "text": "Features for seasonality" }, { "code": null, "e": 7639, "s": 7417, "text": "So far we generated features only for the first two components of time series — base value and trend. What about seasonality? There are special features to use for this component, too. Consider the following code example:" }, { "code": null, "e": 8070, "s": 7639, "text": "for win in [2, 3, 4, 8]: tmp = df_train.iloc[:,-1-win*7:-1:7] #7 for week #Features for weekly seasonality df_feats[‘week_mean_prev_{}’.format(win)] = tmp.mean(axis=1) df_feats[‘week_median_prev_{}’.format(win)] = tmp.median(axis=1) df_feats[‘week_min_prev_{}’.format(win)] = tmp.min(axis=1) df_feats[‘week_max_prev_{}’.format(win)] = tmp.max(axis=1) df_feats[‘week_std_prev_{}’.format(win)] = tmp.std(axis=1)" }, { "code": null, "e": 8387, "s": 8070, "text": "Notice tmp variable in this example takes only each 7th value, therefore it contains data only for the same weekdays as the target variable. This way we are calculating statistics features specific for given weekday. If given time-series has strong weekly seasonality component, such features will be very important." }, { "code": null, "e": 8582, "s": 8387, "text": "We now have prepared basic features, ready to be used in a tree-based machine learning model. LightGBM model will be used as an example and code for modeling is provided below for the reference:" }, { "code": null, "e": 8939, "s": 8582, "text": "import lightgbm as lgbparams = { 'objective': 'regression', 'metric': 'mae', 'boosting': 'gbdt', 'learning_rate': 0.06, 'num_leaves': 64, 'bagging_fraction': 0.9, 'feature_fraction': 0.9}x_train = lgb.Dataset(df_feats, df_train['target'])model = lgb.train(params, x_train, num_boost_round=500)preds = model.predict(df_feats_validation)" }, { "code": null, "e": 9306, "s": 8939, "text": "First we import LightGBM model and prepare couple of it’s most important parameters. Then model is trained on previously prepared features from df_feats variable. Similarly features for validation period are prepared in df_feats_validation variable, which is used for obtaining predictions in preds variable. We can now plot obtained predictions to see, if it works." }, { "code": null, "e": 9539, "s": 9306, "text": "Predictions are far from perfect, as we used only very basic features, but still, we can notice that predictions follow the trend of real data. With more similar features and model parameters tuning, results can be improved further." }, { "code": null, "e": 9972, "s": 9539, "text": "In this article, I showed a generic approach on how to transform time-series data and gave example features calculated for the main time-series components. Tree-based models are not the first choice for achieving state-of-the-art accuracy on time-series data, however, they have many other good characteristics, like interpretability, simplicity, which often dictates to choose exactly these models for real time-series predictions." } ]
Python: Decorators in OOP. A guide on classmethods, staticmethods... | by Aniruddha Karajgi | Towards Data Science
The Object Oriented Programming paradigm became popular in the ’60s and ‘70s, in languages like Lisp and Smalltalk. Such features were also added to existing languages like Ada, Fortran and Pascal. Python is an object oriented programming language, though it doesn’t support strong encapsulation. Introductory topics in object-oriented programming in Python — and more generally — include things like defining classes, creating objects, instance variables, the basics of inheritance, and maybe even some special methods like __str__. But when we have an advanced look, we could talk about things like the use of decorators, or writing a custom new method, metaclasses, and Multiple Inheritance. In this post, we’ll first discuss what decorators are, followed by a discussion on classmethods and staticmethods along with the property decorator. Classmethods, staticmethods and property are examples of what are called descriptors. These are objects which implement the __get__ , __set__ or __delete__ methods. But, that’s a topic for another post. We’ll talk about the following in this article: - what are decorators?- classmethods- staticmethods- @property Let’s work on a simple example: a Student class. For now, this class has two variables: name age score We’ll add a simple __init__ method to instantiate an object when these two attributes are provided. We’ll modify this as we go throughout the post. Decorators are functions (or classes) that provide enhanced functionality to the original function (or class) without the programmer having to modify their structure. A simple example? Suppose we want to add a method to our Student class that takes a student’s score and total marks and then returns a percentage. Our percent function can be defined like so: Let’s define our decorator, creatively named record_decorator. It takes a function as input and outputs another function ( wrapper , in this case). The wrapper function: takes our two arguments score and total calls the function object passed to the grade_decorator then calculates the grade that corresponding to the percent scored. Finally, it returns the calculated percentage along with the grade. We can implement our decorator like so. Now, to improve the get_percent function, just use the @ symbol with the decorator name above our function, which has exactly the same definition as before. To use this, we don’t need to modify our call statement. Executing this: get_percent(25, 100) returns 25.0, D What basically happens is that the function get_percent is replaced by wrapper when we apply the decorator. We’ll place the get_percent method inside the Student class, and place our decorator outside the class. Since get_percent is an instance method, we add a self argument to it. How are decorators used in classes? We’ll see three popular decorators used in classes and their use-cases. Let’s first talk about instance methods. Instance methods are those methods that are called by an object, and hence are passed information about that object. This is done through the self argument as a convention, and when that method is called, the object’s information is passed implicitly through self. For example, we could add a method to our class that calculates a student’s grade and percentage (using the get_percent method) and generates a report as a string with the student’s name, percentage, and grade. Coming to a class method, this type of function is called on a class, and hence, it requires a class to be passed to it. This is done with the cls argument by convention. And we also add the @classmethod decorator to our class method. It looks something like this: class A: def instance_method(self): return self @classmethod def class_method(cls): return clsA.class_method() Since class-methods work with a class, and not an instance, they can be used as part of a factory pattern, where objects are returned based on certain parameters. For example, there are multiple ways to create a Dataframe in pandas. There are methods like: from_records() , from_dict() , etc. which all return a dataframe object. Though their actual implementation is pretty complex, they basically take something like a dictionary, manipulate that and then return a dataframe object after parsing that data. Coming back to our example, let's define a few ways to create instances of our Student class. by two separate arguments: for example, <name>, 20 and 85 by a comma-separated string: for example, “<name>, 20, 85”. by a tuple: for example, (<name>, 20, 85) To accomplish this in Java, we could simply overload our constructor: In python, a clean way to do it would be through classmethods: We also define the __str__ method, so we can directly print a Student object to see if it has been instantiated properly. Our class now looks like this: Now, to test this, let’s create three Student objects, each from a different kind of data. The output is exactly as expected from the definition of the __str__ method above: Name: John Score: 25 Total : 100Name: Jack Score: 60 Total : 100Name: Jill Score: 125 Total : 200 A static method doesn’t care about an instance, like an instance method. It doesn’t require a class being passed to it implicitly. A static method is a regular method, placed inside a class. It can be called using both a class and an object. We use the @staticmethod decorator for these kinds of methods. A simple example: class A: def instance_method(self): return self @classmethod def class_method(cls): return cls @staticmethod def static_method(): returna = A()a.static_method()A.static_method() Why would this be useful? Why not just place such functions outside the class? Static methods are used instead of regular functions when it makes more sense to place the function inside the class. For example, placing utility methods that deal solely with a class or its objects is a good idea, since those methods won’t be used by anyone else. Coming to our example, we can make our get_percent method static, since it serves a general purpose and need not be bound to our objects. To do this, we can simply add @staticmethod above the get_percent method. The property decorator provides methods for accessing (getter), modifying (setter), and deleting (deleter) the attributes of an object. Let’s start with getter and setter methods. These methods are used to access and modify (respectively) a private instance. In Java, we would do something like this: Now, anytime you access or modify this value, you would use these methods. Since the variable x is private, it can’t be accessed outside JavaClass . In python, there is no private keyword. We prepend a variable by a dunder(__ ) to show that it is private and shouldn’t be accessed or modified directly. Adding a __ before a variable name modifies that variable’s name from varname to _Classname__varname , so direct access and modification like print(obj.varname) and obj.varname = 5 won’t work. Still, this isn’t very strong since you could directly replace varname with the modified form to get a direct modification to work. Let’s take the following example to understand this: Taking our Student class example, let’s make the score attribute “private” by adding a __ before the variable name. If we directly went ahead and added get_score and set_score like Java, the main issue is that if we wanted to do this to existing code, we’d have to change every access from: print("Score: " + str(student1.score))student1.score = 100 to this: print(student1.get_score())student1.set_score(100) Here’s where the @property decorator comes in. You can simply define getter, setter and deleter methods using this feature. Our class now looks like this: To make the attribute score read-only, just remove the setter method. Then, when we update score, we get the following error: Traceback (most recent call last): File "main.py", line 16, in <module> student.score = 10AttributeError: can't set attribute The deleter method lets you delete a protected or private attribute using the del function. Using the same example as before, if we directly try and delete the score attribute, we get the following error: student = Student("Tom", 50, 100)del student.scoreThis gives:Traceback (most recent call last): File "<string>", line 17, in <module>AttributeError: can't delete attribute But when we add a deleter method, we can delete our private variable score . The attribute has been successfully removed now. Printing out the value of score gives “object has no attribute...”, since we deleted it. Traceback (most recent call last): File "<string>", line 23, in <module>File "<string>", line 9, in xAttributeError: 'PythonClass' object has no attribute '__score' The property decorator is very useful when defining methods for data validation, like when deciding if a value to be assigned is valid and won’t lead to issues later in the code. Another use-case would be when wanting to display information in a specific way. Coming back to our example, if we wanted to display a student’s name as “Student Name: <name>” , instead of just <name> , we could return the first string from a property getter on the name attribute: Now, any time we access name, we get a formatted result. student = Student("Bob", 350, 500)print(student.name) The output: Student Name: Bob The property decorator can also be used for logging changes. For example, in a setter method, you could add code to log the updating of a variable. Now, whenever the setter is called, which is when the variable is modified, the change is logged. Let’s say there was a totaling error in Bob’s math exam and he ends up getting 50 more marks. student = Student("Bob", 350, 500)print(student.score)student.score = 400print(student.score) The above gives the following output, with the logged change visible: 70.0 %INFO:root:Setting new value...80.0 % Finally, our class looks like this: There are many places you could define a decorator: outside the class, in a separate class, or maybe even in an inner class (with respect to the class we are using the decorator in). In this example, we simply defined grade_decorator outside the Student class. Though this works, the decorator now has nothing to do with our class, which we may not prefer. For a more detailed discussion on this, check out this post: medium.com Apart from overloading the constructor, we could make use of static factory methods in java. We could define a static method like from_str that would extract key information from the string passed to it and then return an object. Object-oriented programming is a very important paradigm to learn and use. Regardless of whether you’ll ever need to use the topics discussed here in your next project, it’s necessary to know the basics really well. Topics like the ones in this post aren’t used all that often compared to more basic concepts — like inheritance or the basic implementation of classes and objects — on which they are built. In any case, I hope this post gave you an idea of the other kinds of methods in Python OOP (apart from instance methods) and the property decorator.
[ { "code": null, "e": 370, "s": 172, "text": "The Object Oriented Programming paradigm became popular in the ’60s and ‘70s, in languages like Lisp and Smalltalk. Such features were also added to existing languages like Ada, Fortran and Pascal." }, { "code": null, "e": 469, "s": 370, "text": "Python is an object oriented programming language, though it doesn’t support strong encapsulation." }, { "code": null, "e": 867, "s": 469, "text": "Introductory topics in object-oriented programming in Python — and more generally — include things like defining classes, creating objects, instance variables, the basics of inheritance, and maybe even some special methods like __str__. But when we have an advanced look, we could talk about things like the use of decorators, or writing a custom new method, metaclasses, and Multiple Inheritance." }, { "code": null, "e": 1016, "s": 867, "text": "In this post, we’ll first discuss what decorators are, followed by a discussion on classmethods and staticmethods along with the property decorator." }, { "code": null, "e": 1181, "s": 1016, "text": "Classmethods, staticmethods and property are examples of what are called descriptors. These are objects which implement the __get__ , __set__ or __delete__ methods." }, { "code": null, "e": 1219, "s": 1181, "text": "But, that’s a topic for another post." }, { "code": null, "e": 1267, "s": 1219, "text": "We’ll talk about the following in this article:" }, { "code": null, "e": 1330, "s": 1267, "text": "- what are decorators?- classmethods- staticmethods- @property" }, { "code": null, "e": 1379, "s": 1330, "text": "Let’s work on a simple example: a Student class." }, { "code": null, "e": 1418, "s": 1379, "text": "For now, this class has two variables:" }, { "code": null, "e": 1423, "s": 1418, "text": "name" }, { "code": null, "e": 1427, "s": 1423, "text": "age" }, { "code": null, "e": 1433, "s": 1427, "text": "score" }, { "code": null, "e": 1533, "s": 1433, "text": "We’ll add a simple __init__ method to instantiate an object when these two attributes are provided." }, { "code": null, "e": 1581, "s": 1533, "text": "We’ll modify this as we go throughout the post." }, { "code": null, "e": 1748, "s": 1581, "text": "Decorators are functions (or classes) that provide enhanced functionality to the original function (or class) without the programmer having to modify their structure." }, { "code": null, "e": 1766, "s": 1748, "text": "A simple example?" }, { "code": null, "e": 1895, "s": 1766, "text": "Suppose we want to add a method to our Student class that takes a student’s score and total marks and then returns a percentage." }, { "code": null, "e": 1940, "s": 1895, "text": "Our percent function can be defined like so:" }, { "code": null, "e": 2088, "s": 1940, "text": "Let’s define our decorator, creatively named record_decorator. It takes a function as input and outputs another function ( wrapper , in this case)." }, { "code": null, "e": 2110, "s": 2088, "text": "The wrapper function:" }, { "code": null, "e": 2150, "s": 2110, "text": "takes our two arguments score and total" }, { "code": null, "e": 2206, "s": 2150, "text": "calls the function object passed to the grade_decorator" }, { "code": null, "e": 2274, "s": 2206, "text": "then calculates the grade that corresponding to the percent scored." }, { "code": null, "e": 2342, "s": 2274, "text": "Finally, it returns the calculated percentage along with the grade." }, { "code": null, "e": 2382, "s": 2342, "text": "We can implement our decorator like so." }, { "code": null, "e": 2539, "s": 2382, "text": "Now, to improve the get_percent function, just use the @ symbol with the decorator name above our function, which has exactly the same definition as before." }, { "code": null, "e": 2612, "s": 2539, "text": "To use this, we don’t need to modify our call statement. Executing this:" }, { "code": null, "e": 2633, "s": 2612, "text": "get_percent(25, 100)" }, { "code": null, "e": 2641, "s": 2633, "text": "returns" }, { "code": null, "e": 2649, "s": 2641, "text": "25.0, D" }, { "code": null, "e": 2757, "s": 2649, "text": "What basically happens is that the function get_percent is replaced by wrapper when we apply the decorator." }, { "code": null, "e": 2932, "s": 2757, "text": "We’ll place the get_percent method inside the Student class, and place our decorator outside the class. Since get_percent is an instance method, we add a self argument to it." }, { "code": null, "e": 2968, "s": 2932, "text": "How are decorators used in classes?" }, { "code": null, "e": 3040, "s": 2968, "text": "We’ll see three popular decorators used in classes and their use-cases." }, { "code": null, "e": 3346, "s": 3040, "text": "Let’s first talk about instance methods. Instance methods are those methods that are called by an object, and hence are passed information about that object. This is done through the self argument as a convention, and when that method is called, the object’s information is passed implicitly through self." }, { "code": null, "e": 3557, "s": 3346, "text": "For example, we could add a method to our class that calculates a student’s grade and percentage (using the get_percent method) and generates a report as a string with the student’s name, percentage, and grade." }, { "code": null, "e": 3792, "s": 3557, "text": "Coming to a class method, this type of function is called on a class, and hence, it requires a class to be passed to it. This is done with the cls argument by convention. And we also add the @classmethod decorator to our class method." }, { "code": null, "e": 3822, "s": 3792, "text": "It looks something like this:" }, { "code": null, "e": 3956, "s": 3822, "text": "class A: def instance_method(self): return self @classmethod def class_method(cls): return clsA.class_method()" }, { "code": null, "e": 4119, "s": 3956, "text": "Since class-methods work with a class, and not an instance, they can be used as part of a factory pattern, where objects are returned based on certain parameters." }, { "code": null, "e": 4465, "s": 4119, "text": "For example, there are multiple ways to create a Dataframe in pandas. There are methods like: from_records() , from_dict() , etc. which all return a dataframe object. Though their actual implementation is pretty complex, they basically take something like a dictionary, manipulate that and then return a dataframe object after parsing that data." }, { "code": null, "e": 4559, "s": 4465, "text": "Coming back to our example, let's define a few ways to create instances of our Student class." }, { "code": null, "e": 4617, "s": 4559, "text": "by two separate arguments: for example, <name>, 20 and 85" }, { "code": null, "e": 4677, "s": 4617, "text": "by a comma-separated string: for example, “<name>, 20, 85”." }, { "code": null, "e": 4719, "s": 4677, "text": "by a tuple: for example, (<name>, 20, 85)" }, { "code": null, "e": 4789, "s": 4719, "text": "To accomplish this in Java, we could simply overload our constructor:" }, { "code": null, "e": 4852, "s": 4789, "text": "In python, a clean way to do it would be through classmethods:" }, { "code": null, "e": 5005, "s": 4852, "text": "We also define the __str__ method, so we can directly print a Student object to see if it has been instantiated properly. Our class now looks like this:" }, { "code": null, "e": 5096, "s": 5005, "text": "Now, to test this, let’s create three Student objects, each from a different kind of data." }, { "code": null, "e": 5179, "s": 5096, "text": "The output is exactly as expected from the definition of the __str__ method above:" }, { "code": null, "e": 5277, "s": 5179, "text": "Name: John Score: 25 Total : 100Name: Jack Score: 60 Total : 100Name: Jill Score: 125 Total : 200" }, { "code": null, "e": 5408, "s": 5277, "text": "A static method doesn’t care about an instance, like an instance method. It doesn’t require a class being passed to it implicitly." }, { "code": null, "e": 5582, "s": 5408, "text": "A static method is a regular method, placed inside a class. It can be called using both a class and an object. We use the @staticmethod decorator for these kinds of methods." }, { "code": null, "e": 5600, "s": 5582, "text": "A simple example:" }, { "code": null, "e": 5814, "s": 5600, "text": "class A: def instance_method(self): return self @classmethod def class_method(cls): return cls @staticmethod def static_method(): returna = A()a.static_method()A.static_method()" }, { "code": null, "e": 5893, "s": 5814, "text": "Why would this be useful? Why not just place such functions outside the class?" }, { "code": null, "e": 6159, "s": 5893, "text": "Static methods are used instead of regular functions when it makes more sense to place the function inside the class. For example, placing utility methods that deal solely with a class or its objects is a good idea, since those methods won’t be used by anyone else." }, { "code": null, "e": 6371, "s": 6159, "text": "Coming to our example, we can make our get_percent method static, since it serves a general purpose and need not be bound to our objects. To do this, we can simply add @staticmethod above the get_percent method." }, { "code": null, "e": 6507, "s": 6371, "text": "The property decorator provides methods for accessing (getter), modifying (setter), and deleting (deleter) the attributes of an object." }, { "code": null, "e": 6672, "s": 6507, "text": "Let’s start with getter and setter methods. These methods are used to access and modify (respectively) a private instance. In Java, we would do something like this:" }, { "code": null, "e": 6821, "s": 6672, "text": "Now, anytime you access or modify this value, you would use these methods. Since the variable x is private, it can’t be accessed outside JavaClass ." }, { "code": null, "e": 6975, "s": 6821, "text": "In python, there is no private keyword. We prepend a variable by a dunder(__ ) to show that it is private and shouldn’t be accessed or modified directly." }, { "code": null, "e": 7300, "s": 6975, "text": "Adding a __ before a variable name modifies that variable’s name from varname to _Classname__varname , so direct access and modification like print(obj.varname) and obj.varname = 5 won’t work. Still, this isn’t very strong since you could directly replace varname with the modified form to get a direct modification to work." }, { "code": null, "e": 7353, "s": 7300, "text": "Let’s take the following example to understand this:" }, { "code": null, "e": 7469, "s": 7353, "text": "Taking our Student class example, let’s make the score attribute “private” by adding a __ before the variable name." }, { "code": null, "e": 7644, "s": 7469, "text": "If we directly went ahead and added get_score and set_score like Java, the main issue is that if we wanted to do this to existing code, we’d have to change every access from:" }, { "code": null, "e": 7704, "s": 7644, "text": "print(\"Score: \" + str(student1.score))student1.score = 100" }, { "code": null, "e": 7713, "s": 7704, "text": "to this:" }, { "code": null, "e": 7764, "s": 7713, "text": "print(student1.get_score())student1.set_score(100)" }, { "code": null, "e": 7888, "s": 7764, "text": "Here’s where the @property decorator comes in. You can simply define getter, setter and deleter methods using this feature." }, { "code": null, "e": 7919, "s": 7888, "text": "Our class now looks like this:" }, { "code": null, "e": 7989, "s": 7919, "text": "To make the attribute score read-only, just remove the setter method." }, { "code": null, "e": 8045, "s": 7989, "text": "Then, when we update score, we get the following error:" }, { "code": null, "e": 8175, "s": 8045, "text": "Traceback (most recent call last): File \"main.py\", line 16, in <module> student.score = 10AttributeError: can't set attribute" }, { "code": null, "e": 8380, "s": 8175, "text": "The deleter method lets you delete a protected or private attribute using the del function. Using the same example as before, if we directly try and delete the score attribute, we get the following error:" }, { "code": null, "e": 8553, "s": 8380, "text": "student = Student(\"Tom\", 50, 100)del student.scoreThis gives:Traceback (most recent call last): File \"<string>\", line 17, in <module>AttributeError: can't delete attribute" }, { "code": null, "e": 8630, "s": 8553, "text": "But when we add a deleter method, we can delete our private variable score ." }, { "code": null, "e": 8768, "s": 8630, "text": "The attribute has been successfully removed now. Printing out the value of score gives “object has no attribute...”, since we deleted it." }, { "code": null, "e": 8934, "s": 8768, "text": "Traceback (most recent call last): File \"<string>\", line 23, in <module>File \"<string>\", line 9, in xAttributeError: 'PythonClass' object has no attribute '__score'" }, { "code": null, "e": 9113, "s": 8934, "text": "The property decorator is very useful when defining methods for data validation, like when deciding if a value to be assigned is valid and won’t lead to issues later in the code." }, { "code": null, "e": 9395, "s": 9113, "text": "Another use-case would be when wanting to display information in a specific way. Coming back to our example, if we wanted to display a student’s name as “Student Name: <name>” , instead of just <name> , we could return the first string from a property getter on the name attribute:" }, { "code": null, "e": 9452, "s": 9395, "text": "Now, any time we access name, we get a formatted result." }, { "code": null, "e": 9506, "s": 9452, "text": "student = Student(\"Bob\", 350, 500)print(student.name)" }, { "code": null, "e": 9518, "s": 9506, "text": "The output:" }, { "code": null, "e": 9536, "s": 9518, "text": "Student Name: Bob" }, { "code": null, "e": 9597, "s": 9536, "text": "The property decorator can also be used for logging changes." }, { "code": null, "e": 9684, "s": 9597, "text": "For example, in a setter method, you could add code to log the updating of a variable." }, { "code": null, "e": 9876, "s": 9684, "text": "Now, whenever the setter is called, which is when the variable is modified, the change is logged. Let’s say there was a totaling error in Bob’s math exam and he ends up getting 50 more marks." }, { "code": null, "e": 9970, "s": 9876, "text": "student = Student(\"Bob\", 350, 500)print(student.score)student.score = 400print(student.score)" }, { "code": null, "e": 10040, "s": 9970, "text": "The above gives the following output, with the logged change visible:" }, { "code": null, "e": 10083, "s": 10040, "text": "70.0 %INFO:root:Setting new value...80.0 %" }, { "code": null, "e": 10119, "s": 10083, "text": "Finally, our class looks like this:" }, { "code": null, "e": 10476, "s": 10119, "text": "There are many places you could define a decorator: outside the class, in a separate class, or maybe even in an inner class (with respect to the class we are using the decorator in). In this example, we simply defined grade_decorator outside the Student class. Though this works, the decorator now has nothing to do with our class, which we may not prefer." }, { "code": null, "e": 10537, "s": 10476, "text": "For a more detailed discussion on this, check out this post:" }, { "code": null, "e": 10548, "s": 10537, "text": "medium.com" }, { "code": null, "e": 10778, "s": 10548, "text": "Apart from overloading the constructor, we could make use of static factory methods in java. We could define a static method like from_str that would extract key information from the string passed to it and then return an object." } ]
Python 3 - Number tan() Method
The tan() method returns the tangent of x radians. Following is the syntax for tan() method − tan(x) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This must be a numeric value. This method returns a numeric value between -1 and 1, which represents the tangent of the parameter x. The following example shows the usage of tan() method. #!/usr/bin/python3 import math print ("(tan(3) : ", math.tan(3)) print ("tan(-3) : ", math.tan(-3)) print ("tan(0) : ", math.tan(0)) print ("tan(math.pi) : ", math.tan(math.pi)) print ("tan(math.pi/2) : ", math.tan(math.pi/2)) print ("tan(math.pi/4) : ", math.tan(math.pi/4)) When we run the above program, it produces the following result − (tan(3) : -0.1425465430742778 tan(-3) : 0.1425465430742778 tan(0) : 0.0 tan(math.pi) : -1.2246467991473532e-16 tan(math.pi/2) : 1.633123935319537e+16 tan(math.pi/4) : 0.9999999999999999 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2391, "s": 2340, "text": "The tan() method returns the tangent of x radians." }, { "code": null, "e": 2434, "s": 2391, "text": "Following is the syntax for tan() method −" }, { "code": null, "e": 2442, "s": 2434, "text": "tan(x)\n" }, { "code": null, "e": 2589, "s": 2442, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2623, "s": 2589, "text": "x − This must be a numeric value." }, { "code": null, "e": 2726, "s": 2623, "text": "This method returns a numeric value between -1 and 1, which represents the tangent of the parameter x." }, { "code": null, "e": 2781, "s": 2726, "text": "The following example shows the usage of tan() method." }, { "code": null, "e": 3064, "s": 2781, "text": "#!/usr/bin/python3\nimport math\n\nprint (\"(tan(3) : \", math.tan(3))\nprint (\"tan(-3) : \", math.tan(-3))\nprint (\"tan(0) : \", math.tan(0))\nprint (\"tan(math.pi) : \", math.tan(math.pi))\nprint (\"tan(math.pi/2) : \", math.tan(math.pi/2))\nprint (\"tan(math.pi/4) : \", math.tan(math.pi/4))" }, { "code": null, "e": 3130, "s": 3064, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3323, "s": 3130, "text": "(tan(3) : -0.1425465430742778\ntan(-3) : 0.1425465430742778\ntan(0) : 0.0\ntan(math.pi) : -1.2246467991473532e-16\ntan(math.pi/2) : 1.633123935319537e+16\ntan(math.pi/4) : 0.9999999999999999\n" }, { "code": null, "e": 3360, "s": 3323, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3376, "s": 3360, "text": " Malhar Lathkar" }, { "code": null, "e": 3409, "s": 3376, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3428, "s": 3409, "text": " Arnab Chakraborty" }, { "code": null, "e": 3463, "s": 3428, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3485, "s": 3463, "text": " In28Minutes Official" }, { "code": null, "e": 3519, "s": 3485, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3547, "s": 3519, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3582, "s": 3547, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3596, "s": 3582, "text": " Lets Kode It" }, { "code": null, "e": 3629, "s": 3596, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3646, "s": 3629, "text": " Abhilash Nelson" }, { "code": null, "e": 3653, "s": 3646, "text": " Print" }, { "code": null, "e": 3664, "s": 3653, "text": " Add Notes" } ]
Flutter - LayoutBuilder Widget - GeeksforGeeks
24 Jan, 2021 In Flutter, LayoutBuilder Widget is similar to the Builder widget except that the framework calls the builder function at layout time and provides the parent widget’s constraints. This is useful when the parent constrains the child’s size and doesn’t depend on the child’s intrinsic size. The LayoutBuilder’s final size will match its child’s size. The builder function is called in the following situations: The first time the widget is laid out. When the parent widget passes different layout constraints. When the parent widget updates this widget. When the dependencies that the builder function subscribes to change. Syntax: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Widget(); } ) Click to learn about BoxConstraints. Example 1: Using the parent’s constraints to calculate the child’s constraints. Most common use case of LayoutBuilder Widget. Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), body: Container( color: Colors.red, /// Giving dimensions to parent Container /// using MediaQuery /// [container's height] = [(phone's height) / 2] /// [container's width] = [phone's width] height: MediaQuery.of(context).size.height * 0.5, width: MediaQuery.of(context).size.width, /// Aligning contents of this Container /// to center alignment: Alignment.center, child: LayoutBuilder( builder: (BuildContext ctx, BoxConstraints constraints) { return Container( color: Colors.green, /// Aligning contents of this Container /// to center alignment: Alignment.center, /// Using parent's constraints /// to calculate child's height and width height: constraints.maxHeight * 0.5, width: constraints.maxWidth * 0.5, child: Text( 'LayoutBuilder Widget', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ); }, ), ), ), ); }} Output: Example 2: We can also use LayoutBuilder Widget to display different UI’s for different screen sizes. Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), body: Container( /// Giving dimensions to parent Container /// using MediaQuery /// [container's height] = [(phone's height) / 2] /// [container's width] = [phone's width] height: MediaQuery.of(context).size.height * 0.5, width: MediaQuery.of(context).size.width, /// Aligning contents of this Container /// to center alignment: Alignment.center, child: LayoutBuilder( builder: (BuildContext ctx, BoxConstraints constraints) { // if the screen width >= 480 i.e Wide Screen if (constraints.maxWidth >= 480) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( padding: const EdgeInsets.symmetric(horizontal: 8), alignment: Alignment.center, height: constraints.maxHeight * 0.5, color: Colors.red, child: Text( 'Left Part of Wide Screen', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8), alignment: Alignment.center, height: constraints.maxHeight * 0.5, color: Colors.green, child: Text( 'Right Part of Wide Screen', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ], ); // If screen size is < 480 } else { return Container( alignment: Alignment.center, height: constraints.maxHeight * 0.5, color: Colors.green, child: Text( 'Normal Screen', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ); } }, ), ), ), ); }} Output: android Flutter Flutter-widgets Picked Technical Scripter 2020 Dart Flutter Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Flutter - Flexible Widget ListView Class in Flutter Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Format Dates in Flutter
[ { "code": null, "e": 23619, "s": 23591, "text": "\n24 Jan, 2021" }, { "code": null, "e": 23968, "s": 23619, "text": "In Flutter, LayoutBuilder Widget is similar to the Builder widget except that the framework calls the builder function at layout time and provides the parent widget’s constraints. This is useful when the parent constrains the child’s size and doesn’t depend on the child’s intrinsic size. The LayoutBuilder’s final size will match its child’s size." }, { "code": null, "e": 24028, "s": 23968, "text": "The builder function is called in the following situations:" }, { "code": null, "e": 24067, "s": 24028, "text": "The first time the widget is laid out." }, { "code": null, "e": 24127, "s": 24067, "text": "When the parent widget passes different layout constraints." }, { "code": null, "e": 24171, "s": 24127, "text": "When the parent widget updates this widget." }, { "code": null, "e": 24241, "s": 24171, "text": "When the dependencies that the builder function subscribes to change." }, { "code": null, "e": 24249, "s": 24241, "text": "Syntax:" }, { "code": null, "e": 24355, "s": 24249, "text": "LayoutBuilder(\n builder: (BuildContext context, BoxConstraints constraints) {\n return Widget();\n }\n)" }, { "code": null, "e": 24392, "s": 24355, "text": "Click to learn about BoxConstraints." }, { "code": null, "e": 24518, "s": 24392, "text": "Example 1: Using the parent’s constraints to calculate the child’s constraints. Most common use case of LayoutBuilder Widget." }, { "code": null, "e": 24523, "s": 24518, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), body: Container( color: Colors.red, /// Giving dimensions to parent Container /// using MediaQuery /// [container's height] = [(phone's height) / 2] /// [container's width] = [phone's width] height: MediaQuery.of(context).size.height * 0.5, width: MediaQuery.of(context).size.width, /// Aligning contents of this Container /// to center alignment: Alignment.center, child: LayoutBuilder( builder: (BuildContext ctx, BoxConstraints constraints) { return Container( color: Colors.green, /// Aligning contents of this Container /// to center alignment: Alignment.center, /// Using parent's constraints /// to calculate child's height and width height: constraints.maxHeight * 0.5, width: constraints.maxWidth * 0.5, child: Text( 'LayoutBuilder Widget', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ); }, ), ), ), ); }}", "e": 26418, "s": 24523, "text": null }, { "code": null, "e": 26426, "s": 26418, "text": "Output:" }, { "code": null, "e": 26528, "s": 26426, "text": "Example 2: We can also use LayoutBuilder Widget to display different UI’s for different screen sizes." }, { "code": null, "e": 26533, "s": 26528, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), body: Container( /// Giving dimensions to parent Container /// using MediaQuery /// [container's height] = [(phone's height) / 2] /// [container's width] = [phone's width] height: MediaQuery.of(context).size.height * 0.5, width: MediaQuery.of(context).size.width, /// Aligning contents of this Container /// to center alignment: Alignment.center, child: LayoutBuilder( builder: (BuildContext ctx, BoxConstraints constraints) { // if the screen width >= 480 i.e Wide Screen if (constraints.maxWidth >= 480) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( padding: const EdgeInsets.symmetric(horizontal: 8), alignment: Alignment.center, height: constraints.maxHeight * 0.5, color: Colors.red, child: Text( 'Left Part of Wide Screen', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8), alignment: Alignment.center, height: constraints.maxHeight * 0.5, color: Colors.green, child: Text( 'Right Part of Wide Screen', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ], ); // If screen size is < 480 } else { return Container( alignment: Alignment.center, height: constraints.maxHeight * 0.5, color: Colors.green, child: Text( 'Normal Screen', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white, ), ), ); } }, ), ), ), ); }}", "e": 29729, "s": 26533, "text": null }, { "code": null, "e": 29737, "s": 29729, "text": "Output:" }, { "code": null, "e": 29745, "s": 29737, "text": "android" }, { "code": null, "e": 29753, "s": 29745, "text": "Flutter" }, { "code": null, "e": 29769, "s": 29753, "text": "Flutter-widgets" }, { "code": null, "e": 29776, "s": 29769, "text": "Picked" }, { "code": null, "e": 29800, "s": 29776, "text": "Technical Scripter 2020" }, { "code": null, "e": 29805, "s": 29800, "text": "Dart" }, { "code": null, "e": 29813, "s": 29805, "text": "Flutter" }, { "code": null, "e": 29832, "s": 29813, "text": "Technical Scripter" }, { "code": null, "e": 29930, "s": 29832, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29939, "s": 29930, "text": "Comments" }, { "code": null, "e": 29952, "s": 29939, "text": "Old Comments" }, { "code": null, "e": 29991, "s": 29952, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30017, "s": 29991, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 30043, "s": 30017, "text": "ListView Class in Flutter" }, { "code": null, "e": 30066, "s": 30043, "text": "Flutter - Stack Widget" }, { "code": null, "e": 30111, "s": 30066, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 30150, "s": 30111, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30167, "s": 30150, "text": "Flutter Tutorial" }, { "code": null, "e": 30193, "s": 30167, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 30216, "s": 30193, "text": "Flutter - Stack Widget" } ]
How to initialize const member variable in a C++ class?
Here we will see how to initialize the const type member variable using constructor? To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma. #include <iostream> using namespace std; class MyClass{ private: const int x; public: MyClass(int a) : x(a){ //constructor } void show_x(){ cout << "Value of constant x: " << x ; } }; int main() { MyClass ob1(40); ob1.show_x(); } Value of constant x: 40
[ { "code": null, "e": 1147, "s": 1062, "text": "Here we will see how to initialize the const type member variable using constructor?" }, { "code": null, "e": 1441, "s": 1147, "text": "To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma." }, { "code": null, "e": 1716, "s": 1441, "text": "#include <iostream>\nusing namespace std;\nclass MyClass{\n private:\n const int x;\n public:\n MyClass(int a) : x(a){\n //constructor\n }\n void show_x(){\n cout << \"Value of constant x: \" << x ;\n }\n};\nint main() {\n MyClass ob1(40);\n ob1.show_x();\n}" }, { "code": null, "e": 1740, "s": 1716, "text": "Value of constant x: 40" } ]
JavaScript algorithm for converting integers to roman numbers
Let’s say, we are required to write a function, say intToRoman(), which, as the name suggests, returns a Roman equivalent of the number passed in it as an argument. Let’s write the code for this function − const intToRoman = (num) => { let result = ""; while(num){ if(num>=1000){ result += "M"; num -= 1000; }else if(num>=500){ if(num>=900){ result += "CM"; num -= 900; }else{ result += "D"; num -= 500; } }else if(num>=100){ if(num>=400){ result += "CD"; num -= 400; }else{ result += "C"; num -= 100; } }else if(num>=50){ if(num>=90){ result += "XC"; num -= 90; }else{ result += "L"; num -= 50; } }else if(num>=10){ if(num>=40){ result += "XL"; num -= 40; }else{ result += "X"; num -= 10; } }else if(num>=5){ if(num>=9){ result += "IX"; num -= 9; }else{ result += "V"; num -= 5; } }else{ if(num>=4){ result += "IV"; num -= 4; }else{ result += "I"; num -= 1; } } } return result; }; console.log(intToRoman(178)); console.log(intToRoman(89)); console.log(intToRoman(55)); console.log(intToRoman(1555)); The output for this code in the console will be − CLXXVIII LXXXIX LV MDLV
[ { "code": null, "e": 1227, "s": 1062, "text": "Let’s say, we are required to write a function, say intToRoman(), which, as the name suggests,\nreturns a Roman equivalent of the number passed in it as an argument." }, { "code": null, "e": 1268, "s": 1227, "text": "Let’s write the code for this function −" }, { "code": null, "e": 2699, "s": 1268, "text": "const intToRoman = (num) => {\n let result = \"\";\n while(num){\n if(num>=1000){\n result += \"M\";\n num -= 1000;\n }else if(num>=500){\n if(num>=900){\n result += \"CM\";\n num -= 900;\n }else{\n result += \"D\";\n num -= 500;\n }\n }else if(num>=100){\n if(num>=400){\n result += \"CD\";\n num -= 400;\n }else{\n result += \"C\";\n num -= 100;\n }\n }else if(num>=50){\n if(num>=90){\n result += \"XC\";\n num -= 90;\n }else{\n result += \"L\";\n num -= 50;\n }\n }else if(num>=10){\n if(num>=40){\n result += \"XL\";\n num -= 40;\n }else{\n result += \"X\";\n num -= 10;\n }\n }else if(num>=5){\n if(num>=9){\n result += \"IX\";\n num -= 9;\n }else{\n result += \"V\";\n num -= 5;\n }\n }else{\n if(num>=4){\n result += \"IV\";\n num -= 4;\n }else{\n result += \"I\";\n num -= 1;\n }\n }\n }\n return result;\n};\nconsole.log(intToRoman(178));\nconsole.log(intToRoman(89));\nconsole.log(intToRoman(55));\nconsole.log(intToRoman(1555));" }, { "code": null, "e": 2749, "s": 2699, "text": "The output for this code in the console will be −" }, { "code": null, "e": 2773, "s": 2749, "text": "CLXXVIII\nLXXXIX\nLV\nMDLV" } ]
Read file line by line using C++
This is a C++ program to read file line by line. tpoint.txt is having initial content as “Tutorials point.” Tutorials point. Begin Create an object newfile against the class fstream. Call open() method to open a file “tpoint.txt” to perform write operation using object newfile. If file is open then Input a string “Tutorials point" in the tpoint.txt file. Close the file object newfile using close() method. Call open() method to open a file “tpoint.txt” to perform read operation using object newfile. If file is open then Declare a string “tp”. Read all data of file object newfile using getline() method and put it into the string tp. Print the data of string tp. Close the file object newfile using close() method. End. #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ fstream newfile; newfile.open("tpoint.txt",ios::out); // open a file to perform write operation using file object if(newfile.is_open()) //checking whether the file is open { newfile<<"Tutorials point \n"; //inserting text newfile.close(); //close the file object } newfile.open("tpoint.txt",ios::in); //open a file to perform read operation using file object if (newfile.is_open()){ //checking whether the file is open string tp; while(getline(newfile, tp)){ //read data from file object and put it into string. cout << tp << "\n"; //print the data of the string } newfile.close(); //close the file object. } } Tutorials point.
[ { "code": null, "e": 1111, "s": 1062, "text": "This is a C++ program to read file line by line." }, { "code": null, "e": 1170, "s": 1111, "text": "tpoint.txt is having initial content as\n“Tutorials point.”" }, { "code": null, "e": 1187, "s": 1170, "text": "Tutorials point." }, { "code": null, "e": 1832, "s": 1187, "text": "Begin\n Create an object newfile against the class fstream.\n Call open() method to open a file “tpoint.txt” to perform write operation using object newfile.\n If file is open then\n Input a string “Tutorials point\" in the tpoint.txt file.\n Close the file object newfile using close() method.\n Call open() method to open a file “tpoint.txt” to perform read operation using object newfile.\n If file is open then\n Declare a string “tp”.\n Read all data of file object newfile using getline() method and put it into the string tp.\n Print the data of string tp.\nClose the file object newfile using close() method.\nEnd." }, { "code": null, "e": 2610, "s": 1832, "text": "#include <iostream>\n#include <fstream>\n#include <string>\nusing namespace std;\nint main(){\n fstream newfile;\n newfile.open(\"tpoint.txt\",ios::out); // open a file to perform write operation using file object\n if(newfile.is_open()) //checking whether the file is open\n {\n newfile<<\"Tutorials point \\n\"; //inserting text\n newfile.close(); //close the file object\n }\n newfile.open(\"tpoint.txt\",ios::in); //open a file to perform read operation using file object\n if (newfile.is_open()){ //checking whether the file is open\n string tp;\n while(getline(newfile, tp)){ //read data from file object and put it into string.\n cout << tp << \"\\n\"; //print the data of the string\n }\n newfile.close(); //close the file object.\n }\n}" }, { "code": null, "e": 2627, "s": 2610, "text": "Tutorials point." } ]
Program to determine color of a chessboard square using Python
Suppose we have a chessboard coordinate, that is a string that represents the coordinates of row and column of the chessboard. Below is a chessboard for your reference. We have to check whether given cell is white or not, if white return true, otherwise return false. So, if the input is like coordinate = "f5", then the output will be True (See the image) To solve this, we will follow these steps − if ASCII of coordinate[0] mod 2 is same coordinate[1]) mod 2, thenreturn False if ASCII of coordinate[0] mod 2 is same coordinate[1]) mod 2, then return False return False otherwise,return True otherwise, return True return True Let us see the following implementation to get better understanding − Live Demo def solve(coordinate): if (ord(coordinate[0]))%2 == int(coordinate[1])%2: return False else: return True coordinate = "f5" print(solve(coordinate)) "f5" True
[ { "code": null, "e": 1231, "s": 1062, "text": "Suppose we have a chessboard coordinate, that is a string that represents the coordinates of row and column of the chessboard. Below is a chessboard for your reference." }, { "code": null, "e": 1330, "s": 1231, "text": "We have to check whether given cell is white or not, if white return true, otherwise return false." }, { "code": null, "e": 1419, "s": 1330, "text": "So, if the input is like coordinate = \"f5\", then the output will be True (See the image)" }, { "code": null, "e": 1463, "s": 1419, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1542, "s": 1463, "text": "if ASCII of coordinate[0] mod 2 is same coordinate[1]) mod 2, thenreturn False" }, { "code": null, "e": 1609, "s": 1542, "text": "if ASCII of coordinate[0] mod 2 is same coordinate[1]) mod 2, then" }, { "code": null, "e": 1622, "s": 1609, "text": "return False" }, { "code": null, "e": 1635, "s": 1622, "text": "return False" }, { "code": null, "e": 1657, "s": 1635, "text": "otherwise,return True" }, { "code": null, "e": 1668, "s": 1657, "text": "otherwise," }, { "code": null, "e": 1680, "s": 1668, "text": "return True" }, { "code": null, "e": 1692, "s": 1680, "text": "return True" }, { "code": null, "e": 1762, "s": 1692, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1773, "s": 1762, "text": " Live Demo" }, { "code": null, "e": 1939, "s": 1773, "text": "def solve(coordinate):\n if (ord(coordinate[0]))%2 == int(coordinate[1])%2:\n return False\n else:\n return True\ncoordinate = \"f5\"\nprint(solve(coordinate))" }, { "code": null, "e": 1944, "s": 1939, "text": "\"f5\"" }, { "code": null, "e": 1949, "s": 1944, "text": "True" } ]
Getting Started with NLP for Indic Languages | by Sundar V | Towards Data Science
Want to go beyond English and use the real power of Natural Language Processing (NLP) to serve the second-most populous country in the world? Everyone knows India is a very diverse country and a home for lots of languages but do you know India speaks 780 languages [1]. It’s time to go beyond English when it comes to NLP. This article is for those who somewhat know about NLP and want to start using it for Indian languages. Before going into the topic, we will glance at some essential concepts and recent accomplishments in NLP. NLP helps computers in understanding human language. Text Classification, Information Extraction, Semantic Parsing, Question Answering, Text Summarization, Machine Translation, and Conversational Agents are some applications of NLP. For computers to understand human language, we initially need to represent the words in numeric form. Numerically represented words can then be utilized by machine learning models to do any NLP task. Traditionally, methods like One Hot Encoding, TF-IDF Representation were used to describe the text as numbers. But the traditional methods resulted in sparse representation by failing to capture the word meaning. Neural Word Embeddings then came to rescue by solving the problems in traditional methods. Word2Vec and GloVe are the two most commonly used word embedding. These methods came up with dense representations where words having similar meaning will have similar representations. A significant weakness with this method is words are considered to have a single meaning. But we know that a word can have multiple meaning depending on the context where it is used. NLP took a major leap by the modern family of language models (AI’s Muppet Empire). Word embedding is no longer independent of context. The same word can have multiple numeric representations depending on the context where it is used. BERT, ELMo, ULMFit, GPT-2 are some currently popular language models. The latest generation is so good, and some people consider it dangerous [3]. The news written by these language models were even rated as credible as the New York Times by the readers [4]. To know more about language models, I would highly recommend reading [2]. Will now go into the topic by getting word embedding for Indic languages. Numerically representing words plays a role in any NLP task. We are going to use the Natural Language Toolkit for Indic Languages (iNLTK) library. iNLTK is an open-source Deep Learning library built on top of PyTorch aiming to provide out of the box support for various NLP tasks that an application developer might need for Indic languages. ULMFiT language models were used to build iNLTK [6]. iNLTK was trending on GitHub in May 2019 and has had 23,000+ Downloads on PyPi [5]. We are using iNLTK here because of its simplicity and support for many Indic languages. iNLTK currently supports the below 12 Indic languages. Please follow this link to install iNLTK. Using iNLTK, we can quickly get the embedding vectors for sentences written in Indic languages. Below is an example that shows how we can get the embedding vectors for a sentence written in Hindi. Given sentence will be broken into tokens, and each token will be represented using a (400 x 1) vector. A token can be a word, or it can be a sub-word. Since tokens can be sub words, we can get a meaningful vector representation for rare words too. # Example 1 - Get Embedding Vectorsfrom inltk.inltk import setupfrom inltk.inltk import tokenizefrom inltk.inltk import get_embedding_vectors'''Note: You need to run setup('<code-of-language>') when you use a language for the FIRST TIME ONLY.This will download all the necessary models required to do inference for that language.'''setup('hi')example_sent = "बहुत समय से मिले नहीं"# Tokenize the sentenceexample_sent_tokens = tokenize(example_sent,'hi')# Get the embedding vector for each tokenexample_sent_vectors = get_embedding_vectors(example_sent, 'hi')print("Tokens:", example_sent_tokens)print("Number of vectors:", len(example_sent_vectors))print("Shape of each vector:", len(example_sent_vectors[0])) Output: Tokens: ['▁बहुत', '▁समय', '▁से', '▁मिले', '▁नहीं ']Number of vectors: 5Shape of each vector: 400 Now that we got the word embeddings, many might wonder how good these numerical representations are? Do similar tokens have similar descriptions? We can get answers to all those questions using the visualizations provided for every language. For example, as shown below, all neighboring tokens to ‘प्रेम’ (love) are closely related to love, affection, wedding, etc. As I said earlier, numerically represented natural language can be used by machine learning models to do many NLP tasks. Apart from that, we can immediately use iNLTK for numerous NLP tasks. For instance, we can use iNLTK to predict next ’n’ words, get similar sentences, get sentence encoding, identify language, etc. In below example, We will be using iNLTK to predict next ’n’ words, and to get similar sentences. For an input like “It’s been a long time since we met” in Tamil, we get a prediction for next ’n’ words as “And, due to this”. And the results for similar sentences task is also impressive. # Example 2 - Predict Next 'n' Words, Get Similar Sentencesfrom inltk.inltk import setupfrom inltk.inltk import predict_next_wordsfrom inltk.inltk import get_similar_sentences'''Note: You need to run setup('<code-of-language>') when you use a language for the FIRST TIME ONLY.This will download all the necessary models required to do inference for that language.'''setup('ta')example_sent = "உங்களைப் பார்த்து நிறைய நாட்கள் ஆகிவிட்டது"# Predict next 'n' tokensn = 5pred_sent = predict_next_words(example_sent, n, 'ta')# Get 'n' similar sentencen = 2simi_sent = get_similar_sentences(example_sent, n, 'ta')print("Predicted Words:", pred_sent)print("Similar Sentences:", simi_sent) Output: Predicted Words: உங்களைப் பார்த்து நிறைய நாட்கள் ஆகிவிட்டது. மேலும், இதற்கு காரணமாகSimilar Sentences: ['உங்களைத் பார்த்து நாட்கள் ஆகிவிட்டது ', 'உங்களைப் பார்த்து ஏராளமான நாட்கள் ஆகிவிட்டது '] As I said, in the beginning, it’s time to go beyond English and use the real power of NLP to serve everyone. Lots of research in recent terms are focused on multilingual NLP. iNLTK is one such library that concentrates on Indic languages. Today you can contribute to iNLTK by adding support to a new language, improving existing models, and adding new functionalities. Apart from iNLTK, I will recommend looking into multilingual models [7], Indic NLP [8]. Don’t forget that everything you just came across is just the tip of the iceberg. Before concluding this article, I want to add in a few words expressing iNLTK’s vision from its creator. I always wished for something like it to exist, which will make NLP more accessible and democratize its benefits to non-English speakers. iNLTK kind of grew organically and now, since it is being appreciated a lot, I see there’s a lot still left to be done. My vision for iNLTK is that it should be the go-to library for anyone working with low-resource languages. — Gaurav Arora, Creator of iNLTK. [1] http://blogs.reuters.com/india/2013/09/07/india-speaks-780-languages-220-lost-in-last-50-years-survey/[2] https://towardsdatascience.com/from-word-embeddings-to-pretrained-language-models-a-new-age-in-nlp-part-1-7ed0c7f3dfc5[3] https://blog.deeplearning.ai/blog/the-batch-biggest-ai-stories-of-2019-driverless-cars-stall-deepfakes-go-mainstream-face-recognition-gets-banned[4] https://www.foreignaffairs.com/articles/2019-08-02/not-your-fathers-bots[5] https://github.com/goru001/inltk[6] https://in.pycon.org/cfp/2019/proposals/natural-language-toolkit-for-indic-languages-inltk~eZQ6d/[7] https://huggingface.co/transformers/multilingual.html[8] https://anoopkunchukuttan.github.io/indic_nlp_library/
[ { "code": null, "e": 598, "s": 172, "text": "Want to go beyond English and use the real power of Natural Language Processing (NLP) to serve the second-most populous country in the world? Everyone knows India is a very diverse country and a home for lots of languages but do you know India speaks 780 languages [1]. It’s time to go beyond English when it comes to NLP. This article is for those who somewhat know about NLP and want to start using it for Indian languages." }, { "code": null, "e": 937, "s": 598, "text": "Before going into the topic, we will glance at some essential concepts and recent accomplishments in NLP. NLP helps computers in understanding human language. Text Classification, Information Extraction, Semantic Parsing, Question Answering, Text Summarization, Machine Translation, and Conversational Agents are some applications of NLP." }, { "code": null, "e": 1350, "s": 937, "text": "For computers to understand human language, we initially need to represent the words in numeric form. Numerically represented words can then be utilized by machine learning models to do any NLP task. Traditionally, methods like One Hot Encoding, TF-IDF Representation were used to describe the text as numbers. But the traditional methods resulted in sparse representation by failing to capture the word meaning." }, { "code": null, "e": 1809, "s": 1350, "text": "Neural Word Embeddings then came to rescue by solving the problems in traditional methods. Word2Vec and GloVe are the two most commonly used word embedding. These methods came up with dense representations where words having similar meaning will have similar representations. A significant weakness with this method is words are considered to have a single meaning. But we know that a word can have multiple meaning depending on the context where it is used." }, { "code": null, "e": 2303, "s": 1809, "text": "NLP took a major leap by the modern family of language models (AI’s Muppet Empire). Word embedding is no longer independent of context. The same word can have multiple numeric representations depending on the context where it is used. BERT, ELMo, ULMFit, GPT-2 are some currently popular language models. The latest generation is so good, and some people consider it dangerous [3]. The news written by these language models were even rated as credible as the New York Times by the readers [4]." }, { "code": null, "e": 2377, "s": 2303, "text": "To know more about language models, I would highly recommend reading [2]." }, { "code": null, "e": 2930, "s": 2377, "text": "Will now go into the topic by getting word embedding for Indic languages. Numerically representing words plays a role in any NLP task. We are going to use the Natural Language Toolkit for Indic Languages (iNLTK) library. iNLTK is an open-source Deep Learning library built on top of PyTorch aiming to provide out of the box support for various NLP tasks that an application developer might need for Indic languages. ULMFiT language models were used to build iNLTK [6]. iNLTK was trending on GitHub in May 2019 and has had 23,000+ Downloads on PyPi [5]." }, { "code": null, "e": 3115, "s": 2930, "text": "We are using iNLTK here because of its simplicity and support for many Indic languages. iNLTK currently supports the below 12 Indic languages. Please follow this link to install iNLTK." }, { "code": null, "e": 3561, "s": 3115, "text": "Using iNLTK, we can quickly get the embedding vectors for sentences written in Indic languages. Below is an example that shows how we can get the embedding vectors for a sentence written in Hindi. Given sentence will be broken into tokens, and each token will be represented using a (400 x 1) vector. A token can be a word, or it can be a sub-word. Since tokens can be sub words, we can get a meaningful vector representation for rare words too." }, { "code": null, "e": 4271, "s": 3561, "text": "# Example 1 - Get Embedding Vectorsfrom inltk.inltk import setupfrom inltk.inltk import tokenizefrom inltk.inltk import get_embedding_vectors'''Note: You need to run setup('<code-of-language>') when you use a language for the FIRST TIME ONLY.This will download all the necessary models required to do inference for that language.'''setup('hi')example_sent = \"बहुत समय से मिले नहीं\"# Tokenize the sentenceexample_sent_tokens = tokenize(example_sent,'hi')# Get the embedding vector for each tokenexample_sent_vectors = get_embedding_vectors(example_sent, 'hi')print(\"Tokens:\", example_sent_tokens)print(\"Number of vectors:\", len(example_sent_vectors))print(\"Shape of each vector:\", len(example_sent_vectors[0]))" }, { "code": null, "e": 4279, "s": 4271, "text": "Output:" }, { "code": null, "e": 4376, "s": 4279, "text": "Tokens: ['▁बहुत', '▁समय', '▁से', '▁मिले', '▁नहीं ']Number of vectors: 5Shape of each vector: 400" }, { "code": null, "e": 4742, "s": 4376, "text": "Now that we got the word embeddings, many might wonder how good these numerical representations are? Do similar tokens have similar descriptions? We can get answers to all those questions using the visualizations provided for every language. For example, as shown below, all neighboring tokens to ‘प्रेम’ (love) are closely related to love, affection, wedding, etc." }, { "code": null, "e": 5061, "s": 4742, "text": "As I said earlier, numerically represented natural language can be used by machine learning models to do many NLP tasks. Apart from that, we can immediately use iNLTK for numerous NLP tasks. For instance, we can use iNLTK to predict next ’n’ words, get similar sentences, get sentence encoding, identify language, etc." }, { "code": null, "e": 5349, "s": 5061, "text": "In below example, We will be using iNLTK to predict next ’n’ words, and to get similar sentences. For an input like “It’s been a long time since we met” in Tamil, we get a prediction for next ’n’ words as “And, due to this”. And the results for similar sentences task is also impressive." }, { "code": null, "e": 6030, "s": 5349, "text": "# Example 2 - Predict Next 'n' Words, Get Similar Sentencesfrom inltk.inltk import setupfrom inltk.inltk import predict_next_wordsfrom inltk.inltk import get_similar_sentences'''Note: You need to run setup('<code-of-language>') when you use a language for the FIRST TIME ONLY.This will download all the necessary models required to do inference for that language.'''setup('ta')example_sent = \"உங்களைப் பார்த்து நிறைய நாட்கள் ஆகிவிட்டது\"# Predict next 'n' tokensn = 5pred_sent = predict_next_words(example_sent, n, 'ta')# Get 'n' similar sentencen = 2simi_sent = get_similar_sentences(example_sent, n, 'ta')print(\"Predicted Words:\", pred_sent)print(\"Similar Sentences:\", simi_sent)" }, { "code": null, "e": 6038, "s": 6030, "text": "Output:" }, { "code": null, "e": 6231, "s": 6038, "text": "Predicted Words: உங்களைப் பார்த்து நிறைய நாட்கள் ஆகிவிட்டது. மேலும், இதற்கு காரணமாகSimilar Sentences: ['உங்களைத் பார்த்து நாட்கள் ஆகிவிட்டது ', 'உங்களைப் பார்த்து ஏராளமான நாட்கள் ஆகிவிட்டது ']" }, { "code": null, "e": 6875, "s": 6231, "text": "As I said, in the beginning, it’s time to go beyond English and use the real power of NLP to serve everyone. Lots of research in recent terms are focused on multilingual NLP. iNLTK is one such library that concentrates on Indic languages. Today you can contribute to iNLTK by adding support to a new language, improving existing models, and adding new functionalities. Apart from iNLTK, I will recommend looking into multilingual models [7], Indic NLP [8]. Don’t forget that everything you just came across is just the tip of the iceberg. Before concluding this article, I want to add in a few words expressing iNLTK’s vision from its creator." }, { "code": null, "e": 7274, "s": 6875, "text": "I always wished for something like it to exist, which will make NLP more accessible and democratize its benefits to non-English speakers. iNLTK kind of grew organically and now, since it is being appreciated a lot, I see there’s a lot still left to be done. My vision for iNLTK is that it should be the go-to library for anyone working with low-resource languages. — Gaurav Arora, Creator of iNLTK." } ]
How can we initialize a boolean array in Java?
The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays.fill() method in such cases. boolean[] booleanArray; import java.util.Arrays; public class BooleanArrayTest { public static void main(String[] args) { Boolean[] boolArray = new Boolean[5]; // initialize a boolean array for(int i = 0; i < boolArray.length; i++) { System.out.println(boolArray[i]); } Arrays.fill(boolArray, Boolean.FALSE); // all the values will be false for(int i = 0; i < boolArray.length; i++) { System.out.println(boolArray[i]); } Arrays.fill(boolArray, Boolean.TRUE); // all the values will be true for (int i = 0; i < boolArray.length; i++) { System.out.println(boolArray[i]); } } } null null null null null false false false false false true true true true true
[ { "code": null, "e": 1424, "s": 1062, "text": "The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays.fill() method in such cases." }, { "code": null, "e": 1448, "s": 1424, "text": "boolean[] booleanArray;" }, { "code": null, "e": 2098, "s": 1448, "text": "import java.util.Arrays;\npublic class BooleanArrayTest {\n public static void main(String[] args) {\n Boolean[] boolArray = new Boolean[5]; // initialize a boolean array\n for(int i = 0; i < boolArray.length; i++) {\n System.out.println(boolArray[i]);\n }\n Arrays.fill(boolArray, Boolean.FALSE);\n // all the values will be false\n for(int i = 0; i < boolArray.length; i++) {\n System.out.println(boolArray[i]);\n }\n Arrays.fill(boolArray, Boolean.TRUE);\n // all the values will be true\n for (int i = 0; i < boolArray.length; i++) {\n System.out.println(boolArray[i]);\n }\n }\n}" }, { "code": null, "e": 2178, "s": 2098, "text": "null\nnull\nnull\nnull\nnull\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\ntrue\ntrue\ntrue\ntrue" } ]
SymPy - Derivative
The derivative of a function is its instantaneous rate of change with respect to one of its variables. This is equivalent to finding the slope of the tangent line to the function at a point.we can find the differentiation of mathematical expressions in the form of variables by using diff() function in SymPy package. diff(expr, variable) >>> from sympy import diff, sin, exp >>> from sympy.abc import x,y >>> expr=x*sin(x*x)+1 >>> expr The above code snippet gives an output equivalent to the below expression − xsin⁡(x2)+1 >>> diff(expr,x) The above code snippet gives an output equivalent to the below expression − 2x2cos⁡(x2)+sin⁡(x2) >>> diff(exp(x**2),x) The above code snippet gives an output equivalent to the below expression − 2xex2 To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable. >>> diff(x**4,x,3) The above code snippet gives an output equivalent to the below expression − 24x >>> for i in range(1,4): print (diff(x**4,x,i)) The above code snippet gives the below expression − 4*x**3 12*x**2 24*x It is also possible to call diff() method of an expression. It works similarly as diff() function. >>> expr=x*sin(x*x)+1 >>> expr.diff(x) The above code snippet gives an output equivalent to the below expression − 2x2cos⁡(x2)+sin⁡(x2) An unevaluated derivative is created by using the Derivative class. It has the same syntax as diff() function. To evaluate an unevaluated derivative, use the doit method. >>> from sympy import Derivative >>> d=Derivative(expr) >>> d The above code snippet gives an output equivalent to the below expression − ddx(xsin⁡(x2)+1) >>> d.doit() The above code snippet gives an output equivalent to the below expression − 2x2cos⁡(x2)+sin⁡(x2) Print Add Notes Bookmark this page
[ { "code": null, "e": 2337, "s": 2019, "text": "The derivative of a function is its instantaneous rate of change with respect to one of its variables. This is equivalent to finding the slope of the tangent line to the function at a point.we can find the differentiation of mathematical expressions in the form of variables by using diff() function in SymPy package." }, { "code": null, "e": 2459, "s": 2337, "text": "diff(expr, variable)\n>>> from sympy import diff, sin, exp \n>>> from sympy.abc import x,y \n>>> expr=x*sin(x*x)+1 >>> expr\n" }, { "code": null, "e": 2535, "s": 2459, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 2547, "s": 2535, "text": "xsin⁡(x2)+1" }, { "code": null, "e": 2565, "s": 2547, "text": ">>> diff(expr,x)\n" }, { "code": null, "e": 2641, "s": 2565, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 2662, "s": 2641, "text": "2x2cos⁡(x2)+sin⁡(x2)" }, { "code": null, "e": 2685, "s": 2662, "text": ">>> diff(exp(x**2),x)\n" }, { "code": null, "e": 2761, "s": 2685, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 2767, "s": 2761, "text": "2xex2" }, { "code": null, "e": 2896, "s": 2767, "text": "To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable." }, { "code": null, "e": 2916, "s": 2896, "text": ">>> diff(x**4,x,3)\n" }, { "code": null, "e": 2992, "s": 2916, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 2996, "s": 2992, "text": "24x" }, { "code": null, "e": 3045, "s": 2996, "text": ">>> for i in range(1,4): print (diff(x**4,x,i))\n" }, { "code": null, "e": 3097, "s": 3045, "text": "The above code snippet gives the below expression −" }, { "code": null, "e": 3104, "s": 3097, "text": "4*x**3" }, { "code": null, "e": 3112, "s": 3104, "text": "12*x**2" }, { "code": null, "e": 3117, "s": 3112, "text": "24*x" }, { "code": null, "e": 3216, "s": 3117, "text": "It is also possible to call diff() method of an expression. It works similarly as diff() function." }, { "code": null, "e": 3257, "s": 3216, "text": ">>> expr=x*sin(x*x)+1 \n>>> expr.diff(x)\n" }, { "code": null, "e": 3333, "s": 3257, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 3354, "s": 3333, "text": "2x2cos⁡(x2)+sin⁡(x2)" }, { "code": null, "e": 3525, "s": 3354, "text": "An unevaluated derivative is created by using the Derivative class. It has the same syntax as diff() function. To evaluate an unevaluated derivative, use the doit method." }, { "code": null, "e": 3590, "s": 3525, "text": ">>> from sympy import Derivative \n>>> d=Derivative(expr) \n>>> d\n" }, { "code": null, "e": 3666, "s": 3590, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 3683, "s": 3666, "text": "ddx(xsin⁡(x2)+1)" }, { "code": null, "e": 3697, "s": 3683, "text": ">>> d.doit()\n" }, { "code": null, "e": 3773, "s": 3697, "text": "The above code snippet gives an output equivalent to the below expression −" }, { "code": null, "e": 3794, "s": 3773, "text": "2x2cos⁡(x2)+sin⁡(x2)" }, { "code": null, "e": 3801, "s": 3794, "text": " Print" }, { "code": null, "e": 3812, "s": 3801, "text": " Add Notes" } ]
Working with Display Block in CSS
The CSS Display property with value block renders an element with parent’s full width available, it also forces a line break. An element with display as block renders as a <div> or <p> element. Following is the syntax of CSS display block − Selector { display: block; } Let’s see an example of CSS display block − Live Demo <!DOCTYPE html> <html> <head> <title>CSS Display Block</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } em{ background-color: #C303C3; color: #fff; display:block; } </style> </head> <body> <form> <fieldset> <legend>CSS-Display-Block</legend> <label for="textSelect">Formatter: </label> <input id="textSelect" type="text" placeholder="John Doe"> <input type="button" onclick="convertItalic()" value="Check"> <div id="divDisplay"></div> </fieldset> </form> <script> var divDisplay = document.getElementById("divDisplay"); var textSelect = document.getElementById("textSelect"); function convertItalic() { for(i=0; i<2; i++){ var italicObject = document.createElement("EM"); var italicText = document.createTextNode(textSelect.value); italicObject.appendChild(italicText); divDisplay.appendChild(italicObject); } } </script> </body> </html> This will produce the following output − Before clicking ‘Check’ button − After clicking ‘Check’ button − Let’s see another example of CSS Display block − Live Demo <!DOCTYPE html> <html> <head> <style> #flex { display: flex; } #none { display: none; } .inline-block { display: inline-block; background-color: mintcream; } .grid { display: grid; background-color: cornflowerblue; } div { margin: 30px; padding: 5px; height: 10px; line-height: 5px; text-align: center; background-color: lightblue; border: 2px solid black; } div > div { background-color: lightpink; border: 2px solid green; } div > div > div { background-color: sandybrown; border: 2px solid darkred; } </style> </head> <body> <div><span id="flex">heyyy</span> <div><span id="none">heyyy</span> <div> <span class="inline-block">heyyy</span> <span class="inline-block">heyyy</span> <div> <span class="grid">heyyy demo</span> <span class="grid">heyyy demo</span> </div> </div> </div> </div> </body> </html> This will produce the following output −
[ { "code": null, "e": 1256, "s": 1062, "text": "The CSS Display property with value block renders an element with parent’s full width available, it also forces a line break. An element with display as block renders as a <div> or <p> element." }, { "code": null, "e": 1303, "s": 1256, "text": "Following is the syntax of CSS display block −" }, { "code": null, "e": 1335, "s": 1303, "text": "Selector {\n display: block;\n}" }, { "code": null, "e": 1379, "s": 1335, "text": "Let’s see an example of CSS display block −" }, { "code": null, "e": 1390, "s": 1379, "text": " Live Demo" }, { "code": null, "e": 2386, "s": 1390, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Display Block</title>\n<style>\nform {\n width:70%;\n margin: 0 auto;\n text-align: center;\n}\n* {\n padding: 2px;\n margin:5px;\n}\ninput[type=\"button\"] {\n border-radius: 10px;\n}\nem{\n background-color: #C303C3;\n color: #fff;\n display:block;\n}\n</style>\n</head>\n<body>\n<form>\n<fieldset>\n<legend>CSS-Display-Block</legend>\n<label for=\"textSelect\">Formatter: </label>\n<input id=\"textSelect\" type=\"text\" placeholder=\"John Doe\">\n<input type=\"button\" onclick=\"convertItalic()\" value=\"Check\">\n<div id=\"divDisplay\"></div>\n</fieldset>\n</form>\n<script>\nvar divDisplay = document.getElementById(\"divDisplay\");\nvar textSelect = document.getElementById(\"textSelect\");\nfunction convertItalic() {\n for(i=0; i<2; i++){\n var italicObject = document.createElement(\"EM\");\n var italicText = document.createTextNode(textSelect.value);\n italicObject.appendChild(italicText);\n divDisplay.appendChild(italicObject);\n }\n}\n</script>\n</body>\n</html>" }, { "code": null, "e": 2427, "s": 2386, "text": "This will produce the following output −" }, { "code": null, "e": 2460, "s": 2427, "text": "Before clicking ‘Check’ button −" }, { "code": null, "e": 2492, "s": 2460, "text": "After clicking ‘Check’ button −" }, { "code": null, "e": 2541, "s": 2492, "text": "Let’s see another example of CSS Display block −" }, { "code": null, "e": 2552, "s": 2541, "text": " Live Demo" }, { "code": null, "e": 3409, "s": 2552, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n#flex {\n display: flex;\n}\n#none {\n display: none;\n}\n.inline-block {\n display: inline-block;\n background-color: mintcream;\n}\n.grid {\n display: grid;\n background-color: cornflowerblue;\n}\ndiv {\n margin: 30px;\n padding: 5px;\n height: 10px;\n line-height: 5px;\n text-align: center;\n background-color: lightblue;\n border: 2px solid black;\n}\ndiv > div {\n background-color: lightpink;\n border: 2px solid green;\n}\ndiv > div > div {\n background-color: sandybrown;\n border: 2px solid darkred;\n}\n</style>\n</head>\n<body>\n<div><span id=\"flex\">heyyy</span>\n<div><span id=\"none\">heyyy</span>\n<div>\n<span class=\"inline-block\">heyyy</span>\n<span class=\"inline-block\">heyyy</span>\n<div>\n<span class=\"grid\">heyyy demo</span>\n<span class=\"grid\">heyyy demo</span>\n</div>\n</div>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 3450, "s": 3409, "text": "This will produce the following output −" } ]
How to map keys to values for an individual field in a MySQL select query?
You can use CASE statement in MySQL to map keys to values for an individual field in select query. The syntax is as follows − SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N ( CASE WHEN yourColumnName = 1 THEN 'ENABLED' ELSE 'DISABLED' END ) AS anyVariableName FROM yourTableName; You can use IF() function also for the same purpose. The syntax is as follows − SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N ,IF(yourColumnName,'ENABLED','DISABLED') as anyVariableName FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table MapKeys -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> isActive boolean, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.65 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into MapKeys(Name,isActive) values('Larry',true); Query OK, 1 row affected (0.13 sec) mysql> insert into MapKeys(Name,isActive) values('David',false); Query OK, 1 row affected (0.16 sec) mysql> insert into MapKeys(Name,isActive) values('Mike',true); Query OK, 1 row affected (0.14 sec) mysql> insert into MapKeys(Name,isActive) values('Carol',false); Query OK, 1 row affected (0.17 sec) mysql> insert into MapKeys(Name,isActive) values('Sam',false); Query OK, 1 row affected (0.15 sec) mysql> insert into MapKeys(Name,isActive) values('Bob',true); Query OK, 1 row affected (0.19 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from MapKeys; The following is the output − +----+-------+----------+ | Id | Name | isActive | +----+-------+----------+ | 1 | Larry | 1 | | 2 | David | 0 | | 3 | Mike | 1 | | 4 | Carol | 0 | | 5 | Sam | 0 | | 6 | Bob | 1 | +----+-------+----------+ 6 rows in set (0.00 sec) Let us now map key using case statement. The query is as follows − mysql> select Id,Name, -> ( -> CASE WHEN isActive = 1 THEN 'ENABLED' -> ELSE 'DISABLED' -> END -> ) AS Status -> from MapKeys; The following is the output − +----+-------+----------+ | Id | Name | Status | +----+-------+----------+ | 1 | Larry | ENABLED | | 2 | David | DISABLED | | 3 | Mike | ENABLED | | 4 | Carol | DISABLED | | 5 | Sam | DISABLED | | 6 | Bob | ENABLED | +----+-------+----------+ 6 rows in set (0.00 sec) You can achieve the same with the help of IF() function − mysql> select Id,Name,if(isActive,'ENABLED','DISABLED') as Status from MapKeys; The following is the output − +----+-------+----------+ | Id | Name | Status | +----+-------+----------+ | 1 | Larry | ENABLED | | 2 | David | DISABLED | | 3 | Mike | ENABLED | | 4 | Carol | DISABLED | | 5 | Sam | DISABLED | | 6 | Bob | ENABLED | +----+-------+----------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1188, "s": 1062, "text": "You can use CASE statement in MySQL to map keys to values for an individual field in select query. The syntax is as follows −" }, { "code": null, "e": 1370, "s": 1188, "text": "SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N\n(\n CASE WHEN yourColumnName = 1 THEN 'ENABLED'\n ELSE 'DISABLED'\n END\n) AS anyVariableName\nFROM yourTableName;" }, { "code": null, "e": 1450, "s": 1370, "text": "You can use IF() function also for the same purpose. The syntax is as follows −" }, { "code": null, "e": 1596, "s": 1450, "text": "SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N\n,IF(yourColumnName,'ENABLED','DISABLED') as anyVariableName FROM yourTableName;" }, { "code": null, "e": 1695, "s": 1596, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1885, "s": 1695, "text": "mysql> create table MapKeys\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(20),\n -> isActive boolean,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.65 sec)" }, { "code": null, "e": 1966, "s": 1885, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2569, "s": 1966, "text": "mysql> insert into MapKeys(Name,isActive) values('Larry',true);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into MapKeys(Name,isActive) values('David',false);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into MapKeys(Name,isActive) values('Mike',true);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into MapKeys(Name,isActive) values('Carol',false);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into MapKeys(Name,isActive) values('Sam',false);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into MapKeys(Name,isActive) values('Bob',true);\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 2653, "s": 2569, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2682, "s": 2653, "text": "mysql> select *from MapKeys;" }, { "code": null, "e": 2712, "s": 2682, "text": "The following is the output −" }, { "code": null, "e": 2997, "s": 2712, "text": "+----+-------+----------+\n| Id | Name | isActive |\n+----+-------+----------+\n| 1 | Larry | 1 |\n| 2 | David | 0 |\n| 3 | Mike | 1 |\n| 4 | Carol | 0 |\n| 5 | Sam | 0 |\n| 6 | Bob | 1 |\n+----+-------+----------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3064, "s": 2997, "text": "Let us now map key using case statement. The query is as follows −" }, { "code": null, "e": 3209, "s": 3064, "text": "mysql> select Id,Name,\n -> (\n -> CASE WHEN isActive = 1 THEN 'ENABLED'\n -> ELSE 'DISABLED'\n -> END\n -> ) AS Status\n -> from MapKeys;" }, { "code": null, "e": 3239, "s": 3209, "text": "The following is the output −" }, { "code": null, "e": 3524, "s": 3239, "text": "+----+-------+----------+\n| Id | Name | Status |\n+----+-------+----------+\n| 1 | Larry | ENABLED |\n| 2 | David | DISABLED |\n| 3 | Mike | ENABLED |\n| 4 | Carol | DISABLED |\n| 5 | Sam | DISABLED |\n| 6 | Bob | ENABLED |\n+----+-------+----------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3582, "s": 3524, "text": "You can achieve the same with the help of IF() function −" }, { "code": null, "e": 3662, "s": 3582, "text": "mysql> select Id,Name,if(isActive,'ENABLED','DISABLED') as Status from MapKeys;" }, { "code": null, "e": 3692, "s": 3662, "text": "The following is the output −" }, { "code": null, "e": 3972, "s": 3692, "text": "+----+-------+----------+\n| Id | Name | Status |\n+----+-------+----------+\n| 1 | Larry | ENABLED |\n| 2 | David | DISABLED |\n| 3 | Mike | ENABLED |\n| 4 | Carol | DISABLED |\n| 5 | Sam | DISABLED |\n| 6 | Bob | ENABLED |\n+----+-------+----------+\n6 rows in set (0.00 sec)" } ]
Why the t.test returns a smallest p-value of 2.2e – 16 in R?
When we perform a t test in R and the difference between two groups is very large then the p-value of the test is printed as 2.2e – 16 which is a printing behaviour of R for hypothesis testing procedures. The actual p-value can be extracted by using the t test function as t.test(“Var1”,”Var2”,var.equal=FALSE)$p.value. This p-value is not likely to be the same as 2.2e – 16. Live Demo > x1<-1:100 > y1<-100001:110000 > t.test(x1,y1,var.equal=FALSE) Welch Two Sample t-test data: x1 and y1 t = -3617.2, df = 10098, p-value < 2.2e-16 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -105006.9 -104893.1 sample estimates: mean of x mean of y 50.5 105000.5 > t.test(x1,y1,var.equal=FALSE)$p.value [1] 0 Live Demo > x2<-sample(1:10,50,replace=TRUE) > y2<-sample(500:510,replace=TRUE) > t.test(x2,y2,var.equal=FALSE) Welch Two Sample t-test data: x2 and y2 t = -427.61, df = 12.789, p-value < 2.2e-16 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -500.4179 -495.3785 sample estimates: mean of x mean of y 5.9200 503.8182 > t.test(x2,y2,var.equal=FALSE)$p.value [1] 5.881324e-28 Live Demo > x3<-sample(101:110,50,replace=TRUE) > y3<-sample(1001:1010,50,replace=TRUE) > t.test(x3,y3,var.equal=FALSE) Welch Two Sample t-test data: x3 and y3 t = -1730.7, df = 97.907, p-value < 2.2e-16 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -901.4725 -899.4075 sample estimates: mean of x mean of y 105.38 1005.82 > t.test(x3,y3,var.equal=FALSE)$p.value [1] 2.07048e-221 Live Demo > x4<-sample(1001:1010,50,replace=TRUE) > y4<-sample(100001:1000010,50) > t.test(x4,y4,var.equal=FALSE) Welch Two Sample t-test data: x4 and y4 t = -14.798, df = 49, p-value < 2.2e-16 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -620129.5 -471835.6 sample estimates: mean of x mean of y 1005.6 546988.1 > t.test(x4,y4,var.equal=FALSE)$p.value [1] 1.043251e-19
[ { "code": null, "e": 1438, "s": 1062, "text": "When we perform a t test in R and the difference between two groups is very large then the p-value of the test is printed as 2.2e – 16 which is a printing behaviour of R for hypothesis testing procedures. The actual p-value can be extracted by using the t test function as t.test(“Var1”,”Var2”,var.equal=FALSE)$p.value. This p-value is not likely to be the same as 2.2e – 16." }, { "code": null, "e": 1449, "s": 1438, "text": " Live Demo" }, { "code": null, "e": 1513, "s": 1449, "text": "> x1<-1:100\n> y1<-100001:110000\n> t.test(x1,y1,var.equal=FALSE)" }, { "code": null, "e": 1773, "s": 1513, "text": " Welch Two Sample t-test\ndata: x1 and y1\nt = -3617.2, df = 10098, p-value < 2.2e-16\nalternative hypothesis: true difference in means is not equal to 0\n95 percent confidence interval:\n-105006.9 -104893.1\nsample estimates:\nmean of x mean of y\n 50.5 105000.5" }, { "code": null, "e": 1819, "s": 1773, "text": "> t.test(x1,y1,var.equal=FALSE)$p.value\n[1] 0" }, { "code": null, "e": 1830, "s": 1819, "text": " Live Demo" }, { "code": null, "e": 1932, "s": 1830, "text": "> x2<-sample(1:10,50,replace=TRUE)\n> y2<-sample(500:510,replace=TRUE)\n> t.test(x2,y2,var.equal=FALSE)" }, { "code": null, "e": 2195, "s": 1932, "text": " Welch Two Sample t-test\ndata: x2 and y2\nt = -427.61, df = 12.789, p-value < 2.2e-16\nalternative hypothesis: true difference in means is not equal to 0\n95 percent confidence interval:\n-500.4179 -495.3785\nsample estimates:\nmean of x mean of y\n 5.9200 503.8182" }, { "code": null, "e": 2252, "s": 2195, "text": "> t.test(x2,y2,var.equal=FALSE)$p.value\n[1] 5.881324e-28" }, { "code": null, "e": 2263, "s": 2252, "text": " Live Demo" }, { "code": null, "e": 2373, "s": 2263, "text": "> x3<-sample(101:110,50,replace=TRUE)\n> y3<-sample(1001:1010,50,replace=TRUE)\n> t.test(x3,y3,var.equal=FALSE)" }, { "code": null, "e": 2635, "s": 2373, "text": " Welch Two Sample t-test\ndata: x3 and y3\nt = -1730.7, df = 97.907, p-value < 2.2e-16\nalternative hypothesis: true difference in means is not equal to 0\n95 percent confidence interval:\n-901.4725 -899.4075\nsample estimates:\nmean of x mean of y\n 105.38 1005.82" }, { "code": null, "e": 2692, "s": 2635, "text": "> t.test(x3,y3,var.equal=FALSE)$p.value\n[1] 2.07048e-221" }, { "code": null, "e": 2703, "s": 2692, "text": " Live Demo" }, { "code": null, "e": 2807, "s": 2703, "text": "> x4<-sample(1001:1010,50,replace=TRUE)\n> y4<-sample(100001:1000010,50)\n> t.test(x4,y4,var.equal=FALSE)" }, { "code": null, "e": 3066, "s": 2807, "text": " Welch Two Sample t-test\ndata: x4 and y4\nt = -14.798, df = 49, p-value < 2.2e-16\nalternative hypothesis: true difference in means is not equal to 0\n95 percent confidence interval:\n-620129.5 -471835.6\nsample estimates:\nmean of x mean of y\n 1005.6 546988.1" }, { "code": null, "e": 3123, "s": 3066, "text": "> t.test(x4,y4,var.equal=FALSE)$p.value\n[1] 1.043251e-19" } ]
std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
06 Jul, 2017 Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header <iostream>. std::fixed – Fixed Floating-point notation : It write floating-point values in fixed-point notation. The value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.std::scientific – Scientific floating-point notation : It writes floating-point values in Scientific-point notation. The value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter “e” followed by an optional sign and three exponential digits.std::hexfloat – Hexfloat floating-point notation : It outputs the desired number after the conversion into hexadecimal format after the precision of no. is initialized ( as discussed in prev. cases ).std::defaultfloat – defaultfloat floating-point notation : It outputs the desired number same as default after the precision of no. is initialized ( as discussed in prev. cases ). It is mainly used to distinguish among other used formats for understandability of code.// C++ code to demonstrate the // working of // std::fixed// std::scientific// std::hexfloat// std::defaultfloat #include <iostream> using namespace std;int main(){ // Initializing floating point variable double a = 4.223234232; double b = 2323.0; // Specifying precision cout.precision(4); // Printing normal values cout << "Normal values of floating point numbers\na = "; cout << a << "\nb = " << b << '\n' ; // Printing values using fixed ( till 4 ) cout << "Values using fixed \n" << std::fixed; cout << a << "\n" << b << '\n' ; // Printing values using scientific ( till 4 ) // after 4, exponent is used cout << "Values using scientific are : " << std::scientific << endl; cout << a << '\n' << b << '\n' ; // Printing values using hexfloat ( till 4 ) cout << "Values using hexfloat are : " << std::hexfloat << endl; cout << a << '\n' << b << '\n' ; // Printing values using defaultfloat ( till 4 ) // same as normal cout << "Values using defaultfloat are : " << std::defaultfloat << endl; cout << a << '\n' << b << '\n' ; return 0;}Output:Normal values of floating point numbers a = 4.223 b = 2323 Values using fixed 4.2232 2323.0000 Values using scientific are : 4.2232e+00 2.3230e+03 Values using hexfloat are : 0x1.0e49783b72695p+2 0x1.226p+11 Values using defaultfloat are : 4.223 2323 This article is contributed by Astha Tyagi. 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.My Personal Notes arrow_drop_upSave std::fixed – Fixed Floating-point notation : It write floating-point values in fixed-point notation. The value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part. std::scientific – Scientific floating-point notation : It writes floating-point values in Scientific-point notation. The value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter “e” followed by an optional sign and three exponential digits. std::hexfloat – Hexfloat floating-point notation : It outputs the desired number after the conversion into hexadecimal format after the precision of no. is initialized ( as discussed in prev. cases ). std::defaultfloat – defaultfloat floating-point notation : It outputs the desired number same as default after the precision of no. is initialized ( as discussed in prev. cases ). It is mainly used to distinguish among other used formats for understandability of code. // C++ code to demonstrate the // working of // std::fixed// std::scientific// std::hexfloat// std::defaultfloat #include <iostream> using namespace std;int main(){ // Initializing floating point variable double a = 4.223234232; double b = 2323.0; // Specifying precision cout.precision(4); // Printing normal values cout << "Normal values of floating point numbers\na = "; cout << a << "\nb = " << b << '\n' ; // Printing values using fixed ( till 4 ) cout << "Values using fixed \n" << std::fixed; cout << a << "\n" << b << '\n' ; // Printing values using scientific ( till 4 ) // after 4, exponent is used cout << "Values using scientific are : " << std::scientific << endl; cout << a << '\n' << b << '\n' ; // Printing values using hexfloat ( till 4 ) cout << "Values using hexfloat are : " << std::hexfloat << endl; cout << a << '\n' << b << '\n' ; // Printing values using defaultfloat ( till 4 ) // same as normal cout << "Values using defaultfloat are : " << std::defaultfloat << endl; cout << a << '\n' << b << '\n' ; return 0;} Output: Normal values of floating point numbers a = 4.223 b = 2323 Values using fixed 4.2232 2323.0000 Values using scientific are : 4.2232e+00 2.3230e+03 Values using hexfloat are : 0x1.0e49783b72695p+2 0x1.226p+11 Values using defaultfloat are : 4.223 2323 This article is contributed by Astha Tyagi. 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-numerics-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Polymorphism in C++ List in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Command line arguments in C/C++ Exception Handling in C++ Sorting a vector in C++ Operators in C / C++ Destructors in C++ Power Function in C/C++ Pure Virtual Functions and Abstract Classes in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2017" }, { "code": null, "e": 356, "s": 52, "text": "Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header <iostream>." }, { "code": null, "e": 3381, "s": 356, "text": "std::fixed – Fixed Floating-point notation : It write floating-point values in fixed-point notation. The value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.std::scientific – Scientific floating-point notation : It writes floating-point values in Scientific-point notation. The value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter “e” followed by an optional sign and three exponential digits.std::hexfloat – Hexfloat floating-point notation : It outputs the desired number after the conversion into hexadecimal format after the precision of no. is initialized ( as discussed in prev. cases ).std::defaultfloat – defaultfloat floating-point notation : It outputs the desired number same as default after the precision of no. is initialized ( as discussed in prev. cases ). It is mainly used to distinguish among other used formats for understandability of code.// C++ code to demonstrate the // working of // std::fixed// std::scientific// std::hexfloat// std::defaultfloat #include <iostream> using namespace std;int main(){ // Initializing floating point variable double a = 4.223234232; double b = 2323.0; // Specifying precision cout.precision(4); // Printing normal values cout << \"Normal values of floating point numbers\\na = \"; cout << a << \"\\nb = \" << b << '\\n' ; // Printing values using fixed ( till 4 ) cout << \"Values using fixed \\n\" << std::fixed; cout << a << \"\\n\" << b << '\\n' ; // Printing values using scientific ( till 4 ) // after 4, exponent is used cout << \"Values using scientific are : \" << std::scientific << endl; cout << a << '\\n' << b << '\\n' ; // Printing values using hexfloat ( till 4 ) cout << \"Values using hexfloat are : \" << std::hexfloat << endl; cout << a << '\\n' << b << '\\n' ; // Printing values using defaultfloat ( till 4 ) // same as normal cout << \"Values using defaultfloat are : \" << std::defaultfloat << endl; cout << a << '\\n' << b << '\\n' ; return 0;}Output:Normal values of floating point numbers\na = 4.223\nb = 2323\nValues using fixed \n4.2232\n2323.0000\nValues using scientific are : \n4.2232e+00\n2.3230e+03\nValues using hexfloat are : \n0x1.0e49783b72695p+2\n0x1.226p+11\nValues using defaultfloat are : \n4.223\n2323\nThis article is contributed by Astha Tyagi. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 3630, "s": 3381, "text": "std::fixed – Fixed Floating-point notation : It write floating-point values in fixed-point notation. The value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part." }, { "code": null, "e": 4065, "s": 3630, "text": "std::scientific – Scientific floating-point notation : It writes floating-point values in Scientific-point notation. The value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision). Finally, this notation always includes an exponential part consisting on the letter “e” followed by an optional sign and three exponential digits." }, { "code": null, "e": 4266, "s": 4065, "text": "std::hexfloat – Hexfloat floating-point notation : It outputs the desired number after the conversion into hexadecimal format after the precision of no. is initialized ( as discussed in prev. cases )." }, { "code": null, "e": 4535, "s": 4266, "text": "std::defaultfloat – defaultfloat floating-point notation : It outputs the desired number same as default after the precision of no. is initialized ( as discussed in prev. cases ). It is mainly used to distinguish among other used formats for understandability of code." }, { "code": "// C++ code to demonstrate the // working of // std::fixed// std::scientific// std::hexfloat// std::defaultfloat #include <iostream> using namespace std;int main(){ // Initializing floating point variable double a = 4.223234232; double b = 2323.0; // Specifying precision cout.precision(4); // Printing normal values cout << \"Normal values of floating point numbers\\na = \"; cout << a << \"\\nb = \" << b << '\\n' ; // Printing values using fixed ( till 4 ) cout << \"Values using fixed \\n\" << std::fixed; cout << a << \"\\n\" << b << '\\n' ; // Printing values using scientific ( till 4 ) // after 4, exponent is used cout << \"Values using scientific are : \" << std::scientific << endl; cout << a << '\\n' << b << '\\n' ; // Printing values using hexfloat ( till 4 ) cout << \"Values using hexfloat are : \" << std::hexfloat << endl; cout << a << '\\n' << b << '\\n' ; // Printing values using defaultfloat ( till 4 ) // same as normal cout << \"Values using defaultfloat are : \" << std::defaultfloat << endl; cout << a << '\\n' << b << '\\n' ; return 0;}", "e": 5691, "s": 4535, "text": null }, { "code": null, "e": 5699, "s": 5691, "text": "Output:" }, { "code": null, "e": 5955, "s": 5699, "text": "Normal values of floating point numbers\na = 4.223\nb = 2323\nValues using fixed \n4.2232\n2323.0000\nValues using scientific are : \n4.2232e+00\n2.3230e+03\nValues using hexfloat are : \n0x1.0e49783b72695p+2\n0x1.226p+11\nValues using defaultfloat are : \n4.223\n2323\n" }, { "code": null, "e": 6378, "s": 5955, "text": "This article is contributed by Astha Tyagi. 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." }, { "code": null, "e": 6399, "s": 6378, "text": "cpp-numerics-library" }, { "code": null, "e": 6403, "s": 6399, "text": "STL" }, { "code": null, "e": 6407, "s": 6403, "text": "C++" }, { "code": null, "e": 6411, "s": 6407, "text": "STL" }, { "code": null, "e": 6415, "s": 6411, "text": "CPP" }, { "code": null, "e": 6513, "s": 6415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6533, "s": 6513, "text": "Polymorphism in C++" }, { "code": null, "e": 6577, "s": 6533, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 6622, "s": 6577, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6654, "s": 6622, "text": "Command line arguments in C/C++" }, { "code": null, "e": 6680, "s": 6654, "text": "Exception Handling in C++" }, { "code": null, "e": 6704, "s": 6680, "text": "Sorting a vector in C++" }, { "code": null, "e": 6725, "s": 6704, "text": "Operators in C / C++" }, { "code": null, "e": 6744, "s": 6725, "text": "Destructors in C++" }, { "code": null, "e": 6768, "s": 6744, "text": "Power Function in C/C++" } ]
SQL - WHERE Clause
The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters. The basic syntax of the SELECT statement with the WHERE clause is as shown below. SELECT column1, column2, columnN FROM table_name WHERE [condition] You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear. Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following code is an example which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 − SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000; This would produce the following result − +----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+ The following query is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table for a customer with the name Hardik. SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE NAME = 'Hardik'; This would produce the following result − +----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 5 | Hardik | 8500.00 |
[ { "code": null, "e": 2905, "s": 2587, "text": "The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records." }, { "code": null, "e": 3074, "s": 2905, "text": "The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters." }, { "code": null, "e": 3156, "s": 3074, "text": "The basic syntax of the SELECT statement with the WHERE clause is as shown below." }, { "code": null, "e": 3225, "s": 3156, "text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 3379, "s": 3225, "text": "You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear." }, { "code": null, "e": 3439, "s": 3379, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 3956, "s": 3439, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 4104, "s": 3956, "text": "The following code is an example which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 −" }, { "code": null, "e": 4170, "s": 4104, "text": "SQL> SELECT ID, NAME, SALARY \nFROM CUSTOMERS\nWHERE SALARY > 2000;" }, { "code": null, "e": 4212, "s": 4170, "text": "This would produce the following result −" }, { "code": null, "e": 4445, "s": 4212, "text": "+----+----------+----------+\n| ID | NAME | SALARY |\n+----+----------+----------+\n| 4 | Chaitali | 6500.00 |\n| 5 | Hardik | 8500.00 |\n| 6 | Komal | 4500.00 |\n| 7 | Muffy | 10000.00 |\n+----+----------+----------+\n" }, { "code": null, "e": 4591, "s": 4445, "text": "The following query is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table for a customer with the name Hardik." }, { "code": null, "e": 4659, "s": 4591, "text": "SQL> SELECT ID, NAME, SALARY \nFROM CUSTOMERS\nWHERE NAME = 'Hardik';" }, { "code": null, "e": 4701, "s": 4659, "text": "This would produce the following result −" } ]
How to dynamically update SCSS variables using ReactJS?
22 Feb, 2021 We can dynamically update SCSS variables using ReactJS with the help of a project by achieving theme switching of the card component between light and dark theme. Prerequisite: Basic knowledge of npm & create-react-app command. Basic knowledge of HTML/CSS. Basic Knowledge of react components & ES6. Basic Setup: You will start a new project using create-react-app so open your terminal and type: npx create-react-app react-scss Now go to your react-scss folder by typing the given command in the terminal: cd react-scss Required module: Install the dependencies required in this project by typing the given command in the terminal. $ npm install node-sass For developers using yarn: $ yarn add node-sass Project Structure: The file structure in the project will look like this. Folder structure Approach: We are going to create a card component using JSX and style it using SCSS.After structuring and styling the card component, we are going to make use of react useState hook to manage the state of the ‘darkTheme’ as per the user.There will be a button with onClick event listener which will set the state of ‘darkTheme’ as false if it previously was true and vice versa.We are going to use useEffect react hook that will fire up every time there is a change in the state of ‘darkTheme’.useEffect will cause a side effect and change the value of SCSS variables : $background-color and $text-color. We are going to create a card component using JSX and style it using SCSS. After structuring and styling the card component, we are going to make use of react useState hook to manage the state of the ‘darkTheme’ as per the user. There will be a button with onClick event listener which will set the state of ‘darkTheme’ as false if it previously was true and vice versa. We are going to use useEffect react hook that will fire up every time there is a change in the state of ‘darkTheme’. useEffect will cause a side effect and change the value of SCSS variables : $background-color and $text-color. Example: App.js import React, { useState, useEffect } from "react";// Import scss file//import './App.scss'; export default function App() { const [darkTheme, setDarkTheme] = useState(false); // React useEffect hook that will fire up // when "darkTheme" changes useEffect(() => { // Accessing scss variable "--background-color" // and "--text-color" using plain JavaScript // and changing the same according to the state of "darkTheme" const root = document.documentElement; root?.style.setProperty( "--background-color", darkTheme ? "#262833" : "#fff" ); root?.style.setProperty("--text-color", darkTheme ? "#fff" : "#262833"); }, [darkTheme]); const URL = "https://media.geeksforgeeks.org/" + "wp-content/uploads/20190918121833/geeksforgeeks-62.png"; return ( <> <div className="card"> <img className="image" src={URL} alt="geeksforgeeks" /> <div className="cardBody"> <h2>Dynamically changing scss variable using react </h2> <p> {" "} According to Wikipedia sass is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS). </p> <button onClick={() => setDarkTheme(!darkTheme)}> {darkTheme ? "????" : "????"} </button> </div> </div> </> );} App.scss #root { // Scss variables which we gonna assign using // useState and JavaScript in reactJS $background-color: #fff; $text-color: #262833; display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); grid-template-rows: auto;} .card { background-color: var(--background-color); margin: 20px 10px; padding: 10px; img { background-color: var(--background-color); width: 100%; height: 150px; object-fit: scale-down; } .cardBody { h2 { font-size: 2rem; color: var(--text-color); } p { font-size: 1rem; color: var(--text-color); } button { font-weight: bolder; border-radius: 50px; color: var(--background-color); border: none; border-style: none; padding: 10px 20px; background-color: var(--text-color); } }} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Picked React-Questions Technical Scripter 2020 ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps How to create a table in ReactJS ? 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? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2021" }, { "code": null, "e": 192, "s": 28, "text": "We can dynamically update SCSS variables using ReactJS with the help of a project by achieving theme switching of the card component between light and dark theme. " }, { "code": null, "e": 206, "s": 192, "text": "Prerequisite:" }, { "code": null, "e": 257, "s": 206, "text": "Basic knowledge of npm & create-react-app command." }, { "code": null, "e": 286, "s": 257, "text": "Basic knowledge of HTML/CSS." }, { "code": null, "e": 329, "s": 286, "text": "Basic Knowledge of react components & ES6." }, { "code": null, "e": 426, "s": 329, "text": "Basic Setup: You will start a new project using create-react-app so open your terminal and type:" }, { "code": null, "e": 458, "s": 426, "text": "npx create-react-app react-scss" }, { "code": null, "e": 536, "s": 458, "text": "Now go to your react-scss folder by typing the given command in the terminal:" }, { "code": null, "e": 550, "s": 536, "text": "cd react-scss" }, { "code": null, "e": 662, "s": 550, "text": "Required module: Install the dependencies required in this project by typing the given command in the terminal." }, { "code": null, "e": 686, "s": 662, "text": "$ npm install node-sass" }, { "code": null, "e": 713, "s": 686, "text": "For developers using yarn:" }, { "code": null, "e": 734, "s": 713, "text": "$ yarn add node-sass" }, { "code": null, "e": 808, "s": 734, "text": "Project Structure: The file structure in the project will look like this." }, { "code": null, "e": 825, "s": 808, "text": "Folder structure" }, { "code": null, "e": 835, "s": 825, "text": "Approach:" }, { "code": null, "e": 1430, "s": 835, "text": "We are going to create a card component using JSX and style it using SCSS.After structuring and styling the card component, we are going to make use of react useState hook to manage the state of the ‘darkTheme’ as per the user.There will be a button with onClick event listener which will set the state of ‘darkTheme’ as false if it previously was true and vice versa.We are going to use useEffect react hook that will fire up every time there is a change in the state of ‘darkTheme’.useEffect will cause a side effect and change the value of SCSS variables : $background-color and $text-color." }, { "code": null, "e": 1505, "s": 1430, "text": "We are going to create a card component using JSX and style it using SCSS." }, { "code": null, "e": 1659, "s": 1505, "text": "After structuring and styling the card component, we are going to make use of react useState hook to manage the state of the ‘darkTheme’ as per the user." }, { "code": null, "e": 1801, "s": 1659, "text": "There will be a button with onClick event listener which will set the state of ‘darkTheme’ as false if it previously was true and vice versa." }, { "code": null, "e": 1918, "s": 1801, "text": "We are going to use useEffect react hook that will fire up every time there is a change in the state of ‘darkTheme’." }, { "code": null, "e": 2029, "s": 1918, "text": "useEffect will cause a side effect and change the value of SCSS variables : $background-color and $text-color." }, { "code": null, "e": 2038, "s": 2029, "text": "Example:" }, { "code": null, "e": 2045, "s": 2038, "text": "App.js" }, { "code": " import React, { useState, useEffect } from \"react\";// Import scss file//import './App.scss'; export default function App() { const [darkTheme, setDarkTheme] = useState(false); // React useEffect hook that will fire up // when \"darkTheme\" changes useEffect(() => { // Accessing scss variable \"--background-color\" // and \"--text-color\" using plain JavaScript // and changing the same according to the state of \"darkTheme\" const root = document.documentElement; root?.style.setProperty( \"--background-color\", darkTheme ? \"#262833\" : \"#fff\" ); root?.style.setProperty(\"--text-color\", darkTheme ? \"#fff\" : \"#262833\"); }, [darkTheme]); const URL = \"https://media.geeksforgeeks.org/\" + \"wp-content/uploads/20190918121833/geeksforgeeks-62.png\"; return ( <> <div className=\"card\"> <img className=\"image\" src={URL} alt=\"geeksforgeeks\" /> <div className=\"cardBody\"> <h2>Dynamically changing scss variable using react </h2> <p> {\" \"} According to Wikipedia sass is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS). </p> <button onClick={() => setDarkTheme(!darkTheme)}> {darkTheme ? \"????\" : \"????\"} </button> </div> </div> </> );}", "e": 3414, "s": 2045, "text": null }, { "code": null, "e": 3423, "s": 3414, "text": "App.scss" }, { "code": "#root { // Scss variables which we gonna assign using // useState and JavaScript in reactJS $background-color: #fff; $text-color: #262833; display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); grid-template-rows: auto;} .card { background-color: var(--background-color); margin: 20px 10px; padding: 10px; img { background-color: var(--background-color); width: 100%; height: 150px; object-fit: scale-down; } .cardBody { h2 { font-size: 2rem; color: var(--text-color); } p { font-size: 1rem; color: var(--text-color); } button { font-weight: bolder; border-radius: 50px; color: var(--background-color); border: none; border-style: none; padding: 10px 20px; background-color: var(--text-color); } }}", "e": 4245, "s": 3423, "text": null }, { "code": null, "e": 4358, "s": 4245, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4368, "s": 4358, "text": "npm start" }, { "code": null, "e": 4467, "s": 4368, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4474, "s": 4467, "text": "Picked" }, { "code": null, "e": 4490, "s": 4474, "text": "React-Questions" }, { "code": null, "e": 4514, "s": 4490, "text": "Technical Scripter 2020" }, { "code": null, "e": 4522, "s": 4514, "text": "ReactJS" }, { "code": null, "e": 4541, "s": 4522, "text": "Technical Scripter" }, { "code": null, "e": 4558, "s": 4541, "text": "Web Technologies" }, { "code": null, "e": 4656, "s": 4558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4694, "s": 4656, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 4762, "s": 4694, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 4797, "s": 4762, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 4818, "s": 4797, "text": "ReactJS defaultProps" }, { "code": null, "e": 4853, "s": 4818, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 4886, "s": 4853, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4948, "s": 4886, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5009, "s": 4948, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5059, "s": 5009, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Suffix Tree Application 4 – Build Linear Time Suffix Array
25 Feb, 2022 Given a string, build it’s Suffix Array We have already discussed following two ways of building suffix array: Naive O(n2Logn) algorithm Enhanced O(nLogn) algorithm Please go through these to have the basic understanding. Here we will see how to build suffix array in linear time using suffix tree.As a prerequisite, we must know how to build a suffix tree in one or the other way. Here we will build suffix tree using Ukkonen’s Algorithm, discussed already as below: Ukkonen’s Suffix Tree Construction – Part 1 Ukkonen’s Suffix Tree Construction – Part 2 Ukkonen’s Suffix Tree Construction – Part 3 Ukkonen’s Suffix Tree Construction – Part 4 Ukkonen’s Suffix Tree Construction – Part 5 Ukkonen’s Suffix Tree Construction – Part 6Lets consider string abcabxabcd. It’s suffix array would be: 0 6 3 1 7 4 2 8 9 5 Lets look at following figure: If we do a DFS traversal, visiting edges in lexicographic order (we have been doing the same traversal in other Suffix Tree Application articles as well) and print suffix indices on leaves, we will get following: 10 0 6 3 1 7 4 2 8 9 5 “$” is lexicographically lesser than [a-zA-Z]. The suffix index 10 corresponds to edge with “$” label. Except this 1st suffix index, the sequence of all other numbers gives the suffix array of the string.So if we have a suffix tree of the string, then to get it’s suffix array, we just need to do a lexicographic order DFS traversal and store all the suffix indices in resultant suffix array, except the very 1st suffix index. C // A C program to implement Ukkonen's Suffix Tree Construction// and then create suffix array in linear time#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX_CHAR 256 struct SuffixTreeNode { struct SuffixTreeNode *children[MAX_CHAR]; //pointer to other node via suffix link struct SuffixTreeNode *suffixLink; /*(start, end) interval specifies the edge, by which the node is connected to its parent node. Each edge will connect two nodes, one parent and one child, and (start, end) interval of a given edge will be stored in the child node. Lets say there are two nods A and B connected by an edge with indices (5, 8) then this indices (5, 8) will be stored in node B. */ int start; int *end; /*for leaf nodes, it stores the index of suffix for the path from root to leaf*/ int suffixIndex;}; typedef struct SuffixTreeNode Node; char text[100]; //Input stringNode *root = NULL; //Pointer to root node /*lastNewNode will point to newly created internal node, waiting for it's suffix link to be set, which might get a new suffix link (other than root) in next extension of same phase. lastNewNode will be set to NULL when last newly created internal node (if there is any) got it's suffix link reset to new internal node created in next extension of same phase. */Node *lastNewNode = NULL;Node *activeNode = NULL; /*activeEdge is represented as input string character index (not the character itself)*/int activeEdge = -1;int activeLength = 0; // remainingSuffixCount tells how many suffixes yet to// be added in treeint remainingSuffixCount = 0;int leafEnd = -1;int *rootEnd = NULL;int *splitEnd = NULL;int size = -1; //Length of input string Node *newNode(int start, int *end){ Node *node =(Node*) malloc(sizeof(Node)); int i; for (i = 0; i < MAX_CHAR; i++) node->children[i] = NULL; /*For root node, suffixLink will be set to NULL For internal nodes, suffixLink will be set to root by default in current extension and may change in next extension*/ node->suffixLink = root; node->start = start; node->end = end; /*suffixIndex will be set to -1 by default and actual suffix index will be set later for leaves at the end of all phases*/ node->suffixIndex = -1; return node;} int edgeLength(Node *n) { if(n == root) return 0; return *(n->end) - (n->start) + 1;} int walkDown(Node *currNode){ /*activePoint change for walk down (APCFWD) using Skip/Count Trick (Trick 1). If activeLength is greater than current edge length, set next internal node as activeNode and adjust activeEdge and activeLength accordingly to represent same activePoint*/ if (activeLength >= edgeLength(currNode)) { activeEdge += edgeLength(currNode); activeLength -= edgeLength(currNode); activeNode = currNode; return 1; } return 0;} void extendSuffixTree(int pos){ /*Extension Rule 1, this takes care of extending all leaves created so far in tree*/ leafEnd = pos; /*Increment remainingSuffixCount indicating that a new suffix added to the list of suffixes yet to be added in tree*/ remainingSuffixCount++; /*set lastNewNode to NULL while starting a new phase, indicating there is no internal node waiting for it's suffix link reset in current phase*/ lastNewNode = NULL; //Add all suffixes (yet to be added) one by one in tree while(remainingSuffixCount > 0) { if (activeLength == 0) activeEdge = pos; //APCFALZ // There is no outgoing edge starting with // activeEdge from activeNode if (activeNode->children] == NULL) { //Extension Rule 2 (A new leaf edge gets created) activeNode->children] = newNode(pos, &leafEnd); /*A new leaf edge is created in above line starting from an existing node (the current activeNode), and if there is any internal node waiting for it's suffix link get reset, point the suffix link from that last internal node to current activeNode. Then set lastNewNode to NULL indicating no more node waiting for suffix link reset.*/ if (lastNewNode != NULL) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } } // There is an outgoing edge starting with activeEdge // from activeNode else { // Get the next node at the end of edge starting // with activeEdge Node *next = activeNode->children]; if (walkDown(next))//Do walkdown { //Start from next node (the new activeNode) continue; } /*Extension Rule 3 (current character being processed is already on the edge)*/ if (text[next->start + activeLength] == text[pos]) { //If a newly created node waiting for it's //suffix link to be set, then set suffix link //of that waiting node to current active node if(lastNewNode != NULL && activeNode != root) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } //APCFER3 activeLength++; /*STOP all further processing in this phase and move on to next phase*/ break; } /*We will be here when activePoint is in middle of the edge being traversed and current character being processed is not on the edge (we fall off the tree). In this case, we add a new internal node and a new leaf edge going out of that new node. This is Extension Rule 2, where a new leaf edge and a new internal node get created*/ splitEnd = (int*) malloc(sizeof(int)); *splitEnd = next->start + activeLength - 1; //New internal node Node *split = newNode(next->start, splitEnd); activeNode->children] = split; //New leaf coming out of new internal node split->children] = newNode(pos, &leafEnd); next->start += activeLength; split->children] = next; /*We got a new internal node here. If there is any internal node created in last extensions of same phase which is still waiting for it's suffix link reset, do it now.*/ if (lastNewNode != NULL) { /*suffixLink of lastNewNode points to current newly created internal node*/ lastNewNode->suffixLink = split; } /*Make the current newly created internal node waiting for it's suffix link reset (which is pointing to root at present). If we come across any other internal node (existing or newly created) in next extension of same phase, when a new leaf edge gets added (i.e. when Extension Rule 2 applies is any of the next extension of same phase) at that point, suffixLink of this node will point to that internal node.*/ lastNewNode = split; } /* One suffix got added in tree, decrement the count of suffixes yet to be added.*/ remainingSuffixCount--; if (activeNode == root && activeLength > 0) //APCFER2C1 { activeLength--; activeEdge = pos - remainingSuffixCount + 1; } else if (activeNode != root) //APCFER2C2 { activeNode = activeNode->suffixLink; } }} void print(int i, int j){ int k; for (k=i; k<=j; k++) printf("%c", text[k]);} //Print the suffix tree as well along with setting suffix index//So tree will be printed in DFS manner//Each edge along with it's suffix index will be printedvoid setSuffixIndexByDFS(Node *n, int labelHeight){ if (n == NULL) return; if (n->start != -1) //A non-root node { //Print the label on edge from parent to current node //Uncomment below line to print suffix tree // print(n->start, *(n->end)); } int leaf = 1; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { //Uncomment below two lines to print suffix index // if (leaf == 1 && n->start != -1) // printf(" [%d]\n", n->suffixIndex); //Current node is not a leaf as it has outgoing //edges from it. leaf = 0; setSuffixIndexByDFS(n->children[i], labelHeight + edgeLength(n->children[i])); } } if (leaf == 1) { n->suffixIndex = size - labelHeight; //Uncomment below line to print suffix index //printf(" [%d]\n", n->suffixIndex); }} void freeSuffixTreeByPostOrder(Node *n){ if (n == NULL) return; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { freeSuffixTreeByPostOrder(n->children[i]); } } if (n->suffixIndex == -1) free(n->end); free(n);} /*Build the suffix tree and print the edge labels along withsuffixIndex. suffixIndex for leaf edges will be >= 0 andfor non-leaf edges will be -1*/void buildSuffixTree(){ size = strlen(text); int i; rootEnd = (int*) malloc(sizeof(int)); *rootEnd = - 1; /*Root is a special node with start and end indices as -1, as it has no parent from where an edge comes to root*/ root = newNode(-1, rootEnd); activeNode = root; //First activeNode will be root for (i=0; i<size; i++) extendSuffixTree(i); int labelHeight = 0; setSuffixIndexByDFS(root, labelHeight);} void doTraversal(Node *n, int suffixArray[], int *idx){ if(n == NULL) { return; } int i=0; if(n->suffixIndex == -1) //If it is internal node { for (i = 0; i < MAX_CHAR; i++) { if(n->children[i] != NULL) { doTraversal(n->children[i], suffixArray, idx); } } } //If it is Leaf node other than "$" label else if(n->suffixIndex > -1 && n->suffixIndex < size) { suffixArray[(*idx)++] = n->suffixIndex; }} void buildSuffixArray(int suffixArray[]){ int i = 0; for(i=0; i< size; i++) suffixArray[i] = -1; int idx = 0; doTraversal(root, suffixArray, &idx); printf("Suffix Array for String "); for(i=0; i<size; i++) printf("%c", text[i]); printf(" is: "); for(i=0; i<size; i++) printf("%d ", suffixArray[i]); printf("\n");} // driver program to test above functionsint main(int argc, char *argv[]){ strcpy(text, "banana$"); buildSuffixTree(); size--; int *suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, "GEEKSFORGEEKS$"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, "AAAAAAAAAA$"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, "ABCDEFG$"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, "ABABABA$"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, "abcabxabcd$"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, "CCAAACCCGATTA$"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); return 0;} Output: Suffix Array for String banana is: 5 3 1 0 4 2 Suffix Array for String GEEKSFORGEEKS is: 9 1 10 2 5 8 0 11 3 6 7 12 4 Suffix Array for String AAAAAAAAAA is: 9 8 7 6 5 4 3 2 1 0 Suffix Array for String ABCDEFG is: 0 1 2 3 4 5 6 Suffix Array for String ABABABA is: 6 4 2 0 5 3 1 Suffix Array for String abcabxabcd is: 0 6 3 1 7 4 2 8 9 5 Suffix Array for String CCAAACCCGATTA is: 12 2 3 4 9 1 0 5 6 7 8 11 10 Ukkonen’s Suffix Tree Construction takes O(N) time and space to build suffix tree for a string of length N and after that, traversal of tree take O(N) to build suffix array. So overall, it’s linear in time and space. Can you see why traversal is O(N) ?? Because a suffix tree of string of length N will have at most N-1 internal nodes and N leaves. Traversal of these nodes can be done in O(N).We have published following more articles on suffix tree applications: Suffix Tree Application 1 – Substring Check Suffix Tree Application 2 – Searching All Patterns Suffix Tree Application 3 – Longest Repeated Substring Generalized Suffix Tree 1 Suffix Tree Application 5 – Longest Common Substring Suffix Tree Application 6 – Longest Palindromic Substring This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nidhi_biet varshagumber28 sagar0719kumar simmytarika5 Suffix-Tree Advanced Data Structure Pattern Searching Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Feb, 2022" }, { "code": null, "e": 165, "s": 52, "text": "Given a string, build it’s Suffix Array We have already discussed following two ways of building suffix array: " }, { "code": null, "e": 191, "s": 165, "text": "Naive O(n2Logn) algorithm" }, { "code": null, "e": 219, "s": 191, "text": "Enhanced O(nLogn) algorithm" }, { "code": null, "e": 847, "s": 219, "text": "Please go through these to have the basic understanding. Here we will see how to build suffix array in linear time using suffix tree.As a prerequisite, we must know how to build a suffix tree in one or the other way. Here we will build suffix tree using Ukkonen’s Algorithm, discussed already as below: Ukkonen’s Suffix Tree Construction – Part 1 Ukkonen’s Suffix Tree Construction – Part 2 Ukkonen’s Suffix Tree Construction – Part 3 Ukkonen’s Suffix Tree Construction – Part 4 Ukkonen’s Suffix Tree Construction – Part 5 Ukkonen’s Suffix Tree Construction – Part 6Lets consider string abcabxabcd. It’s suffix array would be: " }, { "code": null, "e": 867, "s": 847, "text": "0 6 3 1 7 4 2 8 9 5" }, { "code": null, "e": 900, "s": 867, "text": "Lets look at following figure: " }, { "code": null, "e": 1115, "s": 900, "text": "If we do a DFS traversal, visiting edges in lexicographic order (we have been doing the same traversal in other Suffix Tree Application articles as well) and print suffix indices on leaves, we will get following: " }, { "code": null, "e": 1138, "s": 1115, "text": "10 0 6 3 1 7 4 2 8 9 5" }, { "code": null, "e": 1566, "s": 1138, "text": "“$” is lexicographically lesser than [a-zA-Z]. The suffix index 10 corresponds to edge with “$” label. Except this 1st suffix index, the sequence of all other numbers gives the suffix array of the string.So if we have a suffix tree of the string, then to get it’s suffix array, we just need to do a lexicographic order DFS traversal and store all the suffix indices in resultant suffix array, except the very 1st suffix index. " }, { "code": null, "e": 1568, "s": 1566, "text": "C" }, { "code": "// A C program to implement Ukkonen's Suffix Tree Construction// and then create suffix array in linear time#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX_CHAR 256 struct SuffixTreeNode { struct SuffixTreeNode *children[MAX_CHAR]; //pointer to other node via suffix link struct SuffixTreeNode *suffixLink; /*(start, end) interval specifies the edge, by which the node is connected to its parent node. Each edge will connect two nodes, one parent and one child, and (start, end) interval of a given edge will be stored in the child node. Lets say there are two nods A and B connected by an edge with indices (5, 8) then this indices (5, 8) will be stored in node B. */ int start; int *end; /*for leaf nodes, it stores the index of suffix for the path from root to leaf*/ int suffixIndex;}; typedef struct SuffixTreeNode Node; char text[100]; //Input stringNode *root = NULL; //Pointer to root node /*lastNewNode will point to newly created internal node, waiting for it's suffix link to be set, which might get a new suffix link (other than root) in next extension of same phase. lastNewNode will be set to NULL when last newly created internal node (if there is any) got it's suffix link reset to new internal node created in next extension of same phase. */Node *lastNewNode = NULL;Node *activeNode = NULL; /*activeEdge is represented as input string character index (not the character itself)*/int activeEdge = -1;int activeLength = 0; // remainingSuffixCount tells how many suffixes yet to// be added in treeint remainingSuffixCount = 0;int leafEnd = -1;int *rootEnd = NULL;int *splitEnd = NULL;int size = -1; //Length of input string Node *newNode(int start, int *end){ Node *node =(Node*) malloc(sizeof(Node)); int i; for (i = 0; i < MAX_CHAR; i++) node->children[i] = NULL; /*For root node, suffixLink will be set to NULL For internal nodes, suffixLink will be set to root by default in current extension and may change in next extension*/ node->suffixLink = root; node->start = start; node->end = end; /*suffixIndex will be set to -1 by default and actual suffix index will be set later for leaves at the end of all phases*/ node->suffixIndex = -1; return node;} int edgeLength(Node *n) { if(n == root) return 0; return *(n->end) - (n->start) + 1;} int walkDown(Node *currNode){ /*activePoint change for walk down (APCFWD) using Skip/Count Trick (Trick 1). If activeLength is greater than current edge length, set next internal node as activeNode and adjust activeEdge and activeLength accordingly to represent same activePoint*/ if (activeLength >= edgeLength(currNode)) { activeEdge += edgeLength(currNode); activeLength -= edgeLength(currNode); activeNode = currNode; return 1; } return 0;} void extendSuffixTree(int pos){ /*Extension Rule 1, this takes care of extending all leaves created so far in tree*/ leafEnd = pos; /*Increment remainingSuffixCount indicating that a new suffix added to the list of suffixes yet to be added in tree*/ remainingSuffixCount++; /*set lastNewNode to NULL while starting a new phase, indicating there is no internal node waiting for it's suffix link reset in current phase*/ lastNewNode = NULL; //Add all suffixes (yet to be added) one by one in tree while(remainingSuffixCount > 0) { if (activeLength == 0) activeEdge = pos; //APCFALZ // There is no outgoing edge starting with // activeEdge from activeNode if (activeNode->children] == NULL) { //Extension Rule 2 (A new leaf edge gets created) activeNode->children] = newNode(pos, &leafEnd); /*A new leaf edge is created in above line starting from an existing node (the current activeNode), and if there is any internal node waiting for it's suffix link get reset, point the suffix link from that last internal node to current activeNode. Then set lastNewNode to NULL indicating no more node waiting for suffix link reset.*/ if (lastNewNode != NULL) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } } // There is an outgoing edge starting with activeEdge // from activeNode else { // Get the next node at the end of edge starting // with activeEdge Node *next = activeNode->children]; if (walkDown(next))//Do walkdown { //Start from next node (the new activeNode) continue; } /*Extension Rule 3 (current character being processed is already on the edge)*/ if (text[next->start + activeLength] == text[pos]) { //If a newly created node waiting for it's //suffix link to be set, then set suffix link //of that waiting node to current active node if(lastNewNode != NULL && activeNode != root) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } //APCFER3 activeLength++; /*STOP all further processing in this phase and move on to next phase*/ break; } /*We will be here when activePoint is in middle of the edge being traversed and current character being processed is not on the edge (we fall off the tree). In this case, we add a new internal node and a new leaf edge going out of that new node. This is Extension Rule 2, where a new leaf edge and a new internal node get created*/ splitEnd = (int*) malloc(sizeof(int)); *splitEnd = next->start + activeLength - 1; //New internal node Node *split = newNode(next->start, splitEnd); activeNode->children] = split; //New leaf coming out of new internal node split->children] = newNode(pos, &leafEnd); next->start += activeLength; split->children] = next; /*We got a new internal node here. If there is any internal node created in last extensions of same phase which is still waiting for it's suffix link reset, do it now.*/ if (lastNewNode != NULL) { /*suffixLink of lastNewNode points to current newly created internal node*/ lastNewNode->suffixLink = split; } /*Make the current newly created internal node waiting for it's suffix link reset (which is pointing to root at present). If we come across any other internal node (existing or newly created) in next extension of same phase, when a new leaf edge gets added (i.e. when Extension Rule 2 applies is any of the next extension of same phase) at that point, suffixLink of this node will point to that internal node.*/ lastNewNode = split; } /* One suffix got added in tree, decrement the count of suffixes yet to be added.*/ remainingSuffixCount--; if (activeNode == root && activeLength > 0) //APCFER2C1 { activeLength--; activeEdge = pos - remainingSuffixCount + 1; } else if (activeNode != root) //APCFER2C2 { activeNode = activeNode->suffixLink; } }} void print(int i, int j){ int k; for (k=i; k<=j; k++) printf(\"%c\", text[k]);} //Print the suffix tree as well along with setting suffix index//So tree will be printed in DFS manner//Each edge along with it's suffix index will be printedvoid setSuffixIndexByDFS(Node *n, int labelHeight){ if (n == NULL) return; if (n->start != -1) //A non-root node { //Print the label on edge from parent to current node //Uncomment below line to print suffix tree // print(n->start, *(n->end)); } int leaf = 1; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { //Uncomment below two lines to print suffix index // if (leaf == 1 && n->start != -1) // printf(\" [%d]\\n\", n->suffixIndex); //Current node is not a leaf as it has outgoing //edges from it. leaf = 0; setSuffixIndexByDFS(n->children[i], labelHeight + edgeLength(n->children[i])); } } if (leaf == 1) { n->suffixIndex = size - labelHeight; //Uncomment below line to print suffix index //printf(\" [%d]\\n\", n->suffixIndex); }} void freeSuffixTreeByPostOrder(Node *n){ if (n == NULL) return; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { freeSuffixTreeByPostOrder(n->children[i]); } } if (n->suffixIndex == -1) free(n->end); free(n);} /*Build the suffix tree and print the edge labels along withsuffixIndex. suffixIndex for leaf edges will be >= 0 andfor non-leaf edges will be -1*/void buildSuffixTree(){ size = strlen(text); int i; rootEnd = (int*) malloc(sizeof(int)); *rootEnd = - 1; /*Root is a special node with start and end indices as -1, as it has no parent from where an edge comes to root*/ root = newNode(-1, rootEnd); activeNode = root; //First activeNode will be root for (i=0; i<size; i++) extendSuffixTree(i); int labelHeight = 0; setSuffixIndexByDFS(root, labelHeight);} void doTraversal(Node *n, int suffixArray[], int *idx){ if(n == NULL) { return; } int i=0; if(n->suffixIndex == -1) //If it is internal node { for (i = 0; i < MAX_CHAR; i++) { if(n->children[i] != NULL) { doTraversal(n->children[i], suffixArray, idx); } } } //If it is Leaf node other than \"$\" label else if(n->suffixIndex > -1 && n->suffixIndex < size) { suffixArray[(*idx)++] = n->suffixIndex; }} void buildSuffixArray(int suffixArray[]){ int i = 0; for(i=0; i< size; i++) suffixArray[i] = -1; int idx = 0; doTraversal(root, suffixArray, &idx); printf(\"Suffix Array for String \"); for(i=0; i<size; i++) printf(\"%c\", text[i]); printf(\" is: \"); for(i=0; i<size; i++) printf(\"%d \", suffixArray[i]); printf(\"\\n\");} // driver program to test above functionsint main(int argc, char *argv[]){ strcpy(text, \"banana$\"); buildSuffixTree(); size--; int *suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, \"GEEKSFORGEEKS$\"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, \"AAAAAAAAAA$\"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, \"ABCDEFG$\"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, \"ABABABA$\"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, \"abcabxabcd$\"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); strcpy(text, \"CCAAACCCGATTA$\"); buildSuffixTree(); size--; suffixArray =(int*) malloc(sizeof(int) * size); buildSuffixArray(suffixArray); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); free(suffixArray); return 0;}", "e": 14323, "s": 1568, "text": null }, { "code": null, "e": 14331, "s": 14323, "text": "Output:" }, { "code": null, "e": 14743, "s": 14331, "text": "Suffix Array for String banana is: 5 3 1 0 4 2 \nSuffix Array for String GEEKSFORGEEKS is: 9 1 10 2 5 8 0 11 3 6 7 12 4 \nSuffix Array for String AAAAAAAAAA is: 9 8 7 6 5 4 3 2 1 0 \nSuffix Array for String ABCDEFG is: 0 1 2 3 4 5 6 \nSuffix Array for String ABABABA is: 6 4 2 0 5 3 1 \nSuffix Array for String abcabxabcd is: 0 6 3 1 7 4 2 8 9 5\nSuffix Array for String CCAAACCCGATTA is: 12 2 3 4 9 1 0 5 6 7 8 11 10" }, { "code": null, "e": 15210, "s": 14743, "text": "Ukkonen’s Suffix Tree Construction takes O(N) time and space to build suffix tree for a string of length N and after that, traversal of tree take O(N) to build suffix array. So overall, it’s linear in time and space. Can you see why traversal is O(N) ?? Because a suffix tree of string of length N will have at most N-1 internal nodes and N leaves. Traversal of these nodes can be done in O(N).We have published following more articles on suffix tree applications: " }, { "code": null, "e": 15256, "s": 15210, "text": "Suffix Tree Application 1 – Substring Check " }, { "code": null, "e": 15309, "s": 15256, "text": "Suffix Tree Application 2 – Searching All Patterns " }, { "code": null, "e": 15366, "s": 15309, "text": "Suffix Tree Application 3 – Longest Repeated Substring " }, { "code": null, "e": 15394, "s": 15366, "text": "Generalized Suffix Tree 1 " }, { "code": null, "e": 15449, "s": 15394, "text": "Suffix Tree Application 5 – Longest Common Substring " }, { "code": null, "e": 15509, "s": 15449, "text": "Suffix Tree Application 6 – Longest Palindromic Substring " }, { "code": null, "e": 15679, "s": 15509, "text": "This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 15690, "s": 15679, "text": "nidhi_biet" }, { "code": null, "e": 15705, "s": 15690, "text": "varshagumber28" }, { "code": null, "e": 15720, "s": 15705, "text": "sagar0719kumar" }, { "code": null, "e": 15733, "s": 15720, "text": "simmytarika5" }, { "code": null, "e": 15745, "s": 15733, "text": "Suffix-Tree" }, { "code": null, "e": 15769, "s": 15745, "text": "Advanced Data Structure" }, { "code": null, "e": 15787, "s": 15769, "text": "Pattern Searching" }, { "code": null, "e": 15805, "s": 15787, "text": "Pattern Searching" } ]
Recover password of password protected zip file
01 Jun, 2022 In this article, we will get to know about how to get the password of a zip file. I’m using Linux I went with a quick search and came across fcrackzip. This is a free program that allows for both dictionary and brute force cracking of zip file passwords. It is not difficult to use and offers a wide range of options. Let’s make a zip file then we will copy-paste it into Linux after that we will try to break this password by fcrackzip. I created a zip file. This zip file’s password is 12345678. Creating password protected secret.zip In Terminal type fcrackzip –help this command will open help options for fcrackzip USAGE: fcrackzip [-b|--brute-force] use brute force algorithm [-D|--dictionary] use a dictionary [-B|--benchmark] execute a small benchmark [-c|--charset characterset] use characters from charse [-h|--help] show this message [--version] show the version of this program [-V|--validate] sanity-check the algorithm [-v|--verbose] be more verbose [-p|--init-password string] use string as initial password/file [-l|--length min-max] check password with length min to max [-u|--use-unzip] use unzip to weed out wrong passwords [-m|--method num] use method number "num" (see below [-2|--modulo r/m] only calculate 1/m of the password file... the zipfiles to crack There are 2 methods to get the password of the zip file 1. Brute force attack: If you wanted to use a brute force attack from 4-8 characters on “secret.zip” you would use the following command: $fcrackzip -v -m -l 4-8 -u secret.zip To break the command down: v is for verbose and gives you better output m specifies the mode to use, in this case, zip6 l specifies the minimum password length to maximum password length u tells the program to test the password with unzip before declaring it correct 2. Dictionary-based Attack: Using a dictionary-based attack is as easy as brute force attack Syntax: $ fcrackzip -v -D -u -p /usr/share/dict/words secret.zip Here: /usr/share/dict/words is the wordlists and secret.zip is the zipped file that is encrypted. Example: fcrackzip -v -D -u -p /usr/share/wordlists/rockyou.txt 16162020_backup.zip Here the only difference is the -D to specify a dictionary-based attack and -p which is used to specify the password file. This file should contain one word per line and on Linux systems, there’s a nice dictionary included in /usr/share/dict/words or you can use any other password dictionaries. This article is contributed by Akash Sharan. 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. manav014 as5853535 sumitgumber28 kothavvsaakash TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction How to Run a Python Script using Docker? How to setup cron jobs in Ubuntu Top Programming Languages for Android App Development How to Add External JAR File to an IntelliJ IDEA Project? How to Delete Temporary Files in Windows 10? How to set up Command Prompt for Python in Windows10 ? How to Install Z Shell(zsh) on Linux? Whatsapp using Python! Generating Password and OTP in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2022" }, { "code": null, "e": 551, "s": 52, "text": "In this article, we will get to know about how to get the password of a zip file. I’m using Linux I went with a quick search and came across fcrackzip. This is a free program that allows for both dictionary and brute force cracking of zip file passwords. It is not difficult to use and offers a wide range of options. Let’s make a zip file then we will copy-paste it into Linux after that we will try to break this password by fcrackzip. I created a zip file. This zip file’s password is 12345678. " }, { "code": null, "e": 590, "s": 551, "text": "Creating password protected secret.zip" }, { "code": null, "e": 675, "s": 590, "text": "In Terminal type fcrackzip –help this command will open help options for fcrackzip " }, { "code": null, "e": 1643, "s": 675, "text": "USAGE: fcrackzip\n [-b|--brute-force] use brute force algorithm\n [-D|--dictionary] use a dictionary\n [-B|--benchmark] execute a small benchmark\n [-c|--charset characterset] use characters from charse\n [-h|--help] show this message\n [--version] show the version of this program\n [-V|--validate] sanity-check the algorithm\n [-v|--verbose] be more verbose\n [-p|--init-password string] use string as initial password/file\n [-l|--length min-max] check password with length min to max\n [-u|--use-unzip] use unzip to weed out wrong passwords\n [-m|--method num] use method number \"num\" (see below\n [-2|--modulo r/m] only calculate 1/m of the password\n file... the zipfiles to crack" }, { "code": null, "e": 1701, "s": 1643, "text": "There are 2 methods to get the password of the zip file " }, { "code": null, "e": 1840, "s": 1701, "text": "1. Brute force attack: If you wanted to use a brute force attack from 4-8 characters on “secret.zip” you would use the following command: " }, { "code": null, "e": 1878, "s": 1840, "text": "$fcrackzip -v -m -l 4-8 -u secret.zip" }, { "code": null, "e": 1906, "s": 1878, "text": "To break the command down: " }, { "code": null, "e": 1951, "s": 1906, "text": "v is for verbose and gives you better output" }, { "code": null, "e": 1999, "s": 1951, "text": "m specifies the mode to use, in this case, zip6" }, { "code": null, "e": 2066, "s": 1999, "text": "l specifies the minimum password length to maximum password length" }, { "code": null, "e": 2146, "s": 2066, "text": "u tells the program to test the password with unzip before declaring it correct" }, { "code": null, "e": 2239, "s": 2146, "text": "2. Dictionary-based Attack: Using a dictionary-based attack is as easy as brute force attack" }, { "code": null, "e": 2247, "s": 2239, "text": "Syntax:" }, { "code": null, "e": 2304, "s": 2247, "text": "$ fcrackzip -v -D -u -p /usr/share/dict/words secret.zip" }, { "code": null, "e": 2402, "s": 2304, "text": "Here: /usr/share/dict/words is the wordlists and secret.zip is the zipped file that is encrypted." }, { "code": null, "e": 2411, "s": 2402, "text": "Example:" }, { "code": null, "e": 2486, "s": 2411, "text": "fcrackzip -v -D -u -p /usr/share/wordlists/rockyou.txt 16162020_backup.zip" }, { "code": null, "e": 2783, "s": 2486, "text": "Here the only difference is the -D to specify a dictionary-based attack and -p which is used to specify the password file. This file should contain one word per line and on Linux systems, there’s a nice dictionary included in /usr/share/dict/words or you can use any other password dictionaries. " }, { "code": null, "e": 3080, "s": 2783, "text": "This article is contributed by Akash Sharan. 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": 3206, "s": 3080, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 3215, "s": 3206, "text": "manav014" }, { "code": null, "e": 3225, "s": 3215, "text": "as5853535" }, { "code": null, "e": 3239, "s": 3225, "text": "sumitgumber28" }, { "code": null, "e": 3254, "s": 3239, "text": "kothavvsaakash" }, { "code": null, "e": 3263, "s": 3254, "text": "TechTips" }, { "code": null, "e": 3361, "s": 3263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3387, "s": 3361, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3428, "s": 3387, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 3461, "s": 3428, "text": "How to setup cron jobs in Ubuntu" }, { "code": null, "e": 3515, "s": 3461, "text": "Top Programming Languages for Android App Development" }, { "code": null, "e": 3573, "s": 3515, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 3618, "s": 3573, "text": "How to Delete Temporary Files in Windows 10?" }, { "code": null, "e": 3673, "s": 3618, "text": "How to set up Command Prompt for Python in Windows10 ?" }, { "code": null, "e": 3711, "s": 3673, "text": "How to Install Z Shell(zsh) on Linux?" }, { "code": null, "e": 3734, "s": 3711, "text": "Whatsapp using Python!" } ]
Lex program to check whether given string is Palindrome or Not
01 May, 2019 Problem: Write a Lex program to check whether given string is Palindrome or Not. Explanation:Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Description: A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome. Examples: Input: Enter a string : naman Output: Given string is Palindrome Input: Enter a string : geeksforgeeks Output: Given string is not Palindrome Implementation: /* Lex program to check whether - given string is Palindrome or Not */ % { int i, j, flag; % } /* Rule Section */% % [a - z A - z 0 - 9]*{ for (i = 0, j = yyleng - 1; i <= j; i++, j--) { if (yytext[i] == yytext[j]) { flag = 1; } else { flag = 0; break; } } if (flag == 1) printf("Given string is Palindrome"); else printf("Given string is not Palindrome");}% % // driver code int main(){ printf("Enter a string :"); yylex(); return 0;} int yywrap(){ return 1;} Output: Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Runtime Environments in Compiler Design Compiler construction tools Basic Blocks in Compiler Design Token, Patterns, and Lexems Compiler Design - Variants of Syntax Tree Loop Optimization in Compiler Design
[ { "code": null, "e": 28, "s": 0, "text": "\n01 May, 2019" }, { "code": null, "e": 109, "s": 28, "text": "Problem: Write a Lex program to check whether given string is Palindrome or Not." }, { "code": null, "e": 363, "s": 109, "text": "Explanation:Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language." }, { "code": null, "e": 519, "s": 363, "text": "Description: A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome." }, { "code": null, "e": 529, "s": 519, "text": "Examples:" }, { "code": null, "e": 674, "s": 529, "text": "Input: Enter a string : naman \nOutput: Given string is Palindrome\n\nInput: Enter a string : geeksforgeeks\nOutput: Given string is not Palindrome " }, { "code": null, "e": 690, "s": 674, "text": "Implementation:" }, { "code": "/* Lex program to check whether - given string is Palindrome or Not */ % { int i, j, flag; % } /* Rule Section */% % [a - z A - z 0 - 9]*{ for (i = 0, j = yyleng - 1; i <= j; i++, j--) { if (yytext[i] == yytext[j]) { flag = 1; } else { flag = 0; break; } } if (flag == 1) printf(\"Given string is Palindrome\"); else printf(\"Given string is not Palindrome\");}% % // driver code int main(){ printf(\"Enter a string :\"); yylex(); return 0;} int yywrap(){ return 1;}", "e": 1275, "s": 690, "text": null }, { "code": null, "e": 1283, "s": 1275, "text": "Output:" }, { "code": null, "e": 1295, "s": 1283, "text": "Lex program" }, { "code": null, "e": 1311, "s": 1295, "text": "Compiler Design" }, { "code": null, "e": 1409, "s": 1311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1467, "s": 1409, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 1500, "s": 1467, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 1531, "s": 1500, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 1601, "s": 1531, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 1641, "s": 1601, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 1669, "s": 1641, "text": "Compiler construction tools" }, { "code": null, "e": 1701, "s": 1669, "text": "Basic Blocks in Compiler Design" }, { "code": null, "e": 1729, "s": 1701, "text": "Token, Patterns, and Lexems" }, { "code": null, "e": 1771, "s": 1729, "text": "Compiler Design - Variants of Syntax Tree" } ]
Perl | Data Types
22 Jun, 2022 Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. There are 3 data types in Perl as follows: ScalarsArraysHashes(Associative Arrays) Scalars Arrays Hashes(Associative Arrays) It is a single unit of data that can be an integer number, floating-point, a character, a string, a paragraph, or an entire web page. To know more about scalars please refer to Scalars in Perl. Example: Perl # Perl Program to demonstrate the# Scalars data types # An integer assignment$age = 1; # A string$name = "ABC"; # A floating point $salary = 21.5; # displaying resultprint "Age = $age\n";print "Name = $name\n";print "Salary = $salary\n"; Output: Age = 1 Name = ABC Salary = 21.5 Scalar Operations: There are many operations that can be performed on the scalar data types like addition, subtraction, multiplication, etc. Example: Perl # Perl Program to demonstrate# the Scalars operations #!/usr/bin/perl # Concatenates strings$str = "GFG" . " is the best"; # adds two numbers $num = 1 + 0; # multiplies two numbers $mul = 4 * 9; # concatenates string and number $mix = $str . $num; # displaying resultprint "str = $str\n";print "num = $num\n";print "mul = $mul\n";print "mix = $mix\n"; Output: str = GFG is the best num = 1 mul = 36 mix = GFG is the best1 An array is a variable that stores the value of the same data type in the form of a list. To declare an array in Perl, we use ‘@’ sign in front of the variable name. @age=(10, 20, 30) It will create an array of integers that contains the values 10, 20, and 30. To access a single element of an array, we use the ‘$’ sign. $age[0] It will produce an output of 10. To know more about arrays please refer to Arrays in Perl Example: Perl # Perl Program to demonstrate# the Arrays data type #!/usr/bin/perl # creation of arrays@ages = (33, 31, 27); @names = ("Geeks", "for", "Geeks"); # displaying resultprint "\$ages[0] = $ages[0]\n";print "\$ages[1] = $ages[1]\n";print "\$ages[2] = $ages[2]\n";print "\$names[0] = $names[0]\n";print "\$names[1] = $names[1]\n";print "\$names[2] = $names[2]\n"; Output: $ages[0] = 33 $ages[1] = 31 $ages[2] = 27 $names[0] = Geeks $names[1] = for $names[2] = Geeks It is a set of key-value pair. It is also termed the Associative Arrays. To declare a hash in Perl, we use the ‘%’ sign. To access the particular value, we use the ‘$’ symbol which is followed by the key in braces. Example: Perl # Perl Program to demonstrate the# Hashes data type # Hashes%data = ('GFG', 7, 'for', 4, 'Geeks', 11); #displaying resultprint "\$data{'GFG'} = $data{'GFG'}\n";print "\$data{'for'} = $data{'for'}\n";print "\$data{'Geeks'} = $data{'Geeks'}\n"; Output: $data{'GFG'} = 7 $data{'for'} = 4 $data{'Geeks'} = 11 lakshmansingh5016 deepakbethi416 perl-basics perl-data-types Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 324, "s": 52, "text": "Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. " }, { "code": null, "e": 368, "s": 324, "text": "There are 3 data types in Perl as follows: " }, { "code": null, "e": 408, "s": 368, "text": "ScalarsArraysHashes(Associative Arrays)" }, { "code": null, "e": 416, "s": 408, "text": "Scalars" }, { "code": null, "e": 423, "s": 416, "text": "Arrays" }, { "code": null, "e": 450, "s": 423, "text": "Hashes(Associative Arrays)" }, { "code": null, "e": 645, "s": 450, "text": "It is a single unit of data that can be an integer number, floating-point, a character, a string, a paragraph, or an entire web page. To know more about scalars please refer to Scalars in Perl. " }, { "code": null, "e": 654, "s": 645, "text": "Example:" }, { "code": null, "e": 659, "s": 654, "text": "Perl" }, { "code": "# Perl Program to demonstrate the# Scalars data types # An integer assignment$age = 1; # A string$name = \"ABC\"; # A floating point $salary = 21.5; # displaying resultprint \"Age = $age\\n\";print \"Name = $name\\n\";print \"Salary = $salary\\n\";", "e": 914, "s": 659, "text": null }, { "code": null, "e": 923, "s": 914, "text": "Output: " }, { "code": null, "e": 956, "s": 923, "text": "Age = 1\nName = ABC\nSalary = 21.5" }, { "code": null, "e": 1097, "s": 956, "text": "Scalar Operations: There are many operations that can be performed on the scalar data types like addition, subtraction, multiplication, etc." }, { "code": null, "e": 1106, "s": 1097, "text": "Example:" }, { "code": null, "e": 1111, "s": 1106, "text": "Perl" }, { "code": "# Perl Program to demonstrate# the Scalars operations #!/usr/bin/perl # Concatenates strings$str = \"GFG\" . \" is the best\"; # adds two numbers $num = 1 + 0; # multiplies two numbers $mul = 4 * 9; # concatenates string and number $mix = $str . $num; # displaying resultprint \"str = $str\\n\";print \"num = $num\\n\";print \"mul = $mul\\n\";print \"mix = $mix\\n\";", "e": 1500, "s": 1111, "text": null }, { "code": null, "e": 1509, "s": 1500, "text": "Output: " }, { "code": null, "e": 1571, "s": 1509, "text": "str = GFG is the best\nnum = 1\nmul = 36\nmix = GFG is the best1" }, { "code": null, "e": 1738, "s": 1571, "text": "An array is a variable that stores the value of the same data type in the form of a list. To declare an array in Perl, we use ‘@’ sign in front of the variable name. " }, { "code": null, "e": 1756, "s": 1738, "text": "@age=(10, 20, 30)" }, { "code": null, "e": 1895, "s": 1756, "text": "It will create an array of integers that contains the values 10, 20, and 30. To access a single element of an array, we use the ‘$’ sign. " }, { "code": null, "e": 1903, "s": 1895, "text": "$age[0]" }, { "code": null, "e": 1993, "s": 1903, "text": "It will produce an output of 10. To know more about arrays please refer to Arrays in Perl" }, { "code": null, "e": 2002, "s": 1993, "text": "Example:" }, { "code": null, "e": 2007, "s": 2002, "text": "Perl" }, { "code": "# Perl Program to demonstrate# the Arrays data type #!/usr/bin/perl # creation of arrays@ages = (33, 31, 27); @names = (\"Geeks\", \"for\", \"Geeks\"); # displaying resultprint \"\\$ages[0] = $ages[0]\\n\";print \"\\$ages[1] = $ages[1]\\n\";print \"\\$ages[2] = $ages[2]\\n\";print \"\\$names[0] = $names[0]\\n\";print \"\\$names[1] = $names[1]\\n\";print \"\\$names[2] = $names[2]\\n\";", "e": 2376, "s": 2007, "text": null }, { "code": null, "e": 2385, "s": 2376, "text": "Output: " }, { "code": null, "e": 2479, "s": 2385, "text": "$ages[0] = 33\n$ages[1] = 31\n$ages[2] = 27\n$names[0] = Geeks\n$names[1] = for\n$names[2] = Geeks" }, { "code": null, "e": 2694, "s": 2479, "text": "It is a set of key-value pair. It is also termed the Associative Arrays. To declare a hash in Perl, we use the ‘%’ sign. To access the particular value, we use the ‘$’ symbol which is followed by the key in braces." }, { "code": null, "e": 2703, "s": 2694, "text": "Example:" }, { "code": null, "e": 2708, "s": 2703, "text": "Perl" }, { "code": "# Perl Program to demonstrate the# Hashes data type # Hashes%data = ('GFG', 7, 'for', 4, 'Geeks', 11); #displaying resultprint \"\\$data{'GFG'} = $data{'GFG'}\\n\";print \"\\$data{'for'} = $data{'for'}\\n\";print \"\\$data{'Geeks'} = $data{'Geeks'}\\n\";", "e": 2951, "s": 2708, "text": null }, { "code": null, "e": 2960, "s": 2951, "text": "Output: " }, { "code": null, "e": 3014, "s": 2960, "text": "$data{'GFG'} = 7\n$data{'for'} = 4\n$data{'Geeks'} = 11" }, { "code": null, "e": 3032, "s": 3014, "text": "lakshmansingh5016" }, { "code": null, "e": 3047, "s": 3032, "text": "deepakbethi416" }, { "code": null, "e": 3059, "s": 3047, "text": "perl-basics" }, { "code": null, "e": 3075, "s": 3059, "text": "perl-data-types" }, { "code": null, "e": 3080, "s": 3075, "text": "Perl" }, { "code": null, "e": 3085, "s": 3080, "text": "Perl" } ]
Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
06 Jul, 2022 We have introduced Graph basics in Graph and its representations. In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. Following is an example undirected and unweighted graph with 5 vertices. Below is an adjacency list representation of the graph. We use vectors in STL to implement graphs using adjacency list representation. vector: A sequence container. Here we use it to store adjacency lists of all vertices. We use vertex numbers as the index in this vector. The idea is to represent a graph as an array of vectors such that every vector represents the adjacency list of a vertex. Below is a complete STL-based C++ program for DFS Traversal. Implementation: C++ Python3 Javascript // A simple representation of graph using STL,// for the purpose of competitive programming#include<bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to do DFS of graph// recursively from a given vertex u.void DFSUtil(int u, vector<int> adj[], vector<bool> &visited){ visited[u] = true; cout << u << " "; for (int i=0; i<adj[u].size(); i++) if (visited[adj[u][i]] == false) DFSUtil(adj[u][i], adj, visited);} // This function does DFSUtil() for all// unvisited vertices.void DFS(vector<int> adj[], int V){ vector<bool> visited(V, false); for (int u=0; u<V; u++) if (visited[u] == false) DFSUtil(u, adj, visited);} // Driver codeint main(){ int V = 5; // The below line may not work on all // compilers. If it does not work on // your compiler, please replace it with // following // vector<int> *adj = new vector<int>[V]; vector<int> adj[V]; // Vertex numbers should be from 0 to 4. addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); DFS(adj, V); return 0;} # A simple representation of graph using STL,# for the purpose of competitive programming # A utility function to add an edge in an# undirected graph.def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) return adj # A utility function to do DFS of graph# recursively from a given vertex u.def DFSUtil(u, adj, visited): visited[u] = True print(u, end = " ") for i in range(len(adj[u])): if (visited[adj[u][i]] == False): DFSUtil(adj[u][i], adj, visited) # This function does DFSUtil() for all# unvisited vertices.def DFS(adj, V): visited = [False]*(V+1) for u in range(V): if (visited[u] == False): DFSUtil(u, adj, visited) # Driver codeif __name__ == '__main__': V = 5 # The below line may not work on all # compilers. If it does not work on # your compiler, please replace it with # following # vector<int> *adj = new vector<int>[V] adj = [[] for i in range(V)] # Vertex numbers should be from 0 to 4. adj = addEdge(adj, 0, 1) adj = addEdge(adj, 0, 4) adj = addEdge(adj, 1, 2) adj = addEdge(adj, 1, 3) adj = addEdge(adj, 1, 4) adj = addEdge(adj, 2, 3) adj = addEdge(adj, 3, 4) DFS(adj, V) # This code is contributed by mohit kumar 29. <script>// A simple representation of graph using STL,// for the purpose of competitive programming // A utility function to add an edge in an// undirected graph. function addEdge(adj,u,v) { adj[u].push(v); adj[v].push(u); } // A utility function to do DFS of graph// recursively from a given vertex u. function DFSUtil(u,adj,visited) { visited[u] = true; document.write(u+" "); for (let i=0; i<adj[u].length; i++) if (visited[adj[u][i]] == false) DFSUtil(adj[u][i], adj, visited); } // This function does DFSUtil() for all// unvisited vertices. function DFS(adj,V) { let visited=new Array(V); for(let i=0;i<V;i++) { visited[i]=false; } for (let u=0; u<V; u++) if (visited[u] == false) DFSUtil(u, adj, visited); } // Driver code let V = 5; // The below line may not work on all // compilers. If it does not work on // your compiler, please replace it with // following // vector<int> *adj = new vector<int>[V]; let adj=new Array(V); for(let i=0;i<V;i++) { adj[i]=[]; } // Vertex numbers should be from 0 to 4. addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); DFS(adj, V); // This code is contributed by unknown2108</script> 0 1 2 3 4 Below are related articles: Graph implementation using STL for competitive programming | Set 2 (Weighted graph) Dijkstra’s Shortest Path Algorithm using priority_queue of STL Dijkstra’s shortest path algorithm using set in STL Kruskal’s Minimum Spanning Tree using STL in C++ Prim’s algorithm using priority_queue in STL This article is contributed by Shubham Gupta. 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. Akanksha_Rai mohit kumar 29 unknown2108 hardikkoriintern STL Competitive Programming Graph Graph STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 121, "s": 54, "text": "We have introduced Graph basics in Graph and its representations. " }, { "code": null, "e": 318, "s": 121, "text": "In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. " }, { "code": null, "e": 393, "s": 318, "text": "Following is an example undirected and unweighted graph with 5 vertices. " }, { "code": null, "e": 451, "s": 393, "text": "Below is an adjacency list representation of the graph. " }, { "code": null, "e": 531, "s": 451, "text": "We use vectors in STL to implement graphs using adjacency list representation. " }, { "code": null, "e": 669, "s": 531, "text": "vector: A sequence container. Here we use it to store adjacency lists of all vertices. We use vertex numbers as the index in this vector." }, { "code": null, "e": 853, "s": 669, "text": "The idea is to represent a graph as an array of vectors such that every vector represents the adjacency list of a vertex. Below is a complete STL-based C++ program for DFS Traversal. " }, { "code": null, "e": 869, "s": 853, "text": "Implementation:" }, { "code": null, "e": 873, "s": 869, "text": "C++" }, { "code": null, "e": 881, "s": 873, "text": "Python3" }, { "code": null, "e": 892, "s": 881, "text": "Javascript" }, { "code": "// A simple representation of graph using STL,// for the purpose of competitive programming#include<bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to do DFS of graph// recursively from a given vertex u.void DFSUtil(int u, vector<int> adj[], vector<bool> &visited){ visited[u] = true; cout << u << \" \"; for (int i=0; i<adj[u].size(); i++) if (visited[adj[u][i]] == false) DFSUtil(adj[u][i], adj, visited);} // This function does DFSUtil() for all// unvisited vertices.void DFS(vector<int> adj[], int V){ vector<bool> visited(V, false); for (int u=0; u<V; u++) if (visited[u] == false) DFSUtil(u, adj, visited);} // Driver codeint main(){ int V = 5; // The below line may not work on all // compilers. If it does not work on // your compiler, please replace it with // following // vector<int> *adj = new vector<int>[V]; vector<int> adj[V]; // Vertex numbers should be from 0 to 4. addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); DFS(adj, V); return 0;}", "e": 2228, "s": 892, "text": null }, { "code": "# A simple representation of graph using STL,# for the purpose of competitive programming # A utility function to add an edge in an# undirected graph.def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) return adj # A utility function to do DFS of graph# recursively from a given vertex u.def DFSUtil(u, adj, visited): visited[u] = True print(u, end = \" \") for i in range(len(adj[u])): if (visited[adj[u][i]] == False): DFSUtil(adj[u][i], adj, visited) # This function does DFSUtil() for all# unvisited vertices.def DFS(adj, V): visited = [False]*(V+1) for u in range(V): if (visited[u] == False): DFSUtil(u, adj, visited) # Driver codeif __name__ == '__main__': V = 5 # The below line may not work on all # compilers. If it does not work on # your compiler, please replace it with # following # vector<int> *adj = new vector<int>[V] adj = [[] for i in range(V)] # Vertex numbers should be from 0 to 4. adj = addEdge(adj, 0, 1) adj = addEdge(adj, 0, 4) adj = addEdge(adj, 1, 2) adj = addEdge(adj, 1, 3) adj = addEdge(adj, 1, 4) adj = addEdge(adj, 2, 3) adj = addEdge(adj, 3, 4) DFS(adj, V) # This code is contributed by mohit kumar 29.", "e": 3481, "s": 2228, "text": null }, { "code": "<script>// A simple representation of graph using STL,// for the purpose of competitive programming // A utility function to add an edge in an// undirected graph. function addEdge(adj,u,v) { adj[u].push(v); adj[v].push(u); } // A utility function to do DFS of graph// recursively from a given vertex u. function DFSUtil(u,adj,visited) { visited[u] = true; document.write(u+\" \"); for (let i=0; i<adj[u].length; i++) if (visited[adj[u][i]] == false) DFSUtil(adj[u][i], adj, visited); } // This function does DFSUtil() for all// unvisited vertices. function DFS(adj,V) { let visited=new Array(V); for(let i=0;i<V;i++) { visited[i]=false; } for (let u=0; u<V; u++) if (visited[u] == false) DFSUtil(u, adj, visited); } // Driver code let V = 5; // The below line may not work on all // compilers. If it does not work on // your compiler, please replace it with // following // vector<int> *adj = new vector<int>[V]; let adj=new Array(V); for(let i=0;i<V;i++) { adj[i]=[]; } // Vertex numbers should be from 0 to 4. addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); DFS(adj, V); // This code is contributed by unknown2108</script>", "e": 4962, "s": 3481, "text": null }, { "code": null, "e": 4973, "s": 4962, "text": "0 1 2 3 4 " }, { "code": null, "e": 5294, "s": 4973, "text": "Below are related articles: Graph implementation using STL for competitive programming | Set 2 (Weighted graph) Dijkstra’s Shortest Path Algorithm using priority_queue of STL Dijkstra’s shortest path algorithm using set in STL Kruskal’s Minimum Spanning Tree using STL in C++ Prim’s algorithm using priority_queue in STL" }, { "code": null, "e": 5563, "s": 5294, "text": "This article is contributed by Shubham Gupta. 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": 5576, "s": 5563, "text": "Akanksha_Rai" }, { "code": null, "e": 5591, "s": 5576, "text": "mohit kumar 29" }, { "code": null, "e": 5603, "s": 5591, "text": "unknown2108" }, { "code": null, "e": 5620, "s": 5603, "text": "hardikkoriintern" }, { "code": null, "e": 5624, "s": 5620, "text": "STL" }, { "code": null, "e": 5648, "s": 5624, "text": "Competitive Programming" }, { "code": null, "e": 5654, "s": 5648, "text": "Graph" }, { "code": null, "e": 5660, "s": 5654, "text": "Graph" }, { "code": null, "e": 5664, "s": 5660, "text": "STL" } ]
Defining DataFrame Schema with StructField and StructType
17 Jun, 2021 In this article, we will learn how to define DataFrame Schema with StructField and StructType. The StructType and StructFields are used to define a schema or its part for the Dataframe. This defines the name, datatype, and nullable flag for each column. StructType object is the collection of StructFields objects. It is a Built-in datatype that contains the list of StructField. Syntax: pyspark.sql.types.StructType(fields=None) pyspark.sql.types.StructField(name, datatype,nullable=True) Parameter: fields – List of StructField. name – Name of the column. datatype – type of data i.e, Integer, String, Float etc. nullable – whether fields are NULL/None or not. For defining schema we have to use the StructType() object in which we have to define or pass the StructField() which contains the name of the column, datatype of the column, and the nullable flag. We can write:- schema = StructType([StructField(column_name1,datatype(),nullable_flag), StructField(column_name2,datatype(),nullable_flag), StructField(column_name3,datatype(),nullable_flag) ]) Example 1: Defining DataFrame with schema with StructType and StructField. Python # importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import StructType, StructField, IntegerType, LongType, StringType, FloatType # function to create SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_mart.com") \ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Refrigerator", 112345, 4.0, 12499), ("LED TV", 114567, 4.2, 49999), ("Washing Machine", 113465, 3.9, 69999), ("T-shirt", 124378, 4.1, 1999), ("Jeans", 126754, 3.7, 3999), ("Running Shoes", 134565, 4.7, 1499), ("Face Mask", 145234, 4.6, 999)] # defining schema for the dataframe with # StructType and StructField schm = StructType([ StructField("Product Name", StringType(), True), StructField("Product ID", LongType(), True), StructField("Rating", FloatType(), True), StructField("Product Price", IntegerType(), True), ]) # calling function to create dataframe df = create_df(spark, input_data, schm) # visualizing dataframe and it's schema df.printSchema() df.show() Output: In the above code, we made the nullable flag=True. The use of making it True is that if while creating Dataframe any field value is NULL/None then also Dataframe will be created with none value. Example 2: Defining Dataframe schema with nested StructType. Python # importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import StructType, StructField, IntegerType, LongType, StringType, FloatType # function to create SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_mart.com") \ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [(("Refrigerator", 112345), 4.0, 12499), (("LED TV", 114567), 4.2, 49999), (("Washing Machine", 113465), 3.9, 69999), (("T-shirt", 124378), 4.1, 1999), (("Jeans", 126754), 3.7, 3999), (("Running Shoes", 134565), 4.7, 1499), (("Face Mask", 145234), 4.6, 999)] # defining schema for the dataframe using # nested StructType schm = StructType([ StructField('Product', StructType([ StructField('Product Name', StringType(), True), StructField('Product ID', LongType(), True), ])), StructField('Rating', FloatType(), True), StructField('Price', IntegerType(), True)]) # calling function to create dataframe df = create_df(spark, input_data, schm) # visualizing dataframe and it's schema df.printSchema() df.show(truncate=False) Output: Example 3: Changing Structure of Dataframe and adding new column Using PySpark Column Class. Python # importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import *from pyspark.sql.functions import col, struct, whenfrom pyspark.sql.types import StructType, StructField, IntegerType, LongType, StringType, FloatType # function to create SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_mart.com") \ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Refrigerator", 112345, 4.0, 12499), ("LED TV", 114567, 4.2, 49999), ("Washing Machine", 113465, 3.9, 69999), ("T-shirt", 124378, 4.1, 1999), ("Jeans", 126754, 3.7, 3999), ("Running Shoes", 134565, 4.7, 1499), ("Face Mask", 145234, 4.6, 999)] # defining schema for the dataframe using # nested StructType schm = StructType([ StructField("Product Name", StringType(), True), StructField("Product ID", LongType(), True), StructField("Rating", FloatType(), True), StructField("Product Price", IntegerType(), True)]) # calling function to create dataframe df = create_df(spark, input_data, schm) # copying the columns to the new struct # Product new_df = df.withColumn("Product", struct(col("Product Name").alias("Name"), col("Product ID").alias("ID"), col("Rating").alias("Rating"), col("Product Price").alias("Price"))) # adding new column according to the given # condition new_df = new_df.withColumn("Product Range", when(col("Product Price").cast( IntegerType()) < 1000, "Low") .when(col("Product Price").cast(IntegerType() ) < 7000, "Medium") .otherwise("High")) # dropping the columns as all column values # are copied in Product column new_df = new_df.drop("Product Name", "Product ID", "Rating", "Product Price") # visualizing dataframe and it's schema new_df.printSchema() new_df.show(truncate=False) Output: In the above example, we are changing the structure of the Dataframe using struct() function and copy the column into the new struct ‘Product’ and creating the Product column using withColumn() function. After copying the ‘Product Name’, ‘Product ID’, ‘Rating’, ‘Product Price’ to the new struct ‘Product’. We are adding the new column ‘Price Range’ using withColumn() function, according to the given condition that is split into three categories i.e, Low, Medium, and High. If ‘Product Price’ is less than 1000 then that product falls in the Low category and if ‘Product Price’ is less than 7000 then that product falls in the Medium category otherwise that product fall in the High category. After creating the new struct ‘Product’ and adding the new column ‘Price Range’ we have to drop the ‘Product Name’, ‘Product ID’, ‘Rating’, ‘Product Price’ column using the drop() function. Then printing the schema with changed Dataframe structure and added columns. Example 4: Defining Dataframe schema using the JSON format and StructType(). Python # importing necessary librariesfrom pyspark.sql import SparkSessionimport pyspark.sql.types as Timport json # function to create SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_mart.com") \ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Refrigerator", 4.0), ("LED TV", 4.2), ("Washing Machine", 3.9), ("T-shirt", 4.1) ] # defining schema for the dataframe with # StructType and StructField schm = T.StructType([ T.StructField("Product Name", T.StringType(), True), T.StructField("Rating", T.FloatType(), True) ]) # calling function to create dataframe df = create_df(spark, input_data, schm) # visualizing dataframe and it's schema print("Original Dataframe:-") df.printSchema() df.show() print("-------------------------------------------") print("Schema in json format:-") # storing schema in json format using # schema.json() function schma = df.schema.json() print(schma) # loading the json format schema schm1 = StructType.fromJson(json.loads(schma)) # creating dataframe using json format schema json_df = spark.createDataFrame( spark.sparkContext.parallelize(input_data), schm1) print("-------------------------------------------") print("Dataframe using json schema:-") # showing the created dataframe from json format # schema printing the schema of created dataframe json_df.printSchema() json_df.show() Output: Note: You can also store the JSON format in the file and use the file for defining the schema, code for this is also the same as above only you have to pass the JSON file in loads() function, in the above example, the schema in JSON format is stored in a variable, and we are using that variable for defining schema. Example 5: Defining Dataframe schema using StructType() with ArrayType() and MapType(). Python # importing necessary librariesfrom pyspark.sql import SparkSessionimport pyspark.sql.types as T # function to create SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_mart.com") \ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() # Data containing the Array and Map- key,value pair input_data = [ ("Alex", 'Buttler', ["Mathematics", "Computer Science"], {"Mathematics": 'Physics', "Chemistry": "Biology"}), ("Sam", "Samson", ["Chemistry, Biology"], {"Chemistry": 'Physics', "Mathematics": "Biology"}), ("Rossi", "Bryant", ["English", "Geography"], {"History": 'Geography', "Chemistry": "Biology"}), ("Sidz", "Murraz", ["History", "Environmental Science"], {"English": 'Environmental Science', "Chemistry": "Mathematics"}), ("Robert", "Cox", ["Physics", "English"], {"Computer Science": 'Environmental Science', "Chemistry": "Geography"}) ] # defining schema with ArrayType and MapType() # using StructType() and StructField() array_schm = StructType([ StructField('Firstname', StringType(), True), StructField('Lastname', StringType(), True), StructField('Subject', ArrayType(StringType()), True), StructField('Subject Combinations', MapType( StringType(), StringType()), True) ]) # calling function for creating the dataframe df = create_df(spark, input_data, array_schm) # printing schema of df and showing dataframe df.printSchema() df.show(truncate=False) Output: simranarora5sos Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 124, "s": 28, "text": "In this article, we will learn how to define DataFrame Schema with StructField and StructType. " }, { "code": null, "e": 283, "s": 124, "text": "The StructType and StructFields are used to define a schema or its part for the Dataframe. This defines the name, datatype, and nullable flag for each column." }, { "code": null, "e": 409, "s": 283, "text": "StructType object is the collection of StructFields objects. It is a Built-in datatype that contains the list of StructField." }, { "code": null, "e": 418, "s": 409, "text": "Syntax: " }, { "code": null, "e": 460, "s": 418, "text": "pyspark.sql.types.StructType(fields=None)" }, { "code": null, "e": 520, "s": 460, "text": "pyspark.sql.types.StructField(name, datatype,nullable=True)" }, { "code": null, "e": 531, "s": 520, "text": "Parameter:" }, { "code": null, "e": 561, "s": 531, "text": "fields – List of StructField." }, { "code": null, "e": 588, "s": 561, "text": "name – Name of the column." }, { "code": null, "e": 645, "s": 588, "text": "datatype – type of data i.e, Integer, String, Float etc." }, { "code": null, "e": 693, "s": 645, "text": "nullable – whether fields are NULL/None or not." }, { "code": null, "e": 906, "s": 693, "text": "For defining schema we have to use the StructType() object in which we have to define or pass the StructField() which contains the name of the column, datatype of the column, and the nullable flag. We can write:-" }, { "code": null, "e": 1121, "s": 906, "text": "schema = StructType([StructField(column_name1,datatype(),nullable_flag),\n StructField(column_name2,datatype(),nullable_flag),\n StructField(column_name3,datatype(),nullable_flag)\n ])" }, { "code": null, "e": 1196, "s": 1121, "text": "Example 1: Defining DataFrame with schema with StructType and StructField." }, { "code": null, "e": 1203, "s": 1196, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import StructType, StructField, IntegerType, LongType, StringType, FloatType # function to create SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_mart.com\") \\ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Refrigerator\", 112345, 4.0, 12499), (\"LED TV\", 114567, 4.2, 49999), (\"Washing Machine\", 113465, 3.9, 69999), (\"T-shirt\", 124378, 4.1, 1999), (\"Jeans\", 126754, 3.7, 3999), (\"Running Shoes\", 134565, 4.7, 1499), (\"Face Mask\", 145234, 4.6, 999)] # defining schema for the dataframe with # StructType and StructField schm = StructType([ StructField(\"Product Name\", StringType(), True), StructField(\"Product ID\", LongType(), True), StructField(\"Rating\", FloatType(), True), StructField(\"Product Price\", IntegerType(), True), ]) # calling function to create dataframe df = create_df(spark, input_data, schm) # visualizing dataframe and it's schema df.printSchema() df.show()", "e": 2632, "s": 1203, "text": null }, { "code": null, "e": 2640, "s": 2632, "text": "Output:" }, { "code": null, "e": 2836, "s": 2640, "text": "In the above code, we made the nullable flag=True. The use of making it True is that if while creating Dataframe any field value is NULL/None then also Dataframe will be created with none value. " }, { "code": null, "e": 2897, "s": 2836, "text": "Example 2: Defining Dataframe schema with nested StructType." }, { "code": null, "e": 2904, "s": 2897, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import StructType, StructField, IntegerType, LongType, StringType, FloatType # function to create SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_mart.com\") \\ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [((\"Refrigerator\", 112345), 4.0, 12499), ((\"LED TV\", 114567), 4.2, 49999), ((\"Washing Machine\", 113465), 3.9, 69999), ((\"T-shirt\", 124378), 4.1, 1999), ((\"Jeans\", 126754), 3.7, 3999), ((\"Running Shoes\", 134565), 4.7, 1499), ((\"Face Mask\", 145234), 4.6, 999)] # defining schema for the dataframe using # nested StructType schm = StructType([ StructField('Product', StructType([ StructField('Product Name', StringType(), True), StructField('Product ID', LongType(), True), ])), StructField('Rating', FloatType(), True), StructField('Price', IntegerType(), True)]) # calling function to create dataframe df = create_df(spark, input_data, schm) # visualizing dataframe and it's schema df.printSchema() df.show(truncate=False)", "e": 4410, "s": 2904, "text": null }, { "code": null, "e": 4418, "s": 4410, "text": "Output:" }, { "code": null, "e": 4511, "s": 4418, "text": "Example 3: Changing Structure of Dataframe and adding new column Using PySpark Column Class." }, { "code": null, "e": 4518, "s": 4511, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import *from pyspark.sql.functions import col, struct, whenfrom pyspark.sql.types import StructType, StructField, IntegerType, LongType, StringType, FloatType # function to create SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_mart.com\") \\ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Refrigerator\", 112345, 4.0, 12499), (\"LED TV\", 114567, 4.2, 49999), (\"Washing Machine\", 113465, 3.9, 69999), (\"T-shirt\", 124378, 4.1, 1999), (\"Jeans\", 126754, 3.7, 3999), (\"Running Shoes\", 134565, 4.7, 1499), (\"Face Mask\", 145234, 4.6, 999)] # defining schema for the dataframe using # nested StructType schm = StructType([ StructField(\"Product Name\", StringType(), True), StructField(\"Product ID\", LongType(), True), StructField(\"Rating\", FloatType(), True), StructField(\"Product Price\", IntegerType(), True)]) # calling function to create dataframe df = create_df(spark, input_data, schm) # copying the columns to the new struct # Product new_df = df.withColumn(\"Product\", struct(col(\"Product Name\").alias(\"Name\"), col(\"Product ID\").alias(\"ID\"), col(\"Rating\").alias(\"Rating\"), col(\"Product Price\").alias(\"Price\"))) # adding new column according to the given # condition new_df = new_df.withColumn(\"Product Range\", when(col(\"Product Price\").cast( IntegerType()) < 1000, \"Low\") .when(col(\"Product Price\").cast(IntegerType() ) < 7000, \"Medium\") .otherwise(\"High\")) # dropping the columns as all column values # are copied in Product column new_df = new_df.drop(\"Product Name\", \"Product ID\", \"Rating\", \"Product Price\") # visualizing dataframe and it's schema new_df.printSchema() new_df.show(truncate=False)", "e": 7032, "s": 4518, "text": null }, { "code": null, "e": 7040, "s": 7032, "text": "Output:" }, { "code": null, "e": 7244, "s": 7040, "text": "In the above example, we are changing the structure of the Dataframe using struct() function and copy the column into the new struct ‘Product’ and creating the Product column using withColumn() function." }, { "code": null, "e": 7347, "s": 7244, "text": "After copying the ‘Product Name’, ‘Product ID’, ‘Rating’, ‘Product Price’ to the new struct ‘Product’." }, { "code": null, "e": 7735, "s": 7347, "text": "We are adding the new column ‘Price Range’ using withColumn() function, according to the given condition that is split into three categories i.e, Low, Medium, and High. If ‘Product Price’ is less than 1000 then that product falls in the Low category and if ‘Product Price’ is less than 7000 then that product falls in the Medium category otherwise that product fall in the High category." }, { "code": null, "e": 8002, "s": 7735, "text": "After creating the new struct ‘Product’ and adding the new column ‘Price Range’ we have to drop the ‘Product Name’, ‘Product ID’, ‘Rating’, ‘Product Price’ column using the drop() function. Then printing the schema with changed Dataframe structure and added columns." }, { "code": null, "e": 8079, "s": 8002, "text": "Example 4: Defining Dataframe schema using the JSON format and StructType()." }, { "code": null, "e": 8086, "s": 8079, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSessionimport pyspark.sql.types as Timport json # function to create SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_mart.com\") \\ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Refrigerator\", 4.0), (\"LED TV\", 4.2), (\"Washing Machine\", 3.9), (\"T-shirt\", 4.1) ] # defining schema for the dataframe with # StructType and StructField schm = T.StructType([ T.StructField(\"Product Name\", T.StringType(), True), T.StructField(\"Rating\", T.FloatType(), True) ]) # calling function to create dataframe df = create_df(spark, input_data, schm) # visualizing dataframe and it's schema print(\"Original Dataframe:-\") df.printSchema() df.show() print(\"-------------------------------------------\") print(\"Schema in json format:-\") # storing schema in json format using # schema.json() function schma = df.schema.json() print(schma) # loading the json format schema schm1 = StructType.fromJson(json.loads(schma)) # creating dataframe using json format schema json_df = spark.createDataFrame( spark.sparkContext.parallelize(input_data), schm1) print(\"-------------------------------------------\") print(\"Dataframe using json schema:-\") # showing the created dataframe from json format # schema printing the schema of created dataframe json_df.printSchema() json_df.show()", "e": 9884, "s": 8086, "text": null }, { "code": null, "e": 9892, "s": 9884, "text": "Output:" }, { "code": null, "e": 10209, "s": 9892, "text": "Note: You can also store the JSON format in the file and use the file for defining the schema, code for this is also the same as above only you have to pass the JSON file in loads() function, in the above example, the schema in JSON format is stored in a variable, and we are using that variable for defining schema." }, { "code": null, "e": 10297, "s": 10209, "text": "Example 5: Defining Dataframe schema using StructType() with ArrayType() and MapType()." }, { "code": null, "e": 10304, "s": 10297, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSessionimport pyspark.sql.types as T # function to create SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_mart.com\") \\ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() # Data containing the Array and Map- key,value pair input_data = [ (\"Alex\", 'Buttler', [\"Mathematics\", \"Computer Science\"], {\"Mathematics\": 'Physics', \"Chemistry\": \"Biology\"}), (\"Sam\", \"Samson\", [\"Chemistry, Biology\"], {\"Chemistry\": 'Physics', \"Mathematics\": \"Biology\"}), (\"Rossi\", \"Bryant\", [\"English\", \"Geography\"], {\"History\": 'Geography', \"Chemistry\": \"Biology\"}), (\"Sidz\", \"Murraz\", [\"History\", \"Environmental Science\"], {\"English\": 'Environmental Science', \"Chemistry\": \"Mathematics\"}), (\"Robert\", \"Cox\", [\"Physics\", \"English\"], {\"Computer Science\": 'Environmental Science', \"Chemistry\": \"Geography\"}) ] # defining schema with ArrayType and MapType() # using StructType() and StructField() array_schm = StructType([ StructField('Firstname', StringType(), True), StructField('Lastname', StringType(), True), StructField('Subject', ArrayType(StringType()), True), StructField('Subject Combinations', MapType( StringType(), StringType()), True) ]) # calling function for creating the dataframe df = create_df(spark, input_data, array_schm) # printing schema of df and showing dataframe df.printSchema() df.show(truncate=False)", "e": 12099, "s": 10304, "text": null }, { "code": null, "e": 12107, "s": 12099, "text": "Output:" }, { "code": null, "e": 12123, "s": 12107, "text": "simranarora5sos" }, { "code": null, "e": 12130, "s": 12123, "text": "Picked" }, { "code": null, "e": 12145, "s": 12130, "text": "Python-Pyspark" }, { "code": null, "e": 12152, "s": 12145, "text": "Python" } ]
Python OpenCV: Optical Flow with Lucas-Kanade method
09 Mar, 2020 Prerequisites: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV. In this article, we will be learning how to apply the Lucas-Kanade method to track some points on a video. To track the points, first, we need to find the points to be tracked. For finding the points, we’ll use cv2.goodFeaturesToTrack(). Now, we will capture the first frame and detect some corner points. These points will be tracked using the Lucas-Kanade Algorithm provided by OpenCV, i.e, cv2.calcOpticalFlowPyrLK(). Syntax: cv2.calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts[, winSize[, maxLevel[, criteria]]]) Parameters:prevImg – first 8-bit input imagenextImg – second input imageprevPts – vector of 2D points for which the flow needs to be found.winSize – size of the search window at each pyramid level.maxLevel – 0-based maximal pyramid level number; if set to 0, pyramids are not used (single level), if set to 1, two levels are used, and so on.criteria – parameter, specifying the termination criteria of the iterative search algorithm. Return:nextPts – output vector of 2D points (with single-precision floating-point coordinates) containing the calculated new positions of input features in the second image; when OPTFLOW_USE_INITIAL_FLOW flag is passed, the vector must have the same size as in the input.status – output status vector (of unsigned chars); each element of the vector is set to 1 if the flow for the corresponding features has been found, otherwise, it is set to 0.err – output vector of errors; each element of the vector is set to an error for the corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn’t found then the error is not defined (use the status parameter to find such cases). Example: import numpy as npimport cv2 cap = cv2.VideoCapture('sample.mp4') # params for corner detectionfeature_params = dict( maxCorners = 100, qualityLevel = 0.3, minDistance = 7, blockSize = 7 ) # Parameters for lucas kanade optical flowlk_params = dict( winSize = (15, 15), maxLevel = 2, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) # Create some random colorscolor = np.random.randint(0, 255, (100, 3)) # Take first frame and find corners in itret, old_frame = cap.read()old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params) # Create a mask image for drawing purposesmask = np.zeros_like(old_frame) while(1): ret, frame = cap.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # calculate optical flow p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params) # Select good points good_new = p1[st == 1] good_old = p0[st == 1] # draw the tracks for i, (new, old) in enumerate(zip(good_new, good_old)): a, b = new.ravel() c, d = old.ravel() mask = cv2.line(mask, (a, b), (c, d), color[i].tolist(), 2) frame = cv2.circle(frame, (a, b), 5, color[i].tolist(), -1) img = cv2.add(frame, mask) cv2.imshow('frame', img) k = cv2.waitKey(25) if k == 27: break # Updating Previous frame and points old_gray = frame_gray.copy() p0 = good_new.reshape(-1, 1, 2) cv2.destroyAllWindows()cap.release() Output: Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2020" }, { "code": null, "e": 50, "s": 28, "text": "Prerequisites: OpenCV" }, { "code": null, "e": 578, "s": 50, "text": "OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV." }, { "code": null, "e": 999, "s": 578, "text": "In this article, we will be learning how to apply the Lucas-Kanade method to track some points on a video. To track the points, first, we need to find the points to be tracked. For finding the points, we’ll use cv2.goodFeaturesToTrack(). Now, we will capture the first frame and detect some corner points. These points will be tracked using the Lucas-Kanade Algorithm provided by OpenCV, i.e, cv2.calcOpticalFlowPyrLK()." }, { "code": null, "e": 1103, "s": 999, "text": "Syntax: cv2.calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts[, winSize[, maxLevel[, criteria]]])" }, { "code": null, "e": 1537, "s": 1103, "text": "Parameters:prevImg – first 8-bit input imagenextImg – second input imageprevPts – vector of 2D points for which the flow needs to be found.winSize – size of the search window at each pyramid level.maxLevel – 0-based maximal pyramid level number; if set to 0, pyramids are not used (single level), if set to 1, two levels are used, and so on.criteria – parameter, specifying the termination criteria of the iterative search algorithm." }, { "code": null, "e": 2250, "s": 1537, "text": "Return:nextPts – output vector of 2D points (with single-precision floating-point coordinates) containing the calculated new positions of input features in the second image; when OPTFLOW_USE_INITIAL_FLOW flag is passed, the vector must have the same size as in the input.status – output status vector (of unsigned chars); each element of the vector is set to 1 if the flow for the corresponding features has been found, otherwise, it is set to 0.err – output vector of errors; each element of the vector is set to an error for the corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn’t found then the error is not defined (use the status parameter to find such cases)." }, { "code": null, "e": 2259, "s": 2250, "text": "Example:" }, { "code": "import numpy as npimport cv2 cap = cv2.VideoCapture('sample.mp4') # params for corner detectionfeature_params = dict( maxCorners = 100, qualityLevel = 0.3, minDistance = 7, blockSize = 7 ) # Parameters for lucas kanade optical flowlk_params = dict( winSize = (15, 15), maxLevel = 2, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) # Create some random colorscolor = np.random.randint(0, 255, (100, 3)) # Take first frame and find corners in itret, old_frame = cap.read()old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params) # Create a mask image for drawing purposesmask = np.zeros_like(old_frame) while(1): ret, frame = cap.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # calculate optical flow p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params) # Select good points good_new = p1[st == 1] good_old = p0[st == 1] # draw the tracks for i, (new, old) in enumerate(zip(good_new, good_old)): a, b = new.ravel() c, d = old.ravel() mask = cv2.line(mask, (a, b), (c, d), color[i].tolist(), 2) frame = cv2.circle(frame, (a, b), 5, color[i].tolist(), -1) img = cv2.add(frame, mask) cv2.imshow('frame', img) k = cv2.waitKey(25) if k == 27: break # Updating Previous frame and points old_gray = frame_gray.copy() p0 = good_new.reshape(-1, 1, 2) cv2.destroyAllWindows()cap.release()", "e": 4229, "s": 2259, "text": null }, { "code": null, "e": 4237, "s": 4229, "text": "Output:" }, { "code": null, "e": 4251, "s": 4237, "text": "Python-OpenCV" }, { "code": null, "e": 4258, "s": 4251, "text": "Python" } ]
Autoboxing and Unboxing in Java
20 Apr, 2022 In Java, primitive data types are treated differently so do there comes the introduction of wrapper classes where two components play a role namely Autoboxing and Unboxing. Autoboxing refers to the conversion of a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is: Passed as a parameter to a method that expects an object of the corresponding wrapper class. Assigned to a variable of the corresponding wrapper class. Unboxing on the other hand refers to converting an object of a wrapper type to its corresponding primitive value. For example conversion of Integer to int. The Java compiler applies to unbox when an object of a wrapper class is: Passed as a parameter to a method that expects a value of the corresponding primitive type. Assigned to a variable of the corresponding primitive type. The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing. Now let us discuss a few advantages of autoboxing and unboxing in order to get why we are using it. Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly. Example 1: Java // Java program to illustrate the Concept// of Autoboxing and Unboxing // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an Integer Object // with custom value say it be 10 Integer i = new Integer(10); // Unboxing the Object int i1 = i; // Print statements System.out.println("Value of i:" + i); System.out.println("Value of i1: " + i1); // Autoboxing of character Character gfg = 'a'; // Auto-unboxing of Character char ch = gfg; // Print statements System.out.println("Value of ch: " + ch); System.out.println(" Value of gfg: " + gfg); }} Output: Let’s understand how the compiler did autoboxing and unboxing in the example of Collections in Java using generics. Example 2: Java // Java Program to Illustrate Autoboxing // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty Arraylist of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Adding the int primitives type values // using add() method // Autoboxing al.add(1); al.add(2); al.add(24); // Printing the ArrayList elements System.out.println("ArrayList: " + al); }} ArrayList: [1, 2, 24] Output explanation: In the above example, we have created a list of elements of the Integer type. We are adding int primitive type values instead of Integer Object and the code is successfully compiled. It does not generate a compile-time error as the Java compiler creates an Integer wrapper Object from primitive int i and adds it to the list. Example 3: Java // Java Program to Illustrate Autoboxing // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of integer type List<Integer> list = new ArrayList<Integer>(); // Adding the int primitives type values by // converting them into Integer wrapper object for (int i = 0; i < 10; i++) System.out.println( list.add(Integer.valueOf(i))); }} true true true true true true true true true true Another example of auto and unboxing is to find the sum of odd numbers in a list. An important point in the program is that the operators remainder (%) and unary plus (+=) operators do not apply to Integer objects. But still, code compiles successfully because the unboxing of Integer Object to primitive int value is taking place by invoking intValue() method at runtime. Example 4: Java // Java Program to Illustrate Find Sum of Odd Numbers// using Autoboxing and Unboxing // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To sum odd numbers public static int sumOfOddNumber(List<Integer> list) { // Initially setting sum to zero int sum = 0; for (Integer i : list) { // Unboxing of i automatically if (i % 2 != 0) sum += i; // Unboxing of i is done automatically // using intvalue implicitly if (i.intValue() % 2 != 0) sum += i.intValue(); } // Returning the odd sum return sum; } // Method 2 // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of integer type List<Integer> list = new ArrayList<Integer>(); // Adding the int primitives type values to List for (int i = 0; i < 10; i++) list.add(i); // Getting sum of all odd numbers in List int sumOdd = sumOfOddNumber(list); // Printing sum of odd numbers System.out.println("Sum of odd numbers = " + sumOdd); }} Sum of odd numbers = 50 This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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. solankimayank surinderdawra388 java-wrapper-class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Apr, 2022" }, { "code": null, "e": 465, "s": 52, "text": "In Java, primitive data types are treated differently so do there comes the introduction of wrapper classes where two components play a role namely Autoboxing and Unboxing. Autoboxing refers to the conversion of a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is: " }, { "code": null, "e": 558, "s": 465, "text": "Passed as a parameter to a method that expects an object of the corresponding wrapper class." }, { "code": null, "e": 617, "s": 558, "text": "Assigned to a variable of the corresponding wrapper class." }, { "code": null, "e": 847, "s": 617, "text": "Unboxing on the other hand refers to converting an object of a wrapper type to its corresponding primitive value. For example conversion of Integer to int. The Java compiler applies to unbox when an object of a wrapper class is: " }, { "code": null, "e": 939, "s": 847, "text": "Passed as a parameter to a method that expects a value of the corresponding primitive type." }, { "code": null, "e": 999, "s": 939, "text": "Assigned to a variable of the corresponding primitive type." }, { "code": null, "e": 1252, "s": 999, "text": "The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing. Now let us discuss a few advantages of autoboxing and unboxing in order to get why we are using it. " }, { "code": null, "e": 1338, "s": 1252, "text": "Autoboxing and unboxing lets developers write cleaner code, making it easier to read." }, { "code": null, "e": 1480, "s": 1338, "text": "The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly." }, { "code": null, "e": 1491, "s": 1480, "text": "Example 1:" }, { "code": null, "e": 1496, "s": 1491, "text": "Java" }, { "code": "// Java program to illustrate the Concept// of Autoboxing and Unboxing // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an Integer Object // with custom value say it be 10 Integer i = new Integer(10); // Unboxing the Object int i1 = i; // Print statements System.out.println(\"Value of i:\" + i); System.out.println(\"Value of i1: \" + i1); // Autoboxing of character Character gfg = 'a'; // Auto-unboxing of Character char ch = gfg; // Print statements System.out.println(\"Value of ch: \" + ch); System.out.println(\" Value of gfg: \" + gfg); }}", "e": 2258, "s": 1496, "text": null }, { "code": null, "e": 2266, "s": 2258, "text": "Output:" }, { "code": null, "e": 2382, "s": 2266, "text": "Let’s understand how the compiler did autoboxing and unboxing in the example of Collections in Java using generics." }, { "code": null, "e": 2393, "s": 2382, "text": "Example 2:" }, { "code": null, "e": 2398, "s": 2393, "text": "Java" }, { "code": "// Java Program to Illustrate Autoboxing // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty Arraylist of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Adding the int primitives type values // using add() method // Autoboxing al.add(1); al.add(2); al.add(24); // Printing the ArrayList elements System.out.println(\"ArrayList: \" + al); }}", "e": 2965, "s": 2398, "text": null }, { "code": null, "e": 2987, "s": 2965, "text": "ArrayList: [1, 2, 24]" }, { "code": null, "e": 3008, "s": 2987, "text": "Output explanation: " }, { "code": null, "e": 3335, "s": 3008, "text": "In the above example, we have created a list of elements of the Integer type. We are adding int primitive type values instead of Integer Object and the code is successfully compiled. It does not generate a compile-time error as the Java compiler creates an Integer wrapper Object from primitive int i and adds it to the list. " }, { "code": null, "e": 3346, "s": 3335, "text": "Example 3:" }, { "code": null, "e": 3351, "s": 3346, "text": "Java" }, { "code": "// Java Program to Illustrate Autoboxing // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of integer type List<Integer> list = new ArrayList<Integer>(); // Adding the int primitives type values by // converting them into Integer wrapper object for (int i = 0; i < 10; i++) System.out.println( list.add(Integer.valueOf(i))); }}", "e": 3892, "s": 3351, "text": null }, { "code": null, "e": 3942, "s": 3892, "text": "true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue" }, { "code": null, "e": 4316, "s": 3942, "text": "Another example of auto and unboxing is to find the sum of odd numbers in a list. An important point in the program is that the operators remainder (%) and unary plus (+=) operators do not apply to Integer objects. But still, code compiles successfully because the unboxing of Integer Object to primitive int value is taking place by invoking intValue() method at runtime. " }, { "code": null, "e": 4327, "s": 4316, "text": "Example 4:" }, { "code": null, "e": 4332, "s": 4327, "text": "Java" }, { "code": "// Java Program to Illustrate Find Sum of Odd Numbers// using Autoboxing and Unboxing // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To sum odd numbers public static int sumOfOddNumber(List<Integer> list) { // Initially setting sum to zero int sum = 0; for (Integer i : list) { // Unboxing of i automatically if (i % 2 != 0) sum += i; // Unboxing of i is done automatically // using intvalue implicitly if (i.intValue() % 2 != 0) sum += i.intValue(); } // Returning the odd sum return sum; } // Method 2 // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of integer type List<Integer> list = new ArrayList<Integer>(); // Adding the int primitives type values to List for (int i = 0; i < 10; i++) list.add(i); // Getting sum of all odd numbers in List int sumOdd = sumOfOddNumber(list); // Printing sum of odd numbers System.out.println(\"Sum of odd numbers = \" + sumOdd); }}", "e": 5569, "s": 4332, "text": null }, { "code": null, "e": 5593, "s": 5569, "text": "Sum of odd numbers = 50" }, { "code": null, "e": 6016, "s": 5593, "text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 6030, "s": 6016, "text": "solankimayank" }, { "code": null, "e": 6047, "s": 6030, "text": "surinderdawra388" }, { "code": null, "e": 6066, "s": 6047, "text": "java-wrapper-class" }, { "code": null, "e": 6071, "s": 6066, "text": "Java" }, { "code": null, "e": 6076, "s": 6071, "text": "Java" } ]
reflect.Indirect() Function in Golang with Examples
28 Apr, 2020 Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program. Syntax: func Indirect(v Value) Value Parameters: This function takes the following parameters: v: This parameter is the value to be passed. Return Value: This function returns the value that v points to. Below examples illustrate the use of the above method in Golang: Example 1: // Golang program to illustrate// reflect.Indirect() Function package main import ( "fmt" "reflect") // Main functionfunc main() { val1:= []int {1, 2, 3, 4} var val2 reflect.Value = reflect.ValueOf(&val1) fmt.Println("&val2 type : ", val2.Kind()) // using the function indirectI := reflect.Indirect(val2) fmt.Println("indirectI type : ", indirectI.Kind()) fmt.Println("indirectI value : ", indirectI) } Output: &val2 type : ptr indirectI type : slice indirectI value : [1 2 3 4] Example 2: // Golang program to illustrate// reflect.Indirect() Function package main import ( "fmt" "reflect") // Main functionfunc main() { var val1 []int var val2 [3]string var val3 = make(map[int]string) var val4 reflect.Value = reflect.ValueOf(&val1) indirectI := reflect.Indirect(val4) fmt.Println("val1: ", indirectI.Kind()) var val5 reflect.Value = reflect.ValueOf(&val2) indirectStr := reflect.Indirect(val5) fmt.Println("val2 type : ", indirectStr.Kind()) var val6 reflect.Value = reflect.ValueOf(&val3) fmt.Println("&val3 type : ", val6.Kind()) indirectM := reflect.Indirect(val6) fmt.Println("val3 type : ", indirectM.Kind()) } Output: val1: slice val2 type : array &val3 type : ptr val3 type : map Golang-reflect Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2020" }, { "code": null, "e": 473, "s": 28, "text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program." }, { "code": null, "e": 481, "s": 473, "text": "Syntax:" }, { "code": null, "e": 511, "s": 481, "text": "func Indirect(v Value) Value\n" }, { "code": null, "e": 569, "s": 511, "text": "Parameters: This function takes the following parameters:" }, { "code": null, "e": 614, "s": 569, "text": "v: This parameter is the value to be passed." }, { "code": null, "e": 678, "s": 614, "text": "Return Value: This function returns the value that v points to." }, { "code": null, "e": 743, "s": 678, "text": "Below examples illustrate the use of the above method in Golang:" }, { "code": null, "e": 754, "s": 743, "text": "Example 1:" }, { "code": "// Golang program to illustrate// reflect.Indirect() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { val1:= []int {1, 2, 3, 4} var val2 reflect.Value = reflect.ValueOf(&val1) fmt.Println(\"&val2 type : \", val2.Kind()) // using the function indirectI := reflect.Indirect(val2) fmt.Println(\"indirectI type : \", indirectI.Kind()) fmt.Println(\"indirectI value : \", indirectI) }", "e": 1219, "s": 754, "text": null }, { "code": null, "e": 1227, "s": 1219, "text": "Output:" }, { "code": null, "e": 1301, "s": 1227, "text": "&val2 type : ptr\nindirectI type : slice\nindirectI value : [1 2 3 4]\n" }, { "code": null, "e": 1312, "s": 1301, "text": "Example 2:" }, { "code": "// Golang program to illustrate// reflect.Indirect() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { var val1 []int var val2 [3]string var val3 = make(map[int]string) var val4 reflect.Value = reflect.ValueOf(&val1) indirectI := reflect.Indirect(val4) fmt.Println(\"val1: \", indirectI.Kind()) var val5 reflect.Value = reflect.ValueOf(&val2) indirectStr := reflect.Indirect(val5) fmt.Println(\"val2 type : \", indirectStr.Kind()) var val6 reflect.Value = reflect.ValueOf(&val3) fmt.Println(\"&val3 type : \", val6.Kind()) indirectM := reflect.Indirect(val6) fmt.Println(\"val3 type : \", indirectM.Kind()) }", "e": 2037, "s": 1312, "text": null }, { "code": null, "e": 2045, "s": 2037, "text": "Output:" }, { "code": null, "e": 2113, "s": 2045, "text": "val1: slice\nval2 type : array\n&val3 type : ptr\nval3 type : map\n" }, { "code": null, "e": 2128, "s": 2113, "text": "Golang-reflect" }, { "code": null, "e": 2140, "s": 2128, "text": "Go Language" } ]
Excel Dynamic Chart Linked with a Drop-down List
27 Dec, 2021 Dynamic Chart using drop-down list is very helpful when we deal with tons of grouped data and perform comparative analysis. For example, an E-commerce site sells different types of products. They can create a drop-down list for every product and in the chart, they can see the sales details in the last ten years. In this article, we are going to see how to create a dynamic chart with a drop-down list using a suitable example shown below. Example: Consider the table below which shows the details of the ratings provided by our mentors to different students in the courses they have enrolled in. The rating is on a scale of 0-5 based on their performance. The goal is to create a single drop-down list for the courses and associate a chart with it. Follow the below steps to implement a dynamic chart linked with a drop-down menu in Excel: Step 1: Insert the data set into an Excel sheet in the cells as shown above. Step 2: Now select any cell where you want to create the drop-down list for the courses. Step 3: Now click on the Data tab from the top of the Excel window and then click on Data Validation. Step 4: In the Data Validation dialog box : In Allow: Select List. In Source: Select the cell range for the columns. You can enter manually or select the cell range by clicking the cell followed by dragging the AutoFill Options as shown below. Step 5: The drop-down list is ready and now you can format it by changing the color, font size. This drop-down list will do nothing as we have not yet associated it with any Formulas. It will just show the list of courses available in the list. Step 6: It is the most important step. Now we have to associate this drop-down list with the data of the original table using the Formulas. In our case, we have used the INDEX function and MATCH function for creating the Formula. The syntax for the INDEX function is : = INDEX(array,row_num,[col_num],[area_num]) array : range of cells The syntax for the MATCH function is : = MATCH(lookup_value, lookup_array, [match_type]) [match_type] : It denotes whether we need an exact match or appropriate match. The values can be 1,0,-1. In our case, the [match_type] is “0” since we need an exact match with the original data set. Step 7: Now copy and paste all the names in a random cell in Excel where we will create the formula. 8. Now copy the cell location of the drop-down where you have copied the names of the cell. It would be the column name for the dynamic set. = Cell_Location In our case the Cell_Location is B9. Click Enter. It will show whatever is being shown in the cell where the drop-down list is created. Step 9: Now write the Formula as shown below to create a dynamic data set. In the Formula, we have used two MATCH functions. One is for matching the set of Rows for names and the second one is for matching the set of Columns. Step 10: Click Enter. The first data will be inserted in the column. Now drag the AutoFill Options and all the data will be copied from the original table. Now, successfully we have created a dynamic list data set. The drop-down list is now active. Currently, it is showing the ratings of students for the course “Python”. Now, if you select “DSA” from the drop-down the data will be automatically updated. Step 11: Select the data set created in step 9 and go to Insert followed by Chart Groups and insert a suitable chart. Step 12: The Dynamic Chart is now ready to use. You can change the courses using the drop-down list and the chart will be automatically updated as shown below. You can format the chart and add suitable titles, axes title, data labels, etc. Dynamic Chart with drop-down list abhishek0719kadiyan simmytarika5 Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Dec, 2021" }, { "code": null, "e": 367, "s": 52, "text": "Dynamic Chart using drop-down list is very helpful when we deal with tons of grouped data and perform comparative analysis. For example, an E-commerce site sells different types of products. They can create a drop-down list for every product and in the chart, they can see the sales details in the last ten years. " }, { "code": null, "e": 494, "s": 367, "text": "In this article, we are going to see how to create a dynamic chart with a drop-down list using a suitable example shown below." }, { "code": null, "e": 805, "s": 494, "text": "Example: Consider the table below which shows the details of the ratings provided by our mentors to different students in the courses they have enrolled in. The rating is on a scale of 0-5 based on their performance. The goal is to create a single drop-down list for the courses and associate a chart with it. " }, { "code": null, "e": 896, "s": 805, "text": "Follow the below steps to implement a dynamic chart linked with a drop-down menu in Excel:" }, { "code": null, "e": 973, "s": 896, "text": "Step 1: Insert the data set into an Excel sheet in the cells as shown above." }, { "code": null, "e": 1062, "s": 973, "text": "Step 2: Now select any cell where you want to create the drop-down list for the courses." }, { "code": null, "e": 1164, "s": 1062, "text": "Step 3: Now click on the Data tab from the top of the Excel window and then click on Data Validation." }, { "code": null, "e": 1208, "s": 1164, "text": "Step 4: In the Data Validation dialog box :" }, { "code": null, "e": 1231, "s": 1208, "text": "In Allow: Select List." }, { "code": null, "e": 1408, "s": 1231, "text": "In Source: Select the cell range for the columns. You can enter manually or select the cell range by clicking the cell followed by dragging the AutoFill Options as shown below." }, { "code": null, "e": 1653, "s": 1408, "text": "Step 5: The drop-down list is ready and now you can format it by changing the color, font size. This drop-down list will do nothing as we have not yet associated it with any Formulas. It will just show the list of courses available in the list." }, { "code": null, "e": 1883, "s": 1653, "text": "Step 6: It is the most important step. Now we have to associate this drop-down list with the data of the original table using the Formulas. In our case, we have used the INDEX function and MATCH function for creating the Formula." }, { "code": null, "e": 1922, "s": 1883, "text": "The syntax for the INDEX function is :" }, { "code": null, "e": 1990, "s": 1922, "text": "= INDEX(array,row_num,[col_num],[area_num])\n\narray : range of cells" }, { "code": null, "e": 2029, "s": 1990, "text": "The syntax for the MATCH function is :" }, { "code": null, "e": 2185, "s": 2029, "text": "= MATCH(lookup_value, lookup_array, [match_type])\n\n[match_type] : It denotes whether we need an exact match or appropriate match. The values can be 1,0,-1." }, { "code": null, "e": 2279, "s": 2185, "text": "In our case, the [match_type] is “0” since we need an exact match with the original data set." }, { "code": null, "e": 2380, "s": 2279, "text": "Step 7: Now copy and paste all the names in a random cell in Excel where we will create the formula." }, { "code": null, "e": 2521, "s": 2380, "text": "8. Now copy the cell location of the drop-down where you have copied the names of the cell. It would be the column name for the dynamic set." }, { "code": null, "e": 2537, "s": 2521, "text": "= Cell_Location" }, { "code": null, "e": 2575, "s": 2537, "text": "In our case the Cell_Location is B9. " }, { "code": null, "e": 2674, "s": 2575, "text": "Click Enter. It will show whatever is being shown in the cell where the drop-down list is created." }, { "code": null, "e": 2749, "s": 2674, "text": "Step 9: Now write the Formula as shown below to create a dynamic data set." }, { "code": null, "e": 2900, "s": 2749, "text": "In the Formula, we have used two MATCH functions. One is for matching the set of Rows for names and the second one is for matching the set of Columns." }, { "code": null, "e": 3115, "s": 2900, "text": "Step 10: Click Enter. The first data will be inserted in the column. Now drag the AutoFill Options and all the data will be copied from the original table. Now, successfully we have created a dynamic list data set." }, { "code": null, "e": 3308, "s": 3115, "text": "The drop-down list is now active. Currently, it is showing the ratings of students for the course “Python”. Now, if you select “DSA” from the drop-down the data will be automatically updated. " }, { "code": null, "e": 3426, "s": 3308, "text": "Step 11: Select the data set created in step 9 and go to Insert followed by Chart Groups and insert a suitable chart." }, { "code": null, "e": 3666, "s": 3426, "text": "Step 12: The Dynamic Chart is now ready to use. You can change the courses using the drop-down list and the chart will be automatically updated as shown below. You can format the chart and add suitable titles, axes title, data labels, etc." }, { "code": null, "e": 3700, "s": 3666, "text": "Dynamic Chart with drop-down list" }, { "code": null, "e": 3720, "s": 3700, "text": "abhishek0719kadiyan" }, { "code": null, "e": 3733, "s": 3720, "text": "simmytarika5" }, { "code": null, "e": 3739, "s": 3733, "text": "Excel" } ]
TreeMap entrySet() Method in Java
09 Jul, 2018 The java.util.TreeMap.entrySet() method in Java is used to create a set out of the same elements contained in the treemap. It basically returns a set view of the treemap or we can create a new set and store the map elements into them. Syntax: tree_map.entrySet() Parameters: The method does not take any parameter. Return Value: The method returns a set having same elements as the treemap. Below programs are used to illustrate the working of java.util.TreeMap.entrySet() Method:Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the entrySet() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Displaying the TreeMap System.out.println("Initial Mappings are: " + tree_map); // Using entrySet() to get the set view System.out.println("The set is: " + tree_map.entrySet()); }} Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} The set is: [10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You] Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the entrySet() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys tree_map.put("Geeks", 10); tree_map.put("4", 15); tree_map.put("Geeks", 20); tree_map.put("Welcomes", 25); tree_map.put("You", 30); // Displaying the TreeMap System.out.println("Initial Mappings are: " + tree_map); // Using entrySet() to get the set view System.out.println("The set is: " + tree_map.entrySet()); }} Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30} The set is: [4=15, Geeks=20, Welcomes=25, You=30] Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Java-Collections java-TreeMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2018" }, { "code": null, "e": 263, "s": 28, "text": "The java.util.TreeMap.entrySet() method in Java is used to create a set out of the same elements contained in the treemap. It basically returns a set view of the treemap or we can create a new set and store the map elements into them." }, { "code": null, "e": 271, "s": 263, "text": "Syntax:" }, { "code": null, "e": 291, "s": 271, "text": "tree_map.entrySet()" }, { "code": null, "e": 343, "s": 291, "text": "Parameters: The method does not take any parameter." }, { "code": null, "e": 419, "s": 343, "text": "Return Value: The method returns a set having same elements as the treemap." }, { "code": null, "e": 558, "s": 419, "text": "Below programs are used to illustrate the working of java.util.TreeMap.entrySet() Method:Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the entrySet() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Displaying the TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Using entrySet() to get the set view System.out.println(\"The set is: \" + tree_map.entrySet()); }}", "e": 1248, "s": 558, "text": null }, { "code": null, "e": 1379, "s": 1248, "text": "Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}\nThe set is: [10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You]\n" }, { "code": null, "e": 1429, "s": 1379, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the entrySet() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys tree_map.put(\"Geeks\", 10); tree_map.put(\"4\", 15); tree_map.put(\"Geeks\", 20); tree_map.put(\"Welcomes\", 25); tree_map.put(\"You\", 30); // Displaying the TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Using entrySet() to get the set view System.out.println(\"The set is: \" + tree_map.entrySet()); }}", "e": 2119, "s": 1429, "text": null }, { "code": null, "e": 2230, "s": 2119, "text": "Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}\nThe set is: [4=15, Geeks=20, Welcomes=25, You=30]\n" }, { "code": null, "e": 2354, "s": 2230, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 2371, "s": 2354, "text": "Java-Collections" }, { "code": null, "e": 2384, "s": 2371, "text": "java-TreeMap" }, { "code": null, "e": 2389, "s": 2384, "text": "Java" }, { "code": null, "e": 2394, "s": 2389, "text": "Java" }, { "code": null, "e": 2411, "s": 2394, "text": "Java-Collections" } ]
Docker – WORKDIR Instruction
28 Oct, 2020 WORKDIR instruction is used to set the working directory for all the subsequent Dockerfile instructions. Some frequently used instructions in a Dockerfile are RUN, ADD, CMD, ENTRYPOINT, and COPY. If the WORKDIR is not manually created, it gets created automatically during the processing of the instructions. Some points to be noted when using the WORKDIR instruction are as follows: WORKDIR does not create new intermediate Image layers. It adds metadata to the Image Config. You can have multiple WORKDIR instructions in your Dockerfile. If you use relative paths as Working Directory, it will be relative to the previous Working Directory. The default path is / In this article, we will be discussing how to use WORKDIR instruction in your Dockerfile. We will also discuss 2 other ways to issue Working Directory inside your Dockerfile. Follow the below steps to work with the WORKDIR instruction: You can use the following template to create the Dockerfile. FROM ubuntu:latest WORKDIR /my-work-dir To build the Docker Image, you can use the Docker Build command. sudo docker build -t workdir-demo To run the Docker Container, you can use the Docker Run command. sudo docker run -it workdir-demo The above command opens the bash for the container. You can use the print working directory (pwd) command, to print the working directory. Now. Let’s discuss ways to issue a working directory in a Dockerfile. There is 2 possible way to do so, and both of them are explained below: Let’s look at how you can specify a relative path with WORKDIR instruction. The first step is to create a Dockerfile as mentioned below: FROM ubuntu:latest WORKDIR /my-work-dir RUN echo "work directory 1" > file1.txt WORKDIR /my-work-dir-2 RUN echo "work directory 2" > file2.txt Now, build and run the Docker Container. sudo docker build -t workdir-demo . sudo docker run -it workdir-demo bash Finally, print the working directory. pwd The first echo statement runs with the working directory set to the “my-work-dir” folder. That’s why if you use ls command to see the contents of the folder, you will find “file1.txt” inside the “my-work-dir” folder. The second WORKDIR instruction changes the Working Directory to “my-work-dir-2” and hence, the file “file2.txt” is inside that folder. The second way to issue a working directory is by making use of the environment variables. Follow the below steps to take so: The first step is to use the following Dockerfile template as shown below: FROM ubuntu:latest ENV DIRPATH /app WORKDIR $DIRPATH Here, we have set the environment variable DIRPATH to the /app directory and set the WORKDIR. Now, after running the Docker Container, you will find the directory set as /app. sudo docker build -t workdir-demo . sudo docker run -it workdir-demo pwd To conclude, in this article, we discussed how to use the WORKDIR instruction in the Dockerfile to set the working directory. We also saw how to set a working directory using relative paths and environment variables. Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2020" }, { "code": null, "e": 414, "s": 28, "text": "WORKDIR instruction is used to set the working directory for all the subsequent Dockerfile instructions. Some frequently used instructions in a Dockerfile are RUN, ADD, CMD, ENTRYPOINT, and COPY. If the WORKDIR is not manually created, it gets created automatically during the processing of the instructions. Some points to be noted when using the WORKDIR instruction are as follows: " }, { "code": null, "e": 469, "s": 414, "text": "WORKDIR does not create new intermediate Image layers." }, { "code": null, "e": 507, "s": 469, "text": "It adds metadata to the Image Config." }, { "code": null, "e": 570, "s": 507, "text": "You can have multiple WORKDIR instructions in your Dockerfile." }, { "code": null, "e": 673, "s": 570, "text": "If you use relative paths as Working Directory, it will be relative to the previous Working Directory." }, { "code": null, "e": 695, "s": 673, "text": "The default path is /" }, { "code": null, "e": 931, "s": 695, "text": "In this article, we will be discussing how to use WORKDIR instruction in your Dockerfile. We will also discuss 2 other ways to issue Working Directory inside your Dockerfile. Follow the below steps to work with the WORKDIR instruction:" }, { "code": null, "e": 992, "s": 931, "text": "You can use the following template to create the Dockerfile." }, { "code": null, "e": 1034, "s": 992, "text": "FROM ubuntu:latest\nWORKDIR /my-work-dir\n\n" }, { "code": null, "e": 1099, "s": 1034, "text": "To build the Docker Image, you can use the Docker Build command." }, { "code": null, "e": 1135, "s": 1099, "text": "sudo docker build -t workdir-demo\n\n" }, { "code": null, "e": 1200, "s": 1135, "text": "To run the Docker Container, you can use the Docker Run command." }, { "code": null, "e": 1235, "s": 1200, "text": "sudo docker run -it workdir-demo\n\n" }, { "code": null, "e": 1287, "s": 1235, "text": "The above command opens the bash for the container." }, { "code": null, "e": 1374, "s": 1287, "text": "You can use the print working directory (pwd) command, to print the working directory." }, { "code": null, "e": 1516, "s": 1374, "text": "Now. Let’s discuss ways to issue a working directory in a Dockerfile. There is 2 possible way to do so, and both of them are explained below:" }, { "code": null, "e": 1592, "s": 1516, "text": "Let’s look at how you can specify a relative path with WORKDIR instruction." }, { "code": null, "e": 1653, "s": 1592, "text": "The first step is to create a Dockerfile as mentioned below:" }, { "code": null, "e": 1797, "s": 1653, "text": "FROM ubuntu:latest\nWORKDIR /my-work-dir\nRUN echo \"work directory 1\" > file1.txt\nWORKDIR /my-work-dir-2\nRUN echo \"work directory 2\" > file2.txt\n" }, { "code": null, "e": 1838, "s": 1797, "text": "Now, build and run the Docker Container." }, { "code": null, "e": 1913, "s": 1838, "text": "sudo docker build -t workdir-demo .\nsudo docker run -it workdir-demo bash\n" }, { "code": null, "e": 1951, "s": 1913, "text": "Finally, print the working directory." }, { "code": null, "e": 1956, "s": 1951, "text": "pwd\n" }, { "code": null, "e": 2308, "s": 1956, "text": "The first echo statement runs with the working directory set to the “my-work-dir” folder. That’s why if you use ls command to see the contents of the folder, you will find “file1.txt” inside the “my-work-dir” folder. The second WORKDIR instruction changes the Working Directory to “my-work-dir-2” and hence, the file “file2.txt” is inside that folder." }, { "code": null, "e": 2434, "s": 2308, "text": "The second way to issue a working directory is by making use of the environment variables. Follow the below steps to take so:" }, { "code": null, "e": 2509, "s": 2434, "text": "The first step is to use the following Dockerfile template as shown below:" }, { "code": null, "e": 2563, "s": 2509, "text": "FROM ubuntu:latest\nENV DIRPATH /app\nWORKDIR $DIRPATH\n" }, { "code": null, "e": 2657, "s": 2563, "text": "Here, we have set the environment variable DIRPATH to the /app directory and set the WORKDIR." }, { "code": null, "e": 2740, "s": 2657, "text": "Now, after running the Docker Container, you will find the directory set as /app. " }, { "code": null, "e": 2814, "s": 2740, "text": "sudo docker build -t workdir-demo .\nsudo docker run -it workdir-demo\npwd\n" }, { "code": null, "e": 3031, "s": 2814, "text": "To conclude, in this article, we discussed how to use the WORKDIR instruction in the Dockerfile to set the working directory. We also saw how to set a working directory using relative paths and environment variables." }, { "code": null, "e": 3048, "s": 3031, "text": "Docker Container" }, { "code": null, "e": 3054, "s": 3048, "text": "linux" }, { "code": null, "e": 3080, "s": 3054, "text": "Advanced Computer Subject" } ]
How to pass express errors message to Angular view ?
19 Jul, 2021 There are mainly two parts of a web application, one is front-end and another is the backend. We will start with the backend first. The express catches all errors that occur while running route handlers and middleware. We have to just send them properly to the frontend for user knowledge. Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler, so you don’t need to write your own to get started. Approach: Create the Angular app to be used. Create the backend routes as well. We send the error during user signup fail. So we have created the “/signup” route in the express app. Now on signup failure send the error using res.status(401).json() method. Now on the frontend side, the auth.service.ts is sending the signup request to the backend. This will return an observable response. So we can subscribe to this request and except the backend response on the frontend side. So either the error case or success case is handle inside the returned observable. Example: Explain it with a very simple example let’s say we are trying to create a new user in the database and send a post request for this from the signup page. users.js router.post('/signup',UserController.(req,res)=>{ bcrypt.hash(req.body.password,10) .then((hash)=>{ var user = new User({ email: req.body.email, password: hash }) User.save((err,d)=>{ if(err){ res.status(401).json({ message: 'Failed to create new user' }) } else{ res.status(200).json({ message: 'User created' }) } }) })}) In the above code, we will send a post request on /signup route than using the bcrypt library to encoding the password then create a user object that holds the data that we want to save in the database. Then User.save() method saves the data to the database then either of two scenarios occurs so either data saved successfully in a database or any error occurred. So, if data saved successfully then we can send the success response to the user. Syntax: res.status(200).json({ message: 'User created' }) But if data is not saved to the database then we get an error object in the callback. If we get an error, or we know the scenario in which error occurs then we simply send. res.status(401).json({ message: 'Failed to create new user'}) It was either send an error message through res.status(200).send({ message: ‘user created’ }); with a 200 HTTP status, or send a 401 or 403 HTTP status with no further info on what actually went wrong with a res.status(401). Handling Error on frontend side So by this way, we can send it as a response to the frontend now on the frontend side in angular we can handle this simply in the service file, so we have created an auth.service.ts file from where we send a request to the backend. auth.service.ts addUser(user) { this.http.post(BACKEND_URL + '/signup', user) .subscribe((res) => { this.router.navigate(['/auth/login']); }, (err) => { this.error = err.message; console.log(err.message); // In this block you get your error message // as "Failed to create new user" });} Here we have created an addUser() method that sends HTTP request to the backend (Express framework) providing user details so this.http.post() method returns an Observable, so we can subscribe this and this provides us three callback methods first is success case, second is error case and the third is done (when all operations performed or end). In the success case, we are navigating the user to the login page. auth.service.ts }, (err) => { console.log(err.error.message); this.error = err.message; // In this block you get your error message // as "Failed to create new user"}); So in the second callback method, we can access the error message that we are sending from the backend. So we can send any data from backend to frontend. Output: AngularJS-Function AngularJS-Questions Express.js Picked AngularJS Node.js 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": "\n19 Jul, 2021" }, { "code": null, "e": 318, "s": 28, "text": "There are mainly two parts of a web application, one is front-end and another is the backend. We will start with the backend first. The express catches all errors that occur while running route handlers and middleware. We have to just send them properly to the frontend for user knowledge." }, { "code": null, "e": 501, "s": 318, "text": "Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler, so you don’t need to write your own to get started." }, { "code": null, "e": 512, "s": 501, "text": "Approach: " }, { "code": null, "e": 547, "s": 512, "text": "Create the Angular app to be used." }, { "code": null, "e": 582, "s": 547, "text": "Create the backend routes as well." }, { "code": null, "e": 758, "s": 582, "text": "We send the error during user signup fail. So we have created the “/signup” route in the express app. Now on signup failure send the error using res.status(401).json() method." }, { "code": null, "e": 981, "s": 758, "text": "Now on the frontend side, the auth.service.ts is sending the signup request to the backend. This will return an observable response. So we can subscribe to this request and except the backend response on the frontend side." }, { "code": null, "e": 1064, "s": 981, "text": "So either the error case or success case is handle inside the returned observable." }, { "code": null, "e": 1228, "s": 1064, "text": "Example: Explain it with a very simple example let’s say we are trying to create a new user in the database and send a post request for this from the signup page. " }, { "code": null, "e": 1237, "s": 1228, "text": "users.js" }, { "code": "router.post('/signup',UserController.(req,res)=>{ bcrypt.hash(req.body.password,10) .then((hash)=>{ var user = new User({ email: req.body.email, password: hash }) User.save((err,d)=>{ if(err){ res.status(401).json({ message: 'Failed to create new user' }) } else{ res.status(200).json({ message: 'User created' }) } }) })})", "e": 1751, "s": 1237, "text": null }, { "code": null, "e": 2117, "s": 1751, "text": "In the above code, we will send a post request on /signup route than using the bcrypt library to encoding the password then create a user object that holds the data that we want to save in the database. Then User.save() method saves the data to the database then either of two scenarios occurs so either data saved successfully in a database or any error occurred. " }, { "code": null, "e": 2199, "s": 2117, "text": "So, if data saved successfully then we can send the success response to the user." }, { "code": null, "e": 2207, "s": 2199, "text": "Syntax:" }, { "code": null, "e": 2261, "s": 2207, "text": "res.status(200).json({\n message: 'User created'\n})" }, { "code": null, "e": 2434, "s": 2261, "text": "But if data is not saved to the database then we get an error object in the callback. If we get an error, or we know the scenario in which error occurs then we simply send." }, { "code": "res.status(401).json({ message: 'Failed to create new user'})", "e": 2498, "s": 2434, "text": null }, { "code": null, "e": 2723, "s": 2498, "text": "It was either send an error message through res.status(200).send({ message: ‘user created’ }); with a 200 HTTP status, or send a 401 or 403 HTTP status with no further info on what actually went wrong with a res.status(401)." }, { "code": null, "e": 2755, "s": 2723, "text": "Handling Error on frontend side" }, { "code": null, "e": 2987, "s": 2755, "text": "So by this way, we can send it as a response to the frontend now on the frontend side in angular we can handle this simply in the service file, so we have created an auth.service.ts file from where we send a request to the backend." }, { "code": null, "e": 3003, "s": 2987, "text": "auth.service.ts" }, { "code": "addUser(user) { this.http.post(BACKEND_URL + '/signup', user) .subscribe((res) => { this.router.navigate(['/auth/login']); }, (err) => { this.error = err.message; console.log(err.message); // In this block you get your error message // as \"Failed to create new user\" });}", "e": 3354, "s": 3003, "text": null }, { "code": null, "e": 3769, "s": 3354, "text": "Here we have created an addUser() method that sends HTTP request to the backend (Express framework) providing user details so this.http.post() method returns an Observable, so we can subscribe this and this provides us three callback methods first is success case, second is error case and the third is done (when all operations performed or end). In the success case, we are navigating the user to the login page." }, { "code": null, "e": 3785, "s": 3769, "text": "auth.service.ts" }, { "code": "}, (err) => { console.log(err.error.message); this.error = err.message; // In this block you get your error message // as \"Failed to create new user\"});", "e": 3950, "s": 3785, "text": null }, { "code": null, "e": 4104, "s": 3950, "text": "So in the second callback method, we can access the error message that we are sending from the backend. So we can send any data from backend to frontend." }, { "code": null, "e": 4112, "s": 4104, "text": "Output:" }, { "code": null, "e": 4131, "s": 4112, "text": "AngularJS-Function" }, { "code": null, "e": 4151, "s": 4131, "text": "AngularJS-Questions" }, { "code": null, "e": 4162, "s": 4151, "text": "Express.js" }, { "code": null, "e": 4169, "s": 4162, "text": "Picked" }, { "code": null, "e": 4179, "s": 4169, "text": "AngularJS" }, { "code": null, "e": 4187, "s": 4179, "text": "Node.js" }, { "code": null, "e": 4204, "s": 4187, "text": "Web Technologies" } ]
Find ceil of a/b without using ceil() function
14 Jun, 2022 Given a and b, find the ceiling value of a/b without using ceiling function. Examples: Input : a = 5, b = 4 Output : 2 Explanation: a/b = ceil(5/4) = 2 Input : a = 10, b = 2 Output : 5 Explanation: a/b = ceil(10/2) = 5 The problem can be solved using ceiling function, but the ceiling function does not work when integers are passed as parameters. Hence there are following 2 approaches below to find the ceiling value. Approach 1: ceilVal = (a / b) + ((a % b) != 0) a/b returns the integer division value, and ((a % b) != 0) is a checking condition which returns 1 if we have any remainder left after the division of a/b, else it returns 0. The integer division value is added with the checking value to get the ceiling value. Given below is the illustration of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find ceil(a/b)// without using ceil() function#include <cmath>#include <iostream>using namespace std; // Driver functionint main(){ // taking input 1 int a = 4; int b = 3; int val = (a / b) + ((a % b) != 0); cout << "The ceiling value of 4/3 is " << val << endl; // example of perfect division // taking input 2 a = 6; b = 3; val = (a / b) + ((a % b) != 0); cout << "The ceiling value of 6/3 is " << val << endl; return 0;} // Java program to find// ceil(a/b) without// using ceil() functionimport java.io.*; class GFG{ // Driver Code public static void main(String args[]) { // taking input 1 int a = 4; int b = 3, val = 0; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); System.out.println("The ceiling " + "value of 4/3 is " + val); // example of perfect // division taking input 2 a = 6; b = 3; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); System.out.println("The ceiling " + "value of 6/3 is " + val); }} // This code is contributed by// Manish Shaw(manishshaw1) # Python3 program to find ceil(a/b)# without using ceil() functionimport math # Driver Code # taking input 1a = 4;b = 3;val = (a / b) + ((a % b) != 0);print("The ceiling value of 4/3 is", math.floor(val)); # example of perfect division# taking input 2a = 6;b = 3;val = int((a / b) + ((a % b) != 0));print("The ceiling value of 6/3 is", val); # This code is contributed by mits // C# program to find ceil(a/b)// without using ceil() functionusing System; class GFG{ // Driver Code static void Main() { // taking input 1 int a = 4; int b = 3, val = 0; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); Console.WriteLine("The ceiling " + "value of 4/3 is " + val); // example of perfect // division taking input 2 a = 6; b = 3; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); Console.WriteLine("The ceiling " + "value of 6/3 is " + val); }}// This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP program to find ceil(a/b)// without using ceil() function // Driver function // taking input 1 $a = 4; $b = 3; $val = ($a / $b) + (($a % $b) != 0); echo "The ceiling value of 4/3 is " , floor($val) ,"\n"; // example of perfect division // taking input 2 $a = 6; $b = 3; $val = ($a / $b) + (($a % $b) != 0); echo "The ceiling value of 6/3 is " , $val ; // This code is contributed by anuj_67. ?> <script>// javascript program to find// ceil(a/b) without// using ceil() function // Driver Code // taking input 1 var a = 4; var b = 3, val = 0; if ((a % b) != 0) val = parseInt(a / b) + (a % b); else val = parseInt(a / b); document.write("The ceiling " + "value of 4/3 is " + val+"<br/>"); // example of perfect // division taking input 2 a = 6; b = 3; if ((a % b) != 0) val = parseInt(a / b) + (a % b); else val = parseInt(a / b); document.write("The ceiling " + "value of 6/3 is " + val); // This code is contributed by gauravrajput1</script> The ceiling value of 4/3 is 2 The ceiling value of 6/3 is 2 Approach 2: ceilVal = (a+b-1) / b Using simple maths, we can add the denominator to the numerator and subtract 1 from it and then divide it by denominator to get the ceiling value.Given below is the illustration of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find ceil(a/b)// without using ceil() function#include <cmath>#include <iostream>using namespace std; // Driver functionint main(){ // taking input 1 int a = 4; int b = 3; int val = (a + b - 1) / b; cout << "The ceiling value of 4/3 is " << val << endl; // example of perfect division // taking input 2 a = 6; b = 3; val = (a + b - 1) / b; cout << "The ceiling value of 6/3 is " << val << endl; return 0;} // Java program to find ceil(a/b)// without using ceil() function class GFG { // Driver Codepublic static void main(String args[]){ // taking input 1 int a = 4; int b = 3; int val = (a + b - 1) / b; System.out.println("The ceiling value of 4/3 is " + val); // example of perfect division // taking input 2 a = 6; b = 3; val = (a + b - 1) / b; System.out.println("The ceiling value of 6/3 is " + val );}} // This code is contributed by Jaideep Pyne # Python3 program to find# math.ceil(a/b) without# using math.ceil() functionimport math # Driver Code# taking input 1a = 4;b = 3;val = (a + b - 1) / b;print("The ceiling value of 4/3 is ", math.floor(val)); # example of perfect division# taking input 2a = 6;b = 3;val = (a + b - 1) / b;print("The ceiling value of 6/3 is ", math.floor(val)); # This code is contributed by mits // C# program to find ceil(a/b)// without using ceil() functionusing System; class GFG { // Driver Code public static void Main() { // taking input 1 int a = 4; int b = 3; int val = (a + b - 1) / b; Console.WriteLine("The ceiling" + " value of 4/3 is " + val); // example of perfect division // taking input 2 a = 6; b = 3; val = (a + b - 1) / b; Console.WriteLine("The ceiling" + " value of 6/3 is " + val ); }} // This code is contributed by anuj_67. <?php// PHP program to find ceil(a/b)// without using ceil() function // Driver function // taking input 1 $a = 4; $b = 3; $val = ($a + $b - 1) /$b; echo "The ceiling value of 4/3 is " , floor($val) ,"\n"; // example of perfect division // taking input 2 $a = 6; $b = 3; $val = ($a + $b - 1) / $b; echo "The ceiling value of 6/3 is " ,floor($val) ; // This code is contributed by anuj_67.?> <script>// javascript program to find ceil(a/b)// without using ceil() function // Driver Code // taking input 1 var a = 4; var b = 3; var val = (a + b - 1) / b; document.write("The ceiling value of 4/3 is " + val+"<br/>"); // example of perfect division // taking input 2 a = 6; b = 3; val = parseInt((a + b - 1) / b); document.write("The ceiling value of 6/3 is " + val); // This code contributed by Rajput-Ji</script> The ceiling value of 4/3 is 2 The ceiling value of 6/3 is 2 Time Complexity: O(1)Auxiliary Space: O(1) jaideeppyne1997 vt_m manishshaw1 Mithun Kumar GauravRajput1 Rajput-Ji singhh3010 number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 141, "s": 52, "text": "Given a and b, find the ceiling value of a/b without using ceiling function. Examples: " }, { "code": null, "e": 279, "s": 141, "text": "Input : a = 5, b = 4 \nOutput : 2 \nExplanation: a/b = ceil(5/4) = 2 \n\nInput : a = 10, b = 2\nOutput : 5 \nExplanation: a/b = ceil(10/2) = 5 " }, { "code": null, "e": 496, "s": 281, "text": "The problem can be solved using ceiling function, but the ceiling function does not work when integers are passed as parameters. Hence there are following 2 approaches below to find the ceiling value. Approach 1: " }, { "code": null, "e": 532, "s": 496, "text": "ceilVal = (a / b) + ((a % b) != 0) " }, { "code": null, "e": 850, "s": 532, "text": "a/b returns the integer division value, and ((a % b) != 0) is a checking condition which returns 1 if we have any remainder left after the division of a/b, else it returns 0. The integer division value is added with the checking value to get the ceiling value. Given below is the illustration of the above approach: " }, { "code": null, "e": 854, "s": 850, "text": "C++" }, { "code": null, "e": 859, "s": 854, "text": "Java" }, { "code": null, "e": 867, "s": 859, "text": "Python3" }, { "code": null, "e": 870, "s": 867, "text": "C#" }, { "code": null, "e": 874, "s": 870, "text": "PHP" }, { "code": null, "e": 885, "s": 874, "text": "Javascript" }, { "code": "// C++ program to find ceil(a/b)// without using ceil() function#include <cmath>#include <iostream>using namespace std; // Driver functionint main(){ // taking input 1 int a = 4; int b = 3; int val = (a / b) + ((a % b) != 0); cout << \"The ceiling value of 4/3 is \" << val << endl; // example of perfect division // taking input 2 a = 6; b = 3; val = (a / b) + ((a % b) != 0); cout << \"The ceiling value of 6/3 is \" << val << endl; return 0;}", "e": 1381, "s": 885, "text": null }, { "code": "// Java program to find// ceil(a/b) without// using ceil() functionimport java.io.*; class GFG{ // Driver Code public static void main(String args[]) { // taking input 1 int a = 4; int b = 3, val = 0; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); System.out.println(\"The ceiling \" + \"value of 4/3 is \" + val); // example of perfect // division taking input 2 a = 6; b = 3; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); System.out.println(\"The ceiling \" + \"value of 6/3 is \" + val); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 2238, "s": 1381, "text": null }, { "code": "# Python3 program to find ceil(a/b)# without using ceil() functionimport math # Driver Code # taking input 1a = 4;b = 3;val = (a / b) + ((a % b) != 0);print(\"The ceiling value of 4/3 is\", math.floor(val)); # example of perfect division# taking input 2a = 6;b = 3;val = int((a / b) + ((a % b) != 0));print(\"The ceiling value of 6/3 is\", val); # This code is contributed by mits", "e": 2633, "s": 2238, "text": null }, { "code": "// C# program to find ceil(a/b)// without using ceil() functionusing System; class GFG{ // Driver Code static void Main() { // taking input 1 int a = 4; int b = 3, val = 0; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); Console.WriteLine(\"The ceiling \" + \"value of 4/3 is \" + val); // example of perfect // division taking input 2 a = 6; b = 3; if((a % b) != 0) val = (a / b) + (a % b); else val = (a / b); Console.WriteLine(\"The ceiling \" + \"value of 6/3 is \" + val); }}// This code is contributed by// Manish Shaw(manishshaw1)", "e": 3444, "s": 2633, "text": null }, { "code": "<?php// PHP program to find ceil(a/b)// without using ceil() function // Driver function // taking input 1 $a = 4; $b = 3; $val = ($a / $b) + (($a % $b) != 0); echo \"The ceiling value of 4/3 is \" , floor($val) ,\"\\n\"; // example of perfect division // taking input 2 $a = 6; $b = 3; $val = ($a / $b) + (($a % $b) != 0); echo \"The ceiling value of 6/3 is \" , $val ; // This code is contributed by anuj_67. ?>", "e": 3923, "s": 3444, "text": null }, { "code": "<script>// javascript program to find// ceil(a/b) without// using ceil() function // Driver Code // taking input 1 var a = 4; var b = 3, val = 0; if ((a % b) != 0) val = parseInt(a / b) + (a % b); else val = parseInt(a / b); document.write(\"The ceiling \" + \"value of 4/3 is \" + val+\"<br/>\"); // example of perfect // division taking input 2 a = 6; b = 3; if ((a % b) != 0) val = parseInt(a / b) + (a % b); else val = parseInt(a / b); document.write(\"The ceiling \" + \"value of 6/3 is \" + val); // This code is contributed by gauravrajput1</script>", "e": 4622, "s": 3923, "text": null }, { "code": null, "e": 4682, "s": 4622, "text": "The ceiling value of 4/3 is 2\nThe ceiling value of 6/3 is 2" }, { "code": null, "e": 4698, "s": 4684, "text": "Approach 2: " }, { "code": null, "e": 4721, "s": 4698, "text": "ceilVal = (a+b-1) / b " }, { "code": null, "e": 4924, "s": 4721, "text": "Using simple maths, we can add the denominator to the numerator and subtract 1 from it and then divide it by denominator to get the ceiling value.Given below is the illustration of the above approach: " }, { "code": null, "e": 4928, "s": 4924, "text": "C++" }, { "code": null, "e": 4933, "s": 4928, "text": "Java" }, { "code": null, "e": 4941, "s": 4933, "text": "Python3" }, { "code": null, "e": 4944, "s": 4941, "text": "C#" }, { "code": null, "e": 4948, "s": 4944, "text": "PHP" }, { "code": null, "e": 4959, "s": 4948, "text": "Javascript" }, { "code": "// C++ program to find ceil(a/b)// without using ceil() function#include <cmath>#include <iostream>using namespace std; // Driver functionint main(){ // taking input 1 int a = 4; int b = 3; int val = (a + b - 1) / b; cout << \"The ceiling value of 4/3 is \" << val << endl; // example of perfect division // taking input 2 a = 6; b = 3; val = (a + b - 1) / b; cout << \"The ceiling value of 6/3 is \" << val << endl; return 0;}", "e": 5437, "s": 4959, "text": null }, { "code": "// Java program to find ceil(a/b)// without using ceil() function class GFG { // Driver Codepublic static void main(String args[]){ // taking input 1 int a = 4; int b = 3; int val = (a + b - 1) / b; System.out.println(\"The ceiling value of 4/3 is \" + val); // example of perfect division // taking input 2 a = 6; b = 3; val = (a + b - 1) / b; System.out.println(\"The ceiling value of 6/3 is \" + val );}} // This code is contributed by Jaideep Pyne", "e": 5974, "s": 5437, "text": null }, { "code": "# Python3 program to find# math.ceil(a/b) without# using math.ceil() functionimport math # Driver Code# taking input 1a = 4;b = 3;val = (a + b - 1) / b;print(\"The ceiling value of 4/3 is \", math.floor(val)); # example of perfect division# taking input 2a = 6;b = 3;val = (a + b - 1) / b;print(\"The ceiling value of 6/3 is \", math.floor(val)); # This code is contributed by mits", "e": 6390, "s": 5974, "text": null }, { "code": "// C# program to find ceil(a/b)// without using ceil() functionusing System; class GFG { // Driver Code public static void Main() { // taking input 1 int a = 4; int b = 3; int val = (a + b - 1) / b; Console.WriteLine(\"The ceiling\" + \" value of 4/3 is \" + val); // example of perfect division // taking input 2 a = 6; b = 3; val = (a + b - 1) / b; Console.WriteLine(\"The ceiling\" + \" value of 6/3 is \" + val ); }} // This code is contributed by anuj_67.", "e": 6968, "s": 6390, "text": null }, { "code": "<?php// PHP program to find ceil(a/b)// without using ceil() function // Driver function // taking input 1 $a = 4; $b = 3; $val = ($a + $b - 1) /$b; echo \"The ceiling value of 4/3 is \" , floor($val) ,\"\\n\"; // example of perfect division // taking input 2 $a = 6; $b = 3; $val = ($a + $b - 1) / $b; echo \"The ceiling value of 6/3 is \" ,floor($val) ; // This code is contributed by anuj_67.?>", "e": 7411, "s": 6968, "text": null }, { "code": "<script>// javascript program to find ceil(a/b)// without using ceil() function // Driver Code // taking input 1 var a = 4; var b = 3; var val = (a + b - 1) / b; document.write(\"The ceiling value of 4/3 is \" + val+\"<br/>\"); // example of perfect division // taking input 2 a = 6; b = 3; val = parseInt((a + b - 1) / b); document.write(\"The ceiling value of 6/3 is \" + val); // This code contributed by Rajput-Ji</script>", "e": 7919, "s": 7411, "text": null }, { "code": null, "e": 7979, "s": 7919, "text": "The ceiling value of 4/3 is 2\nThe ceiling value of 6/3 is 2" }, { "code": null, "e": 8024, "s": 7981, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 8040, "s": 8024, "text": "jaideeppyne1997" }, { "code": null, "e": 8045, "s": 8040, "text": "vt_m" }, { "code": null, "e": 8057, "s": 8045, "text": "manishshaw1" }, { "code": null, "e": 8070, "s": 8057, "text": "Mithun Kumar" }, { "code": null, "e": 8084, "s": 8070, "text": "GauravRajput1" }, { "code": null, "e": 8094, "s": 8084, "text": "Rajput-Ji" }, { "code": null, "e": 8105, "s": 8094, "text": "singhh3010" }, { "code": null, "e": 8119, "s": 8105, "text": "number-theory" }, { "code": null, "e": 8132, "s": 8119, "text": "Mathematical" }, { "code": null, "e": 8146, "s": 8132, "text": "number-theory" }, { "code": null, "e": 8159, "s": 8146, "text": "Mathematical" } ]
Kotlin Visibility Modifiers
28 Apr, 2022 In Kotlin, visibility modifiers are used to restrict the accessibility of classes, objects, interfaces, constructors, functions, properties, and their setters to a certain level. No need to set the visibility of getters because they have the same visibility as the property.There are four visibility modifiers in Kotlin. If there is no specified modifier then by default it is public. Let’s start discussing the above modifiers one by one. In Kotlin, the default modifier is public. It is possibly the most frequently used modifier in the entire language and there are additional restrictions on who can see the element being modified. Unlike Java, in Kotlin there is no need to declare anything as public – it is the default modifier, if we don’t declare another modifier – public works the same in Kotlin, as in Java. When we apply the public modifier to top-level elements – classes, functions or variables declared directly inside a package, then any other code can access it. If we apply the public modifier to a nested element – an inner class, or function inside a class – then any code that can access the container can also access this element. Kotlin // by default publicclass A { var int = 10} // specified with public modifierpublic class B { var int2 = 20 fun display() { println("Accessible everywhere") }} Here, Class A and B are accessible from anywhere in the entire code, the variables int, int2, and the function display() are accessible from anything that can access classes A and B. In Kotlin, private modifiers allow only the code declared inside the same scope, access. It does not allow access to the modifier variable or function outside the scope. Unlike Java, Kotlin allows multiple top-level declarations in the same file – a private top-level element can be accessed by everything else in the same file. Kotlin // class A is accessible from same source fileprivate class A { private val int = 10 fun display() { // we can access int in the same class println(int) println("Accessing int successful") }}fun main(args: Array<String>){ var a = A() a.display() // can not access 'int': it is private in class A println(a.int) } Output: Cannot access 'int': it is private in 'A' Here, Class A is only accessible from within the same source file, and the int variable is only accessible from the inside of class A. When we tried to access int from outside the class, it gives a compile-time error. In Kotlin, the internal modifier is a newly added modifier that is not supported by Java. Marked as internal means that it will be available in the same module, if we try to access the declaration from another module it will give an error. A module means a group of files that are compiled together. Note: Internal modifier benefits in writing APIs and implementations. Kotlin internal class A {}public class B { internal val int = 10 internal fun display() { }} Here, Class A is only accessible from inside the same module. The variable int and function display() are only accessible from inside the same module, even though class B can be accessed from anywhere. In Kotlin, the protected modifier strictly allows accessibility to the declaring class and its subclasses. The protected modifier can not be declared at the top level. In the below program, we have accessed the int variable in the getvalue() function of the derived class. Kotlin // base classopen class A { // protected variable protected val int = 10} // derived classclass B: A() { fun getvalue(): Int { // accessed from the subclass return int }} fun main(args: Array<String>) { var a = B() println("The value of integer is: "+a.getvalue())} Output: The value of integer is: 10 We need to mark the protected variable or function using an open keywords to override in the derived class. In the below program, we have overridden the int variable. Kotlin // base classopen class A { // protected variable open protected val int = 10 } // derived classclass B: A() { override val int = 20 fun getvalue():Int { // accessed from the subclass return int }} fun main(args: Array<String>) { var a = B() println("The overridden value of integer is: "+a.getvalue())} Output: The value of integer is: 20 By default constructors are public, but we can also change the visibility of a constructor by using the modifiers. class A (name : String) { // other code } We must explicitly specify this by using the constructor keyword whilst changing the visibility. class A private constructor (name : String) { // other code } marktahu7 wish75584 Kotlin OOPs Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2022" }, { "code": null, "e": 350, "s": 28, "text": "In Kotlin, visibility modifiers are used to restrict the accessibility of classes, objects, interfaces, constructors, functions, properties, and their setters to a certain level. No need to set the visibility of getters because they have the same visibility as the property.There are four visibility modifiers in Kotlin. " }, { "code": null, "e": 469, "s": 350, "text": "If there is no specified modifier then by default it is public. Let’s start discussing the above modifiers one by one." }, { "code": null, "e": 1183, "s": 469, "text": "In Kotlin, the default modifier is public. It is possibly the most frequently used modifier in the entire language and there are additional restrictions on who can see the element being modified. Unlike Java, in Kotlin there is no need to declare anything as public – it is the default modifier, if we don’t declare another modifier – public works the same in Kotlin, as in Java. When we apply the public modifier to top-level elements – classes, functions or variables declared directly inside a package, then any other code can access it. If we apply the public modifier to a nested element – an inner class, or function inside a class – then any code that can access the container can also access this element." }, { "code": null, "e": 1190, "s": 1183, "text": "Kotlin" }, { "code": "// by default publicclass A { var int = 10} // specified with public modifierpublic class B { var int2 = 20 fun display() { println(\"Accessible everywhere\") }}", "e": 1390, "s": 1190, "text": null }, { "code": null, "e": 1573, "s": 1390, "text": "Here, Class A and B are accessible from anywhere in the entire code, the variables int, int2, and the function display() are accessible from anything that can access classes A and B." }, { "code": null, "e": 1902, "s": 1573, "text": "In Kotlin, private modifiers allow only the code declared inside the same scope, access. It does not allow access to the modifier variable or function outside the scope. Unlike Java, Kotlin allows multiple top-level declarations in the same file – a private top-level element can be accessed by everything else in the same file." }, { "code": null, "e": 1909, "s": 1902, "text": "Kotlin" }, { "code": "// class A is accessible from same source fileprivate class A { private val int = 10 fun display() { // we can access int in the same class println(int) println(\"Accessing int successful\") }}fun main(args: Array<String>){ var a = A() a.display() // can not access 'int': it is private in class A println(a.int) }", "e": 2269, "s": 1909, "text": null }, { "code": null, "e": 2278, "s": 2269, "text": "Output: " }, { "code": null, "e": 2320, "s": 2278, "text": "Cannot access 'int': it is private in 'A'" }, { "code": null, "e": 2539, "s": 2320, "text": "Here, Class A is only accessible from within the same source file, and the int variable is only accessible from the inside of class A. When we tried to access int from outside the class, it gives a compile-time error. " }, { "code": null, "e": 2839, "s": 2539, "text": "In Kotlin, the internal modifier is a newly added modifier that is not supported by Java. Marked as internal means that it will be available in the same module, if we try to access the declaration from another module it will give an error. A module means a group of files that are compiled together." }, { "code": null, "e": 2910, "s": 2839, "text": "Note: Internal modifier benefits in writing APIs and implementations. " }, { "code": null, "e": 2917, "s": 2910, "text": "Kotlin" }, { "code": "internal class A {}public class B { internal val int = 10 internal fun display() { }}", "e": 3012, "s": 2917, "text": null }, { "code": null, "e": 3215, "s": 3012, "text": "Here, Class A is only accessible from inside the same module. The variable int and function display() are only accessible from inside the same module, even though class B can be accessed from anywhere. " }, { "code": null, "e": 3489, "s": 3215, "text": "In Kotlin, the protected modifier strictly allows accessibility to the declaring class and its subclasses. The protected modifier can not be declared at the top level. In the below program, we have accessed the int variable in the getvalue() function of the derived class. " }, { "code": null, "e": 3496, "s": 3489, "text": "Kotlin" }, { "code": "// base classopen class A { // protected variable protected val int = 10} // derived classclass B: A() { fun getvalue(): Int { // accessed from the subclass return int }} fun main(args: Array<String>) { var a = B() println(\"The value of integer is: \"+a.getvalue())}", "e": 3806, "s": 3496, "text": null }, { "code": null, "e": 3815, "s": 3806, "text": "Output: " }, { "code": null, "e": 3843, "s": 3815, "text": "The value of integer is: 10" }, { "code": null, "e": 4011, "s": 3843, "text": "We need to mark the protected variable or function using an open keywords to override in the derived class. In the below program, we have overridden the int variable. " }, { "code": null, "e": 4018, "s": 4011, "text": "Kotlin" }, { "code": "// base classopen class A { // protected variable open protected val int = 10 } // derived classclass B: A() { override val int = 20 fun getvalue():Int { // accessed from the subclass return int }} fun main(args: Array<String>) { var a = B() println(\"The overridden value of integer is: \"+a.getvalue())}", "e": 4367, "s": 4018, "text": null }, { "code": null, "e": 4376, "s": 4367, "text": "Output: " }, { "code": null, "e": 4404, "s": 4376, "text": "The value of integer is: 20" }, { "code": null, "e": 4521, "s": 4404, "text": "By default constructors are public, but we can also change the visibility of a constructor by using the modifiers. " }, { "code": null, "e": 4569, "s": 4521, "text": "class A (name : String) {\n // other code\n}" }, { "code": null, "e": 4668, "s": 4569, "text": "We must explicitly specify this by using the constructor keyword whilst changing the visibility. " }, { "code": null, "e": 4736, "s": 4668, "text": "class A private constructor (name : String) {\n // other code\n}" }, { "code": null, "e": 4746, "s": 4736, "text": "marktahu7" }, { "code": null, "e": 4756, "s": 4746, "text": "wish75584" }, { "code": null, "e": 4768, "s": 4756, "text": "Kotlin OOPs" }, { "code": null, "e": 4775, "s": 4768, "text": "Kotlin" } ]
Types of inheritance Python
07 Jul, 2022 Inheritance is defined as the mechanism of inheriting the properties of the base class to the child class. Here we a going to see the types of inheritance in Python. Types of Inheritance depend upon the number of child and parent classes involved. There are four types of inheritance in Python: Single inheritance enables a derived class to inherit properties from a single parent class, thus enabling code reusability and the addition of new features to existing code. Example: Python3 # Python program to demonstrate# single inheritance # Base classclass Parent: def func1(self): print("This function is in parent class.") # Derived class class Child(Parent): def func2(self): print("This function is in child class.") # Driver's codeobject = Child()object.func1()object.func2() Output: This function is in parent class. This function is in child class. When a class can be derived from more than one base class this type of inheritance is called multiple inheritances. In multiple inheritances, all the features of the base classes are inherited into the derived class. Example: Python3 # Python program to demonstrate# multiple inheritance # Base class1class Mother: mothername = "" def mother(self): print(self.mothername) # Base class2 class Father: fathername = "" def father(self): print(self.fathername) # Derived class class Son(Mother, Father): def parents(self): print("Father :", self.fathername) print("Mother :", self.mothername) # Driver's codes1 = Son()s1.fathername = "RAM"s1.mothername = "SITA"s1.parents() Output: Father : RAM Mother : SITA In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and a grandfather. Example: Python3 # Python program to demonstrate# multilevel inheritance # Base class class Grandfather: def __init__(self, grandfathername): self.grandfathername = grandfathername # Intermediate class class Father(Grandfather): def __init__(self, fathername, grandfathername): self.fathername = fathername # invoking constructor of Grandfather class Grandfather.__init__(self, grandfathername) # Derived class class Son(Father): def __init__(self, sonname, fathername, grandfathername): self.sonname = sonname # invoking constructor of Father class Father.__init__(self, fathername, grandfathername) def print_name(self): print('Grandfather name :', self.grandfathername) print("Father name :", self.fathername) print("Son name :", self.sonname) # Driver codes1 = Son('Prince', 'Rampal', 'Lal mani')print(s1.grandfathername)s1.print_name() Output: Lal mani Grandfather name : Lal mani Father name : Rampal Son name : Prince When more than one derived class are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes. Example: Python3 # Python program to demonstrate# Hierarchical inheritance # Base classclass Parent: def func1(self): print("This function is in parent class.") # Derived class1 class Child1(Parent): def func2(self): print("This function is in child 1.") # Derivied class2 class Child2(Parent): def func3(self): print("This function is in child 2.") # Driver's codeobject1 = Child1()object2 = Child2()object1.func1()object1.func2()object2.func1()object2.func3() Output: This function is in parent class. This function is in child 1. This function is in parent class. This function is in child 2. Inheritance consisting of multiple types of inheritance is called hybrid inheritance. Example: Python3 # Python program to demonstrate# hybrid inheritance class School: def func1(self): print("This function is in school.") class Student1(School): def func2(self): print("This function is in student 1. ") class Student2(School): def func3(self): print("This function is in student 2.") class Student3(Student1, School): def func4(self): print("This function is in student 3.") # Driver's codeobject = Student3()object.func1()object.func2() Output: This function is in school. This function is in student 1. princelalla24 kumar_satyam python-inheritance Python-OOP python-oop-concepts Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 218, "s": 52, "text": "Inheritance is defined as the mechanism of inheriting the properties of the base class to the child class. Here we a going to see the types of inheritance in Python." }, { "code": null, "e": 349, "s": 220, "text": "Types of Inheritance depend upon the number of child and parent classes involved. There are four types of inheritance in Python:" }, { "code": null, "e": 524, "s": 349, "text": "Single inheritance enables a derived class to inherit properties from a single parent class, thus enabling code reusability and the addition of new features to existing code." }, { "code": null, "e": 535, "s": 526, "text": "Example:" }, { "code": null, "e": 543, "s": 535, "text": "Python3" }, { "code": "# Python program to demonstrate# single inheritance # Base classclass Parent: def func1(self): print(\"This function is in parent class.\") # Derived class class Child(Parent): def func2(self): print(\"This function is in child class.\") # Driver's codeobject = Child()object.func1()object.func2()", "e": 859, "s": 543, "text": null }, { "code": null, "e": 867, "s": 859, "text": "Output:" }, { "code": null, "e": 934, "s": 867, "text": "This function is in parent class.\nThis function is in child class." }, { "code": null, "e": 1152, "s": 934, "text": "When a class can be derived from more than one base class this type of inheritance is called multiple inheritances. In multiple inheritances, all the features of the base classes are inherited into the derived class. " }, { "code": null, "e": 1163, "s": 1154, "text": "Example:" }, { "code": null, "e": 1171, "s": 1163, "text": "Python3" }, { "code": "# Python program to demonstrate# multiple inheritance # Base class1class Mother: mothername = \"\" def mother(self): print(self.mothername) # Base class2 class Father: fathername = \"\" def father(self): print(self.fathername) # Derived class class Son(Mother, Father): def parents(self): print(\"Father :\", self.fathername) print(\"Mother :\", self.mothername) # Driver's codes1 = Son()s1.fathername = \"RAM\"s1.mothername = \"SITA\"s1.parents()", "e": 1655, "s": 1171, "text": null }, { "code": null, "e": 1663, "s": 1655, "text": "Output:" }, { "code": null, "e": 1690, "s": 1663, "text": "Father : RAM\nMother : SITA" }, { "code": null, "e": 1891, "s": 1690, "text": "In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and a grandfather. " }, { "code": null, "e": 1902, "s": 1893, "text": "Example:" }, { "code": null, "e": 1910, "s": 1902, "text": "Python3" }, { "code": "# Python program to demonstrate# multilevel inheritance # Base class class Grandfather: def __init__(self, grandfathername): self.grandfathername = grandfathername # Intermediate class class Father(Grandfather): def __init__(self, fathername, grandfathername): self.fathername = fathername # invoking constructor of Grandfather class Grandfather.__init__(self, grandfathername) # Derived class class Son(Father): def __init__(self, sonname, fathername, grandfathername): self.sonname = sonname # invoking constructor of Father class Father.__init__(self, fathername, grandfathername) def print_name(self): print('Grandfather name :', self.grandfathername) print(\"Father name :\", self.fathername) print(\"Son name :\", self.sonname) # Driver codes1 = Son('Prince', 'Rampal', 'Lal mani')print(s1.grandfathername)s1.print_name()", "e": 2825, "s": 1910, "text": null }, { "code": null, "e": 2833, "s": 2825, "text": "Output:" }, { "code": null, "e": 2909, "s": 2833, "text": "Lal mani\nGrandfather name : Lal mani\nFather name : Rampal\nSon name : Prince" }, { "code": null, "e": 3114, "s": 2909, "text": "When more than one derived class are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes." }, { "code": null, "e": 3125, "s": 3116, "text": "Example:" }, { "code": null, "e": 3133, "s": 3125, "text": "Python3" }, { "code": "# Python program to demonstrate# Hierarchical inheritance # Base classclass Parent: def func1(self): print(\"This function is in parent class.\") # Derived class1 class Child1(Parent): def func2(self): print(\"This function is in child 1.\") # Derivied class2 class Child2(Parent): def func3(self): print(\"This function is in child 2.\") # Driver's codeobject1 = Child1()object2 = Child2()object1.func1()object1.func2()object2.func1()object2.func3()", "e": 3612, "s": 3133, "text": null }, { "code": null, "e": 3620, "s": 3612, "text": "Output:" }, { "code": null, "e": 3746, "s": 3620, "text": "This function is in parent class.\nThis function is in child 1.\nThis function is in parent class.\nThis function is in child 2." }, { "code": null, "e": 3832, "s": 3746, "text": "Inheritance consisting of multiple types of inheritance is called hybrid inheritance." }, { "code": null, "e": 3843, "s": 3834, "text": "Example:" }, { "code": null, "e": 3851, "s": 3843, "text": "Python3" }, { "code": "# Python program to demonstrate# hybrid inheritance class School: def func1(self): print(\"This function is in school.\") class Student1(School): def func2(self): print(\"This function is in student 1. \") class Student2(School): def func3(self): print(\"This function is in student 2.\") class Student3(Student1, School): def func4(self): print(\"This function is in student 3.\") # Driver's codeobject = Student3()object.func1()object.func2()", "e": 4333, "s": 3851, "text": null }, { "code": null, "e": 4341, "s": 4333, "text": "Output:" }, { "code": null, "e": 4400, "s": 4341, "text": "This function is in school.\nThis function is in student 1." }, { "code": null, "e": 4414, "s": 4400, "text": "princelalla24" }, { "code": null, "e": 4427, "s": 4414, "text": "kumar_satyam" }, { "code": null, "e": 4446, "s": 4427, "text": "python-inheritance" }, { "code": null, "e": 4457, "s": 4446, "text": "Python-OOP" }, { "code": null, "e": 4477, "s": 4457, "text": "python-oop-concepts" }, { "code": null, "e": 4484, "s": 4477, "text": "Python" }, { "code": null, "e": 4503, "s": 4484, "text": "Technical Scripter" } ]
Survival analysis in clinical trials — Log-rank test | by Tereza Burgetova | Towards Data Science
In Part 1 of the series, I explained the reasoning behind the Kaplan-Meier estimator of the survival curve. While it is a ubiquitous tool for visualizing the results of a clinical trial that involves a time-to-event analysis, it is only descriptive. To be able to draw conclusions and show the benefits of a new treatment, we need a formal testing procedure. One such procedure is the log-rank test. I will take a look at how it’s derived and why it’s still considered one of the most important indicators of drug efficacy. We start with a ggplot of a survfit object, using the same data set as in Part 1: library(survival)library(survminer)data(ovarian)fit <- survfit(Surv(ovarian$futime, ovarian$fustat) ~ rx, data = ovarian, conf.type="log")p_fit <- ggsurvplot( fit, conf.int = TRUE, pval = TRUE)p_fit How the survival probability estimates and confidence intervals are obtained is described in Part 1. If pval is set to TRUE, the function also prints the p-value 0.3, which is a result of a log-rank test. So how was it calculated? The log-rank test is basically multiple separate Fisher’s exact tests pooled together. I will show exactly what I mean by that later. But it is essential to first understand how the Fisher’s exact test works. So let’s start with a fictitious example. Suppose there is an Introduction to statistics class for second-year university students. They can attend tutorials during the semester, which some do and some don’t. After the final exam, we want to see if failing the exam is associated with tutorial attendance. And so for every student, we record whether they were present at the tutorials at least 75% of the time in addition to whether they passed or not. And we get the following picture: Now we want to test whether tutorial attendance and passing the exam are independent. The probabilities table looks like this: Meaning, for example, that and the hypothesis we want to test is H0: π11/π1+ = π21/π2+. Now suppose this hypothesis is true. This means that we would expect the proportion of failed students in the group with high tutorial attendance to be similar to the proportion of failed students in the group with low attendance. In other words, with A being the random variable whose value is the number of students who both attended 75%+ of tutorials and passed the exam. What is the distribution of A? Note that n++ as well as the marginals (fail/pass & attendance - yes/no counts) are fixed. Under the null hypothesis, the probability that A=a (probability that the number of students who passed and attended 75%+ of tutorials is equal to a) is the probability that if out of n++=343 students, of which 217 attended 75%+ tutorials, we pick 281 at random, a would have attended 75%+ of tutorials. This is because we assume that those 281 students who passed are no different to the whole sample of 343 of students in terms of how much they went to tutorial classes. The distribution of A is called the hypergeometric distribution, and one can both derive or just copy from Wikipedia its probability mass function and variance: Calculating exact p-values for samples this big is problematic, but we can use the chi-squared approximation of the following statistic instead: Suppose the same experiment was done at 12 different universities. We don’t want to combine these into one table, as there might be differences between the universities. We want to test the following hypothesis: H0: π11 = π12, π21 = π22, ..., πk1 = πk2, where k is the number of sites (in this case 12). This can be done using the Mantel–Haenszel statistic: i is the group index, O is the sum of observed deaths, E the sum of expected deaths, and V is the sum of variances of the deaths in population 1, over all sites. We plug in the sums into MH and note its asymptotic distribution: This is used to test the null hypothesis the usual way. Now we can use this same statistic and apply it on our censored data. How does this relate to the log-rank test? Essentially, we look at each time point when death was observed as the “university” in the above example and create a contingency table for each. Even though the samples (“universities”) are not independent, the asymptotic distribution of Menzel-Haenszel statistic is still chi-squared with one degree of freedom. Effectively, we test the hypothesis H0: F1 = F2, or the equality of survival curves for the combined treatment and standard treatment group. Now let’s check how they obtained the p-value on the graph from the beginning of the article. We basically create a contingency table for each time point t of an event. From this table, we can calculate the number of deaths a and the expectation and variance of A for each ti under the null hypothesis. All that is left is to sum these and plug in into the expression for our test statistic, MH. In this case, MH2 = (7–5.23)2 / 2.94 = 1.066. Note that the event times do not enter the statistic calculations, only their ranks do. In R, the log-rank test can be performed with the function survdiff() from the package survival. logr <- survdiff(Surv(ovarian$futime, ovarian$fustat) ~ rx, data = ovarian)logr## Call:## survdiff(formula = Surv(ovarian$futime, ovarian$fustat) ~ rx,## data = ovarian)## ## N Observed Expected (O-E)^2/E (O-E)^2/V## rx=1 13 7 5.23 0.596 1.06## rx=2 13 5 6.77 0.461 1.06## ## Chisq= 1.1 on 1 degrees of freedom, p= 0.3 Apart from some differences due to rounding, the test gives the same answer as was calculated manually above. In particular (O-E)^2/V is 1.06, which is the MH2 statistic. The probability of a chi-squared distributed variable with 1 degree of freedom being larger than this is 0.3, which can be checked with the following code: 1 - pchisq(1.06, df = 1)## [1] 0.3032152 Hence, we cannot reject the null hypothesis that the combined treatment is no better (or worse) than the standard one. To account for covariates, we can stratify the sample. In this case, there is a variable resid.ds in the data set, indicating whether there was minimal residual disease present (resid.ds=1), or the disease was advanced (resid.ds=2) at the beginning of the study. What stratification does is it performs the analyses of the series of contingency tables for each strata separately and then pools the results. This ensures that if there are differences between the women with minimal vs. with extensive residual disease (which is to be expected), this will not skew the estimate of the treatment effect. There are more patients with extensive residual disease than minimal residual disease in the control group (8 vs. 5), while the ratio is more balanced in the treatment group (7 vs. 6). table(ovarian$resid.ds, ovarian$rx, dnn=c("resid.ds", "rx"))## rx## resid.ds 1 2## 1 5 6## 2 8 7 To ensure that we test for difference in the treatment and not for the difference between the patients with less advanced vs. advanced disease, we calculate the observed and expected counts and their variance separately in each stratum (extensive vs. minimal residual disease). The event times (censored times are followed by a plus sign) are listed for each treatment group at the top right: Pooling the results together (taking the sum of a, E(A) and Var(A) over both groups), we obtain MH2 = (7–5.09)2/(0.743+2.093) = 1.286. Now we check the output of the survdiff() function when the strata(resid.ds) argument in the formula is added: logr_strat <- survdiff(Surv(ovarian$futime, ovarian$fustat) ~ rx + strata(resid.ds), data = ovarian)logr_strat## Call:## survdiff(formula = Surv(ovarian$futime, ovarian$fustat) ~ rx + ## strata(resid.ds), data = ovarian)## ## N Observed Expected (O-E)^2/E (O-E)^2/V## rx=1 13 7 5.1 0.712 1.28## rx=2 13 5 6.9 0.525 1.28## ## Chisq= 1.3 on 1 degrees of freedom, p= 0.3 Again, except for a rounding error, we obtain the same result for the MH2, i.e. (O-E)^2/V is 1.28. In this case, the p-value is still 0.3 and hence does not change much compared to the value before stratification. Note that for such important covariates that are expected to have a significant effect on the survival, it is crucial to perform stratification at the randomization stage, i.e. when designing the experiment. This means that we must ensure that the proportion of patients from each strata is approximately the same in each treatment group, so that the test is powerful enough for the potential treatment effect to be detected. The log-rank test is used when we want to establish whether survival distributions of two groups differ. It is one of the most prevalent and accepted ways of providing evidence that a drug has a positive treatment effect. It arises as an adaptation of Fisher’s exact test, or more precisely the Mantel Haenszel test for censored data. A contingency table is created for each time of event and the results are then pooled to compute the desired statistic. If we want to avoid accidentally testing for another covariate that is imbalanced between the groups, or prevent the treatment effect from being masked by a covariate, we can use stratification. In that case, the contingency tables are created separately for each level of the covariate, and the results are pooled together, as shown above. The log-rank test is non-parametric: we did not assume any distribution of the event times. Nevertheless, it arises as score test in the semi-parametric Cox proportional hazards model (more on that in the next article). Note that ‘testing for a significant treatment effect’ is an arbitrary task in case of comparing two survival curves. Here is a nice illustration of the different scenarios that all have a positive treatment effect. The log-rank is oriented towards one type of those scenarios.
[ { "code": null, "e": 572, "s": 172, "text": "In Part 1 of the series, I explained the reasoning behind the Kaplan-Meier estimator of the survival curve. While it is a ubiquitous tool for visualizing the results of a clinical trial that involves a time-to-event analysis, it is only descriptive. To be able to draw conclusions and show the benefits of a new treatment, we need a formal testing procedure. One such procedure is the log-rank test." }, { "code": null, "e": 696, "s": 572, "text": "I will take a look at how it’s derived and why it’s still considered one of the most important indicators of drug efficacy." }, { "code": null, "e": 778, "s": 696, "text": "We start with a ggplot of a survfit object, using the same data set as in Part 1:" }, { "code": null, "e": 993, "s": 778, "text": "library(survival)library(survminer)data(ovarian)fit <- survfit(Surv(ovarian$futime, ovarian$fustat) ~ rx, data = ovarian, conf.type=\"log\")p_fit <- ggsurvplot( fit, conf.int = TRUE, pval = TRUE)p_fit" }, { "code": null, "e": 1224, "s": 993, "text": "How the survival probability estimates and confidence intervals are obtained is described in Part 1. If pval is set to TRUE, the function also prints the p-value 0.3, which is a result of a log-rank test. So how was it calculated?" }, { "code": null, "e": 1475, "s": 1224, "text": "The log-rank test is basically multiple separate Fisher’s exact tests pooled together. I will show exactly what I mean by that later. But it is essential to first understand how the Fisher’s exact test works. So let’s start with a fictitious example." }, { "code": null, "e": 1920, "s": 1475, "text": "Suppose there is an Introduction to statistics class for second-year university students. They can attend tutorials during the semester, which some do and some don’t. After the final exam, we want to see if failing the exam is associated with tutorial attendance. And so for every student, we record whether they were present at the tutorials at least 75% of the time in addition to whether they passed or not. And we get the following picture:" }, { "code": null, "e": 2047, "s": 1920, "text": "Now we want to test whether tutorial attendance and passing the exam are independent. The probabilities table looks like this:" }, { "code": null, "e": 2074, "s": 2047, "text": "Meaning, for example, that" }, { "code": null, "e": 2382, "s": 2074, "text": "and the hypothesis we want to test is H0: π11/π1+ = π21/π2+. Now suppose this hypothesis is true. This means that we would expect the proportion of failed students in the group with high tutorial attendance to be similar to the proportion of failed students in the group with low attendance. In other words," }, { "code": null, "e": 2541, "s": 2382, "text": "with A being the random variable whose value is the number of students who both attended 75%+ of tutorials and passed the exam. What is the distribution of A?" }, { "code": null, "e": 2936, "s": 2541, "text": "Note that n++ as well as the marginals (fail/pass & attendance - yes/no counts) are fixed. Under the null hypothesis, the probability that A=a (probability that the number of students who passed and attended 75%+ of tutorials is equal to a) is the probability that if out of n++=343 students, of which 217 attended 75%+ tutorials, we pick 281 at random, a would have attended 75%+ of tutorials." }, { "code": null, "e": 3266, "s": 2936, "text": "This is because we assume that those 281 students who passed are no different to the whole sample of 343 of students in terms of how much they went to tutorial classes. The distribution of A is called the hypergeometric distribution, and one can both derive or just copy from Wikipedia its probability mass function and variance:" }, { "code": null, "e": 3411, "s": 3266, "text": "Calculating exact p-values for samples this big is problematic, but we can use the chi-squared approximation of the following statistic instead:" }, { "code": null, "e": 3623, "s": 3411, "text": "Suppose the same experiment was done at 12 different universities. We don’t want to combine these into one table, as there might be differences between the universities. We want to test the following hypothesis:" }, { "code": null, "e": 3715, "s": 3623, "text": "H0: π11 = π12, π21 = π22, ..., πk1 = πk2, where k is the number of sites (in this case 12)." }, { "code": null, "e": 3769, "s": 3715, "text": "This can be done using the Mantel–Haenszel statistic:" }, { "code": null, "e": 3997, "s": 3769, "text": "i is the group index, O is the sum of observed deaths, E the sum of expected deaths, and V is the sum of variances of the deaths in population 1, over all sites. We plug in the sums into MH and note its asymptotic distribution:" }, { "code": null, "e": 4123, "s": 3997, "text": "This is used to test the null hypothesis the usual way. Now we can use this same statistic and apply it on our censored data." }, { "code": null, "e": 4312, "s": 4123, "text": "How does this relate to the log-rank test? Essentially, we look at each time point when death was observed as the “university” in the above example and create a contingency table for each." }, { "code": null, "e": 4480, "s": 4312, "text": "Even though the samples (“universities”) are not independent, the asymptotic distribution of Menzel-Haenszel statistic is still chi-squared with one degree of freedom." }, { "code": null, "e": 4621, "s": 4480, "text": "Effectively, we test the hypothesis H0: F1 = F2, or the equality of survival curves for the combined treatment and standard treatment group." }, { "code": null, "e": 4790, "s": 4621, "text": "Now let’s check how they obtained the p-value on the graph from the beginning of the article. We basically create a contingency table for each time point t of an event." }, { "code": null, "e": 5063, "s": 4790, "text": "From this table, we can calculate the number of deaths a and the expectation and variance of A for each ti under the null hypothesis. All that is left is to sum these and plug in into the expression for our test statistic, MH. In this case, MH2 = (7–5.23)2 / 2.94 = 1.066." }, { "code": null, "e": 5151, "s": 5063, "text": "Note that the event times do not enter the statistic calculations, only their ranks do." }, { "code": null, "e": 5248, "s": 5151, "text": "In R, the log-rank test can be performed with the function survdiff() from the package survival." }, { "code": null, "e": 5644, "s": 5248, "text": "logr <- survdiff(Surv(ovarian$futime, ovarian$fustat) ~ rx, data = ovarian)logr## Call:## survdiff(formula = Surv(ovarian$futime, ovarian$fustat) ~ rx,## data = ovarian)## ## N Observed Expected (O-E)^2/E (O-E)^2/V## rx=1 13 7 5.23 0.596 1.06## rx=2 13 5 6.77 0.461 1.06## ## Chisq= 1.1 on 1 degrees of freedom, p= 0.3" }, { "code": null, "e": 5971, "s": 5644, "text": "Apart from some differences due to rounding, the test gives the same answer as was calculated manually above. In particular (O-E)^2/V is 1.06, which is the MH2 statistic. The probability of a chi-squared distributed variable with 1 degree of freedom being larger than this is 0.3, which can be checked with the following code:" }, { "code": null, "e": 6012, "s": 5971, "text": "1 - pchisq(1.06, df = 1)## [1] 0.3032152" }, { "code": null, "e": 6131, "s": 6012, "text": "Hence, we cannot reject the null hypothesis that the combined treatment is no better (or worse) than the standard one." }, { "code": null, "e": 6394, "s": 6131, "text": "To account for covariates, we can stratify the sample. In this case, there is a variable resid.ds in the data set, indicating whether there was minimal residual disease present (resid.ds=1), or the disease was advanced (resid.ds=2) at the beginning of the study." }, { "code": null, "e": 6732, "s": 6394, "text": "What stratification does is it performs the analyses of the series of contingency tables for each strata separately and then pools the results. This ensures that if there are differences between the women with minimal vs. with extensive residual disease (which is to be expected), this will not skew the estimate of the treatment effect." }, { "code": null, "e": 6917, "s": 6732, "text": "There are more patients with extensive residual disease than minimal residual disease in the control group (8 vs. 5), while the ratio is more balanced in the treatment group (7 vs. 6)." }, { "code": null, "e": 7036, "s": 6917, "text": "table(ovarian$resid.ds, ovarian$rx, dnn=c(\"resid.ds\", \"rx\"))## rx## resid.ds 1 2## 1 5 6## 2 8 7" }, { "code": null, "e": 7429, "s": 7036, "text": "To ensure that we test for difference in the treatment and not for the difference between the patients with less advanced vs. advanced disease, we calculate the observed and expected counts and their variance separately in each stratum (extensive vs. minimal residual disease). The event times (censored times are followed by a plus sign) are listed for each treatment group at the top right:" }, { "code": null, "e": 7675, "s": 7429, "text": "Pooling the results together (taking the sum of a, E(A) and Var(A) over both groups), we obtain MH2 = (7–5.09)2/(0.743+2.093) = 1.286. Now we check the output of the survdiff() function when the strata(resid.ds) argument in the formula is added:" }, { "code": null, "e": 8132, "s": 7675, "text": "logr_strat <- survdiff(Surv(ovarian$futime, ovarian$fustat) ~ rx + strata(resid.ds), data = ovarian)logr_strat## Call:## survdiff(formula = Surv(ovarian$futime, ovarian$fustat) ~ rx + ## strata(resid.ds), data = ovarian)## ## N Observed Expected (O-E)^2/E (O-E)^2/V## rx=1 13 7 5.1 0.712 1.28## rx=2 13 5 6.9 0.525 1.28## ## Chisq= 1.3 on 1 degrees of freedom, p= 0.3" }, { "code": null, "e": 8231, "s": 8132, "text": "Again, except for a rounding error, we obtain the same result for the MH2, i.e. (O-E)^2/V is 1.28." }, { "code": null, "e": 8772, "s": 8231, "text": "In this case, the p-value is still 0.3 and hence does not change much compared to the value before stratification. Note that for such important covariates that are expected to have a significant effect on the survival, it is crucial to perform stratification at the randomization stage, i.e. when designing the experiment. This means that we must ensure that the proportion of patients from each strata is approximately the same in each treatment group, so that the test is powerful enough for the potential treatment effect to be detected." }, { "code": null, "e": 9227, "s": 8772, "text": "The log-rank test is used when we want to establish whether survival distributions of two groups differ. It is one of the most prevalent and accepted ways of providing evidence that a drug has a positive treatment effect. It arises as an adaptation of Fisher’s exact test, or more precisely the Mantel Haenszel test for censored data. A contingency table is created for each time of event and the results are then pooled to compute the desired statistic." }, { "code": null, "e": 9568, "s": 9227, "text": "If we want to avoid accidentally testing for another covariate that is imbalanced between the groups, or prevent the treatment effect from being masked by a covariate, we can use stratification. In that case, the contingency tables are created separately for each level of the covariate, and the results are pooled together, as shown above." }, { "code": null, "e": 9660, "s": 9568, "text": "The log-rank test is non-parametric: we did not assume any distribution of the event times." }, { "code": null, "e": 9788, "s": 9660, "text": "Nevertheless, it arises as score test in the semi-parametric Cox proportional hazards model (more on that in the next article)." } ]
Java Program to get duration between two time instants
Create two time instants: Instant time1 = Instant.now(); Instant time2 = Instant.now().plusSeconds(50); Use between() to get the duration between two time instants: long resMilli = Duration.between(time1, time2).toMillis(); import java.time.Duration; import java.time.Instant; public class Demo { public static void main(String[] args) { Instant time1 = Instant.now(); Instant time2 = Instant.now().plusSeconds(50); long resMilli = Duration.between(time1, time2).toMillis(); System.out.println("Duration between two time intervals = "+resMilli); } } Duration between two time intervals = 50000
[ { "code": null, "e": 1088, "s": 1062, "text": "Create two time instants:" }, { "code": null, "e": 1166, "s": 1088, "text": "Instant time1 = Instant.now();\nInstant time2 = Instant.now().plusSeconds(50);" }, { "code": null, "e": 1227, "s": 1166, "text": "Use between() to get the duration between two time instants:" }, { "code": null, "e": 1286, "s": 1227, "text": "long resMilli = Duration.between(time1, time2).toMillis();" }, { "code": null, "e": 1642, "s": 1286, "text": "import java.time.Duration;\nimport java.time.Instant;\npublic class Demo {\n public static void main(String[] args) {\n Instant time1 = Instant.now();\n Instant time2 = Instant.now().plusSeconds(50);\n long resMilli = Duration.between(time1, time2).toMillis();\n System.out.println(\"Duration between two time intervals = \"+resMilli);\n }\n}" }, { "code": null, "e": 1686, "s": 1642, "text": "Duration between two time intervals = 50000" } ]
How do I get the current AUTO_INCREMENT value for a table in MySQL?
To know the current auto_increment value, we can use the last_insert_id() function. Firstly, we will create a table with the help of INSERT command. Creating a table − mysql> CREATE table AutoIncrement -> ( -> IdAuto int auto_increment, -> primary key(IdAuto) -> ); Query OK, 0 rows affected (0.59 sec) After creating a table, we will insert the records with the help of INSERT command. Inserting records − mysql> INSERT into AutoIncrement values(); Query OK, 1 row affected (0.48 sec) mysql> INSERT into AutoIncrement values(); Query OK, 1 row affected (0.17 sec) mysql> INSERT into AutoIncrement values(); Query OK, 1 row affected (0.13 sec) mysql> INSERT into AutoIncrement values(); Query OK, 1 row affected (0.09 sec) Now, we will see how many records have I inserted into my table with the help of SELECT command. Displaying all records − mysql> SELECT * from AutoIncrement; +--------+ | IdAuto | +--------+ | 1 | | 2 | | 3 | | 4 | +--------+ 4 rows in set (0.00 sec) Therefore, the last auto increment is 4. Here is the query to know the current value have inserted, which is 4. mysql> SELECT last_insert_id(); The following is the output − +------------------+ | last_insert_id() | +------------------+ | 4 | +------------------+ 1 row in set (0.00 sec) Here is the query that tells the next auto increment value. The syntax is as follows − SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'yourDatabaseName' AND TABLE_NAME = 'yourTableName'; Now, I am applying the above query − mysql> SELECT `AUTO_INCREMENT` -> FROM INFORMATION_SCHEMA.TABLES -> WHERE TABLE_SCHEMA = 'business' -> AND TABLE_NAME = 'AutoIncrement'; The following is the output − +----------------------------+ | AUTO_INCREMENT | +----------------------------+ | 5 | +----------------------------+ 1 row in set (0.13 sec) From the above query, we are getting the next increment value.
[ { "code": null, "e": 1211, "s": 1062, "text": "To know the current auto_increment value, we can use the last_insert_id() function. Firstly, we will create a table with the help of INSERT command." }, { "code": null, "e": 1230, "s": 1211, "text": "Creating a table −" }, { "code": null, "e": 1365, "s": 1230, "text": "mysql> CREATE table AutoIncrement\n-> (\n-> IdAuto int auto_increment,\n-> primary key(IdAuto)\n-> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1469, "s": 1365, "text": "After creating a table, we will insert the records with the help of INSERT command. Inserting\nrecords −" }, { "code": null, "e": 1788, "s": 1469, "text": "mysql> INSERT into AutoIncrement values();\nQuery OK, 1 row affected (0.48 sec)\n\nmysql> INSERT into AutoIncrement values();\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> INSERT into AutoIncrement values();\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> INSERT into AutoIncrement values();\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 1885, "s": 1788, "text": "Now, we will see how many records have I inserted into my table with the help of SELECT\ncommand." }, { "code": null, "e": 1910, "s": 1885, "text": "Displaying all records −" }, { "code": null, "e": 2059, "s": 1910, "text": "mysql> SELECT * from AutoIncrement;\n+--------+\n| IdAuto |\n+--------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2171, "s": 2059, "text": "Therefore, the last auto increment is 4. Here is the query to know the current value have\ninserted, which is 4." }, { "code": null, "e": 2204, "s": 2171, "text": "mysql> SELECT last_insert_id();\n" }, { "code": null, "e": 2234, "s": 2204, "text": "The following is the output −" }, { "code": null, "e": 2363, "s": 2234, "text": "+------------------+\n| last_insert_id() |\n+------------------+\n| 4 |\n+------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2450, "s": 2363, "text": "Here is the query that tells the next auto increment value. The syntax is as follows −" }, { "code": null, "e": 2579, "s": 2450, "text": "SELECT `AUTO_INCREMENT`\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA = 'yourDatabaseName'\nAND TABLE_NAME = 'yourTableName';" }, { "code": null, "e": 2616, "s": 2579, "text": "Now, I am applying the above query −" }, { "code": null, "e": 2753, "s": 2616, "text": "mysql> SELECT `AUTO_INCREMENT`\n-> FROM INFORMATION_SCHEMA.TABLES\n-> WHERE TABLE_SCHEMA = 'business'\n-> AND TABLE_NAME = 'AutoIncrement';" }, { "code": null, "e": 2783, "s": 2753, "text": "The following is the output −" }, { "code": null, "e": 2962, "s": 2783, "text": "+----------------------------+\n| AUTO_INCREMENT |\n+----------------------------+\n| 5 |\n+----------------------------+\n1 row in set (0.13 sec)" }, { "code": null, "e": 3025, "s": 2962, "text": "From the above query, we are getting the next increment value." } ]
How to write a switch statement in a JSP page?
Following is the example of using a switch statement within a JSP page. Live Demo <%! int day = 3; %> <html> <head> <title>SWITCH...CASE Example</title> </head> <body> <% switch(day) { case 0: out.println("It\'s Sunday."); break; case 1: out.println("It\'s Monday."); break; case 2: out.println("It\'s Tuesday."); break; case 3: out.println("It\'s Wednesday."); break; case 4: out.println("It\'s Thursday."); break; case 5: out.println("It\'s Friday."); break; default: out.println("It's Saturday."); } %> </body> </html> The above code will generate the following result − It's Wednesday.
[ { "code": null, "e": 1134, "s": 1062, "text": "Following is the example of using a switch statement within a JSP page." }, { "code": null, "e": 1145, "s": 1134, "text": " Live Demo" }, { "code": null, "e": 1912, "s": 1145, "text": "<%! int day = 3; %>\n<html>\n <head>\n <title>SWITCH...CASE Example</title>\n </head>\n <body>\n <%\n switch(day) {\n case 0:\n out.println(\"It\\'s Sunday.\");\n break;\n case 1:\n out.println(\"It\\'s Monday.\");\n break;\n case 2:\n out.println(\"It\\'s Tuesday.\");\n break;\n case 3:\n out.println(\"It\\'s Wednesday.\");\n break;\n case 4:\n out.println(\"It\\'s Thursday.\");\n break;\n case 5:\n out.println(\"It\\'s Friday.\");\n break;\n default:\n out.println(\"It's Saturday.\");\n }\n %>\n </body>\n</html>" }, { "code": null, "e": 1964, "s": 1912, "text": "The above code will generate the following result −" }, { "code": null, "e": 1980, "s": 1964, "text": "It's Wednesday." } ]
Add a row at top in pandas DataFrame - GeeksforGeeks
29 Jul, 2021 Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let’s see how can we can add a row at top in pandas DataFrame.Observe this dataset first. Python3 # importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df.head(10) Code #1: Adding row at the top of given dataframe by concatenating the old dataframe with new one. Python3 new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0])# simply concatenate both dataframesdf = pd.concat([new_row, df]).reset_index(drop = True)df.head(5) Output: Code #2: Adding row at the top of given dataframe by concatenating the old dataframe with new one. Python3 new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0]) # Concatenate new_row with dfdf = pd.concat([new_row, df[:]]).reset_index(drop = True)df.head(5) Output: Code #3: Adding row at the top of given dataframe by concatenating the old dataframe with new one using df.ix[] method. Python3 new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0]) df = pd.concat([new_row, df.ix[:]]).reset_index(drop = True)df.head(5) Output: surindertarika1234 pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n29 Jul, 2021" }, { "code": null, "e": 24440, "s": 24212, "text": "Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let’s see how can we can add a row at top in pandas DataFrame.Observe this dataset first. " }, { "code": null, "e": 24448, "s": 24440, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df.head(10)", "e": 24605, "s": 24448, "text": null }, { "code": null, "e": 24706, "s": 24605, "text": "Code #1: Adding row at the top of given dataframe by concatenating the old dataframe with new one. " }, { "code": null, "e": 24714, "s": 24706, "text": "Python3" }, { "code": "new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0])# simply concatenate both dataframesdf = pd.concat([new_row, df]).reset_index(drop = True)df.head(5)", "e": 25091, "s": 24714, "text": null }, { "code": null, "e": 25101, "s": 25091, "text": "Output: " }, { "code": null, "e": 25204, "s": 25101, "text": " Code #2: Adding row at the top of given dataframe by concatenating the old dataframe with new one. " }, { "code": null, "e": 25212, "s": 25204, "text": "Python3" }, { "code": "new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0]) # Concatenate new_row with dfdf = pd.concat([new_row, df[:]]).reset_index(drop = True)df.head(5)", "e": 25527, "s": 25212, "text": null }, { "code": null, "e": 25537, "s": 25527, "text": "Output: " }, { "code": null, "e": 25660, "s": 25537, "text": " Code #3: Adding row at the top of given dataframe by concatenating the old dataframe with new one using df.ix[] method. " }, { "code": null, "e": 25668, "s": 25660, "text": "Python3" }, { "code": "new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99999}, index =[0]) df = pd.concat([new_row, df.ix[:]]).reset_index(drop = True)df.head(5)", "e": 25957, "s": 25668, "text": null }, { "code": null, "e": 25967, "s": 25957, "text": "Output: " }, { "code": null, "e": 25988, "s": 25969, "text": "surindertarika1234" }, { "code": null, "e": 26013, "s": 25988, "text": "pandas-dataframe-program" }, { "code": null, "e": 26037, "s": 26013, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26051, "s": 26037, "text": "Python-pandas" }, { "code": null, "e": 26058, "s": 26051, "text": "Python" }, { "code": null, "e": 26156, "s": 26058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26165, "s": 26156, "text": "Comments" }, { "code": null, "e": 26178, "s": 26165, "text": "Old Comments" }, { "code": null, "e": 26199, "s": 26178, "text": "Python OOPs Concepts" }, { "code": null, "e": 26231, "s": 26199, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26254, "s": 26231, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26276, "s": 26254, "text": "Defaultdict in Python" }, { "code": null, "e": 26303, "s": 26276, "text": "Python Classes and Objects" }, { "code": null, "e": 26319, "s": 26303, "text": "Deque in Python" }, { "code": null, "e": 26361, "s": 26319, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26417, "s": 26361, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26462, "s": 26417, "text": "Python - Ways to remove duplicates from list" } ]
PHP | md5(), sha1(), hash() Functions - GeeksforGeeks
08 Mar, 2018 PHP is a server-side scripting language which implies that PHP is responsible for all the back-end functionalities required by the website. The authentication system is one of the most important parts of a website and it is one of the most commonplace where developers commit mistakes leaving out vulnerabilities for others to exploit. One example could be storing and using user passwords in its true form, which may lead to a situation where an unauthorized person gets the access to the database and the whole system is compromised. This situation can be easily prevented using password hashing. Password Hashing is a method which takes the user password( a variable-length sequence of characters) and encrypts it to a fixed-length password containing random characters from a larger set. PHP has a few functions that can be used to achieve the same. md5() Function Syntax: string md5 ($string, $getRawOutput) Parameters: The function an take up to a maximum of two parameters as follows: $string: This parameter expects the string to be hashed. $getRawOutput: This optional parameter expects a boolean value, on TRUE the function returns the hash in a raw binary format of length 16. Return Type: This function returns the hashed string (either in lowercase hex character sequence of length 32 or raw binary form of length 16). sha1() Function Syntax: string sha1($string, $getRawOutput) Parameters: The function an take up to a maximum of two parameters as follows: $string: This parameter expects the string to be hashed. $getRawOutput: This optional parameter expects a boolean value, on TRUE the function returns the hash in a raw binary format of length 20. Return Type: This function returns the hashed string (either in lowercase hex character sequence of length 40 or raw binary form of length 20). hash() Function Syntax: string hash($algo, $string, $getRawOutput) Parameters: The function an take up to a maximum of three parameters as follows: $algo: This parameter expects a string defining the hashing algorithm to be used. PHP has a total of 46 registered hashing algorithms among which “sha1”, “sha256”, “md5”, “haval160, 4” are the most popular ones. $string: This parameter expects the string to be hashed. $getRawOutput: This optional parameter expects a boolean value, on TRUE the function returns the hash in a raw binary format. Return Type: This function returns the hashed string (either in lowercase hex character sequence or raw binary form). Below program illustrates the working of md5(), sha1() and hash() in PHP: <?php // PHP code to illustrate the working // of md5(), sha1() and hash() $str = 'Password';$salt = 'Username20Jun96';echo sprintf("The md5 hashed password of %s is: %s\n", $str, md5($str.$salt));echo sprintf("The sha1 hashed password of %s is: %s\n", $str, sha1($str.$salt));echo sprintf("The gost hashed password of %s is: %s\n", $str, hash('gost', $str.$salt)); ?> Output: The md5 hashed password of Password is: a59a0e0fcfab450008571e94a5549225 The sha1 hashed password of Password is: a69652ddbc8401ae93b5d2f0390d98abd94fc2f4 The gost hashed password of Password is: 5376160a0d848c327949364b96fb9fd6e13a9b20c58fbab50f418ea9eea3b67f Important points to note: The complexity of a hashing algorithm defines how good the hashing is itself. Both sha1 and md5 are not very complex thus experts suggest we should use the following algorithms only if the risk factor is not condemnable. Using only the Password as input string gives a mediocre result, but using salt we can enhance the result. Salt in hashing is a term that refers to a random string that is used explicitly with the password. Many developers prefer to use the username and some other field (such as Date of birth in the example) as the salt which increases the randomness. A hashing algorithm should preferably be a one-way route i.e. there should not exist a decrypt method, but all these known algorithms can be guessed with a proper implementation of Brute Force and Dictionary attack. Reference: http://php.net/manual/en/function.hash.php http://php.net/manual/en/function.sha1.php http://php.net/manual/en/function.md5.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP How to get parameters from a URL string in PHP? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26327, "s": 26299, "text": "\n08 Mar, 2018" }, { "code": null, "e": 26863, "s": 26327, "text": "PHP is a server-side scripting language which implies that PHP is responsible for all the back-end functionalities required by the website. The authentication system is one of the most important parts of a website and it is one of the most commonplace where developers commit mistakes leaving out vulnerabilities for others to exploit. One example could be storing and using user passwords in its true form, which may lead to a situation where an unauthorized person gets the access to the database and the whole system is compromised." }, { "code": null, "e": 27181, "s": 26863, "text": "This situation can be easily prevented using password hashing. Password Hashing is a method which takes the user password( a variable-length sequence of characters) and encrypts it to a fixed-length password containing random characters from a larger set. PHP has a few functions that can be used to achieve the same." }, { "code": null, "e": 27196, "s": 27181, "text": "md5() Function" }, { "code": null, "e": 27204, "s": 27196, "text": "Syntax:" }, { "code": null, "e": 27241, "s": 27204, "text": "string md5 ($string, $getRawOutput)\n" }, { "code": null, "e": 27320, "s": 27241, "text": "Parameters: The function an take up to a maximum of two parameters as follows:" }, { "code": null, "e": 27377, "s": 27320, "text": "$string: This parameter expects the string to be hashed." }, { "code": null, "e": 27516, "s": 27377, "text": "$getRawOutput: This optional parameter expects a boolean value, on TRUE the function returns the hash in a raw binary format of length 16." }, { "code": null, "e": 27660, "s": 27516, "text": "Return Type: This function returns the hashed string (either in lowercase hex character sequence of length 32 or raw binary form of length 16)." }, { "code": null, "e": 27676, "s": 27660, "text": "sha1() Function" }, { "code": null, "e": 27684, "s": 27676, "text": "Syntax:" }, { "code": null, "e": 27721, "s": 27684, "text": "string sha1($string, $getRawOutput)\n" }, { "code": null, "e": 27800, "s": 27721, "text": "Parameters: The function an take up to a maximum of two parameters as follows:" }, { "code": null, "e": 27857, "s": 27800, "text": "$string: This parameter expects the string to be hashed." }, { "code": null, "e": 27996, "s": 27857, "text": "$getRawOutput: This optional parameter expects a boolean value, on TRUE the function returns the hash in a raw binary format of length 20." }, { "code": null, "e": 28140, "s": 27996, "text": "Return Type: This function returns the hashed string (either in lowercase hex character sequence of length 40 or raw binary form of length 20)." }, { "code": null, "e": 28156, "s": 28140, "text": "hash() Function" }, { "code": null, "e": 28164, "s": 28156, "text": "Syntax:" }, { "code": null, "e": 28208, "s": 28164, "text": "string hash($algo, $string, $getRawOutput)\n" }, { "code": null, "e": 28289, "s": 28208, "text": "Parameters: The function an take up to a maximum of three parameters as follows:" }, { "code": null, "e": 28501, "s": 28289, "text": "$algo: This parameter expects a string defining the hashing algorithm to be used. PHP has a total of 46 registered hashing algorithms among which “sha1”, “sha256”, “md5”, “haval160, 4” are the most popular ones." }, { "code": null, "e": 28558, "s": 28501, "text": "$string: This parameter expects the string to be hashed." }, { "code": null, "e": 28684, "s": 28558, "text": "$getRawOutput: This optional parameter expects a boolean value, on TRUE the function returns the hash in a raw binary format." }, { "code": null, "e": 28802, "s": 28684, "text": "Return Type: This function returns the hashed string (either in lowercase hex character sequence or raw binary form)." }, { "code": null, "e": 28876, "s": 28802, "text": "Below program illustrates the working of md5(), sha1() and hash() in PHP:" }, { "code": "<?php // PHP code to illustrate the working // of md5(), sha1() and hash() $str = 'Password';$salt = 'Username20Jun96';echo sprintf(\"The md5 hashed password of %s is: %s\\n\", $str, md5($str.$salt));echo sprintf(\"The sha1 hashed password of %s is: %s\\n\", $str, sha1($str.$salt));echo sprintf(\"The gost hashed password of %s is: %s\\n\", $str, hash('gost', $str.$salt)); ?>", "e": 29359, "s": 28876, "text": null }, { "code": null, "e": 29367, "s": 29359, "text": "Output:" }, { "code": null, "e": 29632, "s": 29367, "text": "The md5 hashed password of Password is: \na59a0e0fcfab450008571e94a5549225\nThe sha1 hashed password of Password is: \na69652ddbc8401ae93b5d2f0390d98abd94fc2f4\nThe gost hashed password of Password is:\n5376160a0d848c327949364b96fb9fd6e13a9b20c58fbab50f418ea9eea3b67f\n" }, { "code": null, "e": 29658, "s": 29632, "text": "Important points to note:" }, { "code": null, "e": 29879, "s": 29658, "text": "The complexity of a hashing algorithm defines how good the hashing is itself. Both sha1 and md5 are not very complex thus experts suggest we should use the following algorithms only if the risk factor is not condemnable." }, { "code": null, "e": 30233, "s": 29879, "text": "Using only the Password as input string gives a mediocre result, but using salt we can enhance the result. Salt in hashing is a term that refers to a random string that is used explicitly with the password. Many developers prefer to use the username and some other field (such as Date of birth in the example) as the salt which increases the randomness." }, { "code": null, "e": 30449, "s": 30233, "text": "A hashing algorithm should preferably be a one-way route i.e. there should not exist a decrypt method, but all these known algorithms can be guessed with a proper implementation of Brute Force and Dictionary attack." }, { "code": null, "e": 30460, "s": 30449, "text": "Reference:" }, { "code": null, "e": 30503, "s": 30460, "text": "http://php.net/manual/en/function.hash.php" }, { "code": null, "e": 30546, "s": 30503, "text": "http://php.net/manual/en/function.sha1.php" }, { "code": null, "e": 30588, "s": 30546, "text": "http://php.net/manual/en/function.md5.php" }, { "code": null, "e": 30601, "s": 30588, "text": "PHP-function" }, { "code": null, "e": 30605, "s": 30601, "text": "PHP" }, { "code": null, "e": 30622, "s": 30605, "text": "Web Technologies" }, { "code": null, "e": 30626, "s": 30622, "text": "PHP" }, { "code": null, "e": 30724, "s": 30626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30764, "s": 30724, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 30809, "s": 30764, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 30851, "s": 30809, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 30903, "s": 30851, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 30951, "s": 30903, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 30991, "s": 30951, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31024, "s": 30991, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31069, "s": 31024, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31112, "s": 31069, "text": "How to fetch data from an API in ReactJS ?" } ]
BooleanField - Django Forms - GeeksforGeeks
13 Feb, 2020 BooleanField in Django Forms is a checkbox field which stores either True or False. It is used for taking boolean inputs from the user. The default widget for this input is CheckboxInput. It normalizes to: A Python True or False value. Syntax field_name = forms.BooleanField(**options) Illustration of BooleanField 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.BooleanField( ) 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 = "GET"> {{ form }} <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 BooleanField is created by replacing “_” with ” “. It is a field to store boolean values – True or False. BooleanField is used for input of boolean values in the database. One can input boolean fields such as is_admin, is_teacher, is_staff, etc. Till now we have discussed how to implement BooleanField 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 ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(temp) return render(request, "home.html", context) Now let’s try turning on the field button. Now this 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. 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 BooleanField 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 ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25421, "s": 25393, "text": "\n13 Feb, 2020" }, { "code": null, "e": 25657, "s": 25421, "text": "BooleanField in Django Forms is a checkbox field which stores either True or False. It is used for taking boolean inputs from the user. The default widget for this input is CheckboxInput. It normalizes to: A Python True or False value." }, { "code": null, "e": 25664, "s": 25657, "text": "Syntax" }, { "code": null, "e": 25707, "s": 25664, "text": "field_name = forms.BooleanField(**options)" }, { "code": null, "e": 25820, "s": 25707, "text": "Illustration of BooleanField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 25907, "s": 25820, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 25958, "s": 25907, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25991, "s": 25958, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26049, "s": 25991, "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.BooleanField( )", "e": 26161, "s": 26049, "text": null }, { "code": null, "e": 26197, "s": 26161, "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": 26435, "s": 26197, "text": null }, { "code": null, "e": 26568, "s": 26435, "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": 26780, "s": 26568, "text": null }, { "code": null, "e": 27066, "s": 26780, "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 = \"GET\"> {{ form }} <input type = \"submit\" value = \"Submit\"></form>", "e": 27153, "s": 27066, "text": null }, { "code": null, "e": 27199, "s": 27153, "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": 27333, "s": 27199, "text": null }, { "code": null, "e": 27396, "s": 27333, "text": "Let’s run the server and check what has actually happened, Run" }, { "code": null, "e": 27423, "s": 27396, "text": "Python manage.py runserver" }, { "code": null, "e": 27550, "s": 27423, "text": "Thus, an geeks_field BooleanField is created by replacing “_” with ” “. It is a field to store boolean values – True or False." }, { "code": null, "e": 27925, "s": 27550, "text": "BooleanField is used for input of boolean values in the database. One can input boolean fields such as is_admin, is_teacher, is_staff, etc. Till now we have discussed how to implement BooleanField 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 ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(temp) return render(request, \"home.html\", context)", "e": 28228, "s": 27925, "text": null }, { "code": null, "e": 28271, "s": 28228, "text": "Now let’s try turning on the field button." }, { "code": null, "e": 28517, "s": 28271, "text": "Now this 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." }, { "code": null, "e": 28947, "s": 28517, "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 BooleanField 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": 28959, "s": 28947, "text": "NaveenArora" }, { "code": null, "e": 28972, "s": 28959, "text": "Django-forms" }, { "code": null, "e": 28986, "s": 28972, "text": "Python Django" }, { "code": null, "e": 28993, "s": 28986, "text": "Python" }, { "code": null, "e": 29091, "s": 28993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29109, "s": 29091, "text": "Python Dictionary" }, { "code": null, "e": 29144, "s": 29109, "text": "Read a file line by line in Python" }, { "code": null, "e": 29176, "s": 29144, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29198, "s": 29176, "text": "Enumerate() in Python" }, { "code": null, "e": 29240, "s": 29198, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29270, "s": 29240, "text": "Iterate over a list in Python" }, { "code": null, "e": 29296, "s": 29270, "text": "Python String | replace()" }, { "code": null, "e": 29325, "s": 29296, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29369, "s": 29325, "text": "Reading and Writing to text files in Python" } ]
C Quiz - 108 - GeeksforGeeks
31 May, 2021 #include <stdio.h> void wrt_it (void); int main (void) { printf("Enter Text"); printf ("n"); wrt_ it(); printf ("n"); return 0; } void wrt_it (void) { int c; if (?1) wrt_it(); ?2 } Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies C Program For Finding Length Of A Linked List How to calculate MOVING AVERAGE in a Pandas DataFrame? How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python How to Fix: KeyError in Pandas C Program to read contents of Whole File How to Append Pandas DataFrame to Existing CSV File? How to Replace Values in a List in Python?
[ { "code": null, "e": 28855, "s": 28827, "text": "\n31 May, 2021" }, { "code": null, "e": 29078, "s": 28855, "text": "#include <stdio.h>\nvoid wrt_it (void);\nint main (void)\n{\n printf(\"Enter Text\"); \n printf (\"n\");\n wrt_ it();\n printf (\"n\");\n return 0;\n}\nvoid wrt_it (void)\n{\n int c;\n if (?1)\n wrt_it();\n ?2\n}\n" }, { "code": null, "e": 29176, "s": 29078, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29229, "s": 29176, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29275, "s": 29229, "text": "C Program For Finding Length Of A Linked List" }, { "code": null, "e": 29330, "s": 29275, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 29388, "s": 29330, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 29450, "s": 29388, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 29530, "s": 29450, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 29561, "s": 29530, "text": "How to Fix: KeyError in Pandas" }, { "code": null, "e": 29602, "s": 29561, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29655, "s": 29602, "text": "How to Append Pandas DataFrame to Existing CSV File?" } ]
Introduction to Linear Bounded Automata (LBA) - GeeksforGeeks
02 Mar, 2021 History :In 1960, associate degree automaton model was introduced by Myhill and these days this automation model is understood as deterministic linear bounded automaton. After this, another scientist named Landweber worked on this and proposed that the languages accepted by a deterministic LBA are continually context-sensitive languages. In 1964, Kuroda introduced a replacement and a lot of general models specially for non-deterministic linear bounded automata, and established that the languages accepted by the non-deterministic linear bounded automata are exactly the context-sensitive languages. Introduction to Linear Bounded Automata :A Linear Bounded Automaton (LBA) is similar to Turing Machine with some properties stated below: Turing Machine with Non-deterministic logic, Turing Machine with Multi-track, and Turing Machine with a bounded finite length of the tape. Tuples Used in LBA : LBA can be defined with eight tuples (elements that help to design automata) as: M = (Q , T , E , q0 , ML , MR , S , F), where, Q -> A finite set of transition states T -> Tape alphabet E -> Input alphabet q0 -> Initial state ML -> Left bound of tape MR -> Right bound of tape S -> Transition Function F -> A finite set of final states Diagrammatic Representation of LBA : Examples: Languages that form LBA with tape as shown above, L = {an! | n >= 0} L = {wn | w from {a, b}+, n >= 1} L = {wwwR | w from {a, b}+} Facts : Suppose that a given LBA M has --> q states, --> m characters within the tape alphabet, and --> the input length is n Then M can be in at most f(n) = q * n * mn configurations i.e. a tape of n cells and m symbols, we are able to have solely mn totally different tapes.The tape head is typically on any of the n cells which we have a tendency to are typically death penalty in any of the q states. Then M can be in at most f(n) = q * n * mn configurations i.e. a tape of n cells and m symbols, we are able to have solely mn totally different tapes. The tape head is typically on any of the n cells which we have a tendency to are typically death penalty in any of the q states. Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. NPDA for accepting the language L = {an bn | n>=1} Construct Pushdown Automata for all length palindrome NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's} NPDA for accepting the language L = {wwR | w ∈ (a,b)*} Construct a Turing Machine for language L = {ww | w ∈ {0,1}} Pushdown Automata Acceptance by Final State Ambiguity in Context free Grammar and Context free Languages Halting Problem in Theory of Computation Decidability and Undecidability in TOC Decidable and Undecidable problems in Theory of Computation
[ { "code": null, "e": 26129, "s": 26101, "text": "\n02 Mar, 2021" }, { "code": null, "e": 26469, "s": 26129, "text": "History :In 1960, associate degree automaton model was introduced by Myhill and these days this automation model is understood as deterministic linear bounded automaton. After this, another scientist named Landweber worked on this and proposed that the languages accepted by a deterministic LBA are continually context-sensitive languages." }, { "code": null, "e": 26733, "s": 26469, "text": "In 1964, Kuroda introduced a replacement and a lot of general models specially for non-deterministic linear bounded automata, and established that the languages accepted by the non-deterministic linear bounded automata are exactly the context-sensitive languages." }, { "code": null, "e": 26871, "s": 26733, "text": "Introduction to Linear Bounded Automata :A Linear Bounded Automaton (LBA) is similar to Turing Machine with some properties stated below:" }, { "code": null, "e": 26916, "s": 26871, "text": "Turing Machine with Non-deterministic logic," }, { "code": null, "e": 26953, "s": 26916, "text": "Turing Machine with Multi-track, and" }, { "code": null, "e": 27010, "s": 26953, "text": "Turing Machine with a bounded finite length of the tape." }, { "code": null, "e": 27186, "s": 27083, "text": "Tuples Used in LBA : LBA can be defined with eight tuples (elements that help to design automata) as: " }, { "code": null, "e": 27446, "s": 27186, "text": "M = (Q , T , E , q0 , ML , MR , S , F), \n\nwhere, \nQ -> A finite set of transition states\nT -> Tape alphabet\nE -> Input alphabet\nq0 -> Initial state\nML -> Left bound of tape\nMR -> Right bound of tape\nS -> Transition Function\nF -> A finite set of final states " }, { "code": null, "e": 27483, "s": 27446, "text": "Diagrammatic Representation of LBA :" }, { "code": null, "e": 27493, "s": 27483, "text": "Examples:" }, { "code": null, "e": 27543, "s": 27493, "text": "Languages that form LBA with tape as shown above," }, { "code": null, "e": 27562, "s": 27543, "text": "L = {an! | n >= 0}" }, { "code": null, "e": 27596, "s": 27562, "text": "L = {wn | w from {a, b}+, n >= 1}" }, { "code": null, "e": 27624, "s": 27596, "text": "L = {wwwR | w from {a, b}+}" }, { "code": null, "e": 27632, "s": 27624, "text": "Facts :" }, { "code": null, "e": 27762, "s": 27632, "text": "Suppose that a given LBA M has\n --> q states,\n --> m characters within the tape alphabet, and\n --> the input length is n" }, { "code": null, "e": 28041, "s": 27762, "text": "Then M can be in at most f(n) = q * n * mn configurations i.e. a tape of n cells and m symbols, we are able to have solely mn totally different tapes.The tape head is typically on any of the n cells which we have a tendency to are typically death penalty in any of the q states." }, { "code": null, "e": 28192, "s": 28041, "text": "Then M can be in at most f(n) = q * n * mn configurations i.e. a tape of n cells and m symbols, we are able to have solely mn totally different tapes." }, { "code": null, "e": 28321, "s": 28192, "text": "The tape head is typically on any of the n cells which we have a tendency to are typically death penalty in any of the q states." }, { "code": null, "e": 28354, "s": 28321, "text": "Theory of Computation & Automata" }, { "code": null, "e": 28452, "s": 28354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28503, "s": 28452, "text": "NPDA for accepting the language L = {an bn | n>=1}" }, { "code": null, "e": 28557, "s": 28503, "text": "Construct Pushdown Automata for all length palindrome" }, { "code": null, "e": 28631, "s": 28557, "text": "NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's}" }, { "code": null, "e": 28686, "s": 28631, "text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}" }, { "code": null, "e": 28747, "s": 28686, "text": "Construct a Turing Machine for language L = {ww | w ∈ {0,1}}" }, { "code": null, "e": 28791, "s": 28747, "text": "Pushdown Automata Acceptance by Final State" }, { "code": null, "e": 28852, "s": 28791, "text": "Ambiguity in Context free Grammar and Context free Languages" }, { "code": null, "e": 28893, "s": 28852, "text": "Halting Problem in Theory of Computation" }, { "code": null, "e": 28932, "s": 28893, "text": "Decidability and Undecidability in TOC" } ]
Check for BST | Practice | GeeksforGeeks
Given the root of a binary tree. Check whether it is a BST or not. Note: We are considering that BSTs can not contain duplicate Nodes. A BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: 2 / \ 1 3 Output: 1 Explanation: The left subtree of root node contains node with key lesser than the root nodes key and the right subtree of root node contains node with key greater than the root nodes key. Hence, the tree is a BST. Example 2: Input: 2 \ 7 \ 6 \ 5 \ 9 \ 2 \ 6 Output: 0 Explanation: Since the node with value 7 has right subtree nodes with keys less than 7, this is not a BST. Your Task: You don't need to read input or print anything. Your task is to complete the function isBST() which takes the root of the tree as a parameter and returns true if the given binary tree is BST, else returns false. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the BST). Constraints: 0 <= Number of edges <= 100000 0 anikethjain This comment was deleted. 0 smohtashima15 hours ago Simple Python Solution with Iterative DFS using STACK: def isBST(self, root): #code here if not root: return True stack = [(root, -math.inf, math.inf)] while stack: root, lower, upper = stack.pop() if not root: continue val = root.data if val <= lower or val >= upper: return False stack.append((root.right, val, upper)) stack.append((root.left, lower, val)) return True +1 shashwatsingh7116 hours ago By Inorder Trav → Time - O(N) Space - O(N) bool isValidBST(TreeNode* root) { if(!root->left && !root->right ) return true; long prev=LONG_MIN; stack<TreeNode*> st; TreeNode* ptr=root; while(!st.empty() || ptr) { if(ptr) { st.push(ptr); ptr=ptr->left; } else { ptr=st.top(); st.pop(); if(prev >= ptr->val) return false; prev=ptr->val; ptr=ptr->right; } } return true; } By Morris Trav -→ Time = O(n) Space = O(1) bool isBST(Node* root) { Node* ptr=root; int prev=0; while(ptr) { if(!ptr->left) { if(prev>ptr->data) return false; prev=ptr->data; ptr=ptr->right; } else { Node* temp = ptr->left; while(temp->right && temp->right!=ptr) temp=temp->right; if(!temp->right) { temp->right=ptr; ptr=ptr->left; } else { temp->right=NULL; if(prev>ptr->data) return false; prev=ptr->data; ptr=ptr->right; } } } return true; } +1 sudhirdaga19981 day ago bool isValidBST(Node *root,int mini,int maxi) { if(root==NULL) return true; if(root->data > maxi || root->data < mini) return false; return (isValidBST(root->left,mini,root->data) && isValidBST(root->right,root->data,maxi)); } bool isBST(Node* root) { // Your code here return isValidBST(root,INT_MIN,INT_MAX); } 0 siddhantmedar2 days ago #Function to check whether a Binary Tree is BST or not. def isBST(self, root): #code here def util(root, mn, mx): if not root: return True if root.data < mn or root.data > mx: return False return util(root.left, mn, root.data-1) and util(root.right, root.data+1 ,mx) return util(root, float("-inf"), float("inf")) 0 neeshumaini554 days ago #intition #for every node we will define the range of values that satify the condition #condition -- a < root.val < b #a -- min_value #b -- max_value def bst(self,root,int_min,int_max): if root is None: return True if root.data < int_min or root.data > int_max: return False return self.bst(root.left,int_min,root.data) and self.bst(root.right,root.data,int_max) def isBST(self, root): return self.bst(root,float('-inf'),float('inf')) +1 anshrathore69844 days ago bool isBST(Node* node) { if(node ==NULL) return 1; if(node->left!=NULL && maxValue(node->left,node->data)) return 0; if(node->right!=NULL && minValue(node->right,node->data)) return 0; if (!isBST(node->left) || !isBST(node->right)) return 0; return 1; } bool maxValue(Node* node,int i) { if(node->data > i) return 1; else return 0; } bool minValue(Node* node , int i) { if(node->data < i) return 1; else return 0; } 101 test case passed 0 debojyotisinha5 days ago Programming Language: Java Test Cases Passed: 120 / 120 Total Time Taken: 0.39/1.13 public class Solution { int prev; boolean inOrder(Node root) { if (root != null) { boolean check1 = inOrder(root.left); if(prev <= root.data) { prev = root.data; } else { return false; } boolean check2 = inOrder(root.right); return check1 && check2; } return true; } boolean isBST(Node root) { prev = Integer.MIN_VALUE; return inOrder(root); } } -1 shubham211019975 days ago class bst{ boolean isbst; int max; int min; } public bst isbst(Node root){ if(root==null){ bst bp= new bst(); bp.isbst=true; bp.min=Integer.MAX_VALUE; bp.max=Integer.MIN_VALUE; return bp; } bst lp=isbst(root.left); bst rp=isbst(root.right); bst mp=new bst(); mp.isbst=(root.data>=lp.max && root.data<=rp.min)&&lp.isbst && rp.isbst; mp.min=Math.min(root.data,Math.min(lp.min,rp.min)); mp.max=Math.max(root.data,Math.max(lp.max,rp.max)); return mp; } boolean isBST(Node root) { bst res=isbst(root); return res.isbst; } 0 kkumarakash70111 week ago bool bst(Node*root,int min,int max) { if(root==NULL) return true; if(root->data<min || root->data>max) return false; return bst(root->left,min,root->data)&&bst(root->right,root->data,max); } bool isBST(Node* root) { // Your code here return bst(root,INT_MIN,INT_MAX); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 402, "s": 238, "text": "Given the root of a binary tree. Check whether it is a BST or not.\nNote: We are considering that BSTs can not contain duplicate Nodes.\nA BST is defined as follows:" }, { "code": null, "e": 487, "s": 402, "text": "\nThe left subtree of a node contains only nodes with keys less than the node's key.\n" }, { "code": null, "e": 576, "s": 487, "text": "\nThe right subtree of a node contains only nodes with keys greater than the node's key.\n" }, { "code": null, "e": 645, "s": 576, "text": "\nBoth the left and right subtrees must also be binary search trees.\n" }, { "code": null, "e": 658, "s": 647, "text": "Example 1:" }, { "code": null, "e": 916, "s": 658, "text": "Input:\n 2\n / \\\n1 3\nOutput: 1 \nExplanation: \nThe left subtree of root node contains node\nwith key lesser than the root nodes key and \nthe right subtree of root node contains node \nwith key greater than the root nodes key.\nHence, the tree is a BST.\n" }, { "code": null, "e": 927, "s": 916, "text": "Example 2:" }, { "code": null, "e": 1185, "s": 927, "text": "Input:\n 2\n \\\n 7\n \\\n 6\n \\\n 5\n \\\n 9\n \\\n 2\n \\\n 6\nOutput: 0 \nExplanation: \nSince the node with value 7 has right subtree \nnodes with keys less than 7, this is not a BST.\n" }, { "code": null, "e": 1409, "s": 1185, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isBST() which takes the root of the tree as a parameter and returns true if the given binary tree is BST, else returns false. " }, { "code": null, "e": 1489, "s": 1409, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the BST)." }, { "code": null, "e": 1533, "s": 1489, "text": "Constraints:\n0 <= Number of edges <= 100000" }, { "code": null, "e": 1535, "s": 1533, "text": "0" }, { "code": null, "e": 1547, "s": 1535, "text": "anikethjain" }, { "code": null, "e": 1573, "s": 1547, "text": "This comment was deleted." }, { "code": null, "e": 1575, "s": 1573, "text": "0" }, { "code": null, "e": 1599, "s": 1575, "text": "smohtashima15 hours ago" }, { "code": null, "e": 1654, "s": 1599, "text": "Simple Python Solution with Iterative DFS using STACK:" }, { "code": null, "e": 2127, "s": 1654, "text": "def isBST(self, root):\n #code here\n if not root:\n return True\n\n stack = [(root, -math.inf, math.inf)]\n while stack:\n root, lower, upper = stack.pop()\n if not root:\n continue\n val = root.data\n if val <= lower or val >= upper:\n return False\n stack.append((root.right, val, upper))\n stack.append((root.left, lower, val))\n return True" }, { "code": null, "e": 2130, "s": 2127, "text": "+1" }, { "code": null, "e": 2158, "s": 2130, "text": "shashwatsingh7116 hours ago" }, { "code": null, "e": 2188, "s": 2158, "text": "By Inorder Trav → Time - O(N)" }, { "code": null, "e": 2201, "s": 2188, "text": "Space - O(N)" }, { "code": null, "e": 2807, "s": 2203, "text": " bool isValidBST(TreeNode* root) { if(!root->left && !root->right ) return true; long prev=LONG_MIN; stack<TreeNode*> st; TreeNode* ptr=root; while(!st.empty() || ptr) { if(ptr) { st.push(ptr); ptr=ptr->left; } else { ptr=st.top(); st.pop(); if(prev >= ptr->val) return false; prev=ptr->val; ptr=ptr->right; } } return true; }" }, { "code": null, "e": 2827, "s": 2809, "text": "By Morris Trav -→" }, { "code": null, "e": 2839, "s": 2827, "text": "Time = O(n)" }, { "code": null, "e": 2852, "s": 2839, "text": "Space = O(1)" }, { "code": null, "e": 3680, "s": 2854, "text": " bool isBST(Node* root) { Node* ptr=root; int prev=0; while(ptr) { if(!ptr->left) { if(prev>ptr->data) return false; prev=ptr->data; ptr=ptr->right; } else { Node* temp = ptr->left; while(temp->right && temp->right!=ptr) temp=temp->right; if(!temp->right) { temp->right=ptr; ptr=ptr->left; } else { temp->right=NULL; if(prev>ptr->data) return false; prev=ptr->data; ptr=ptr->right; } } } return true; }" }, { "code": null, "e": 3683, "s": 3680, "text": "+1" }, { "code": null, "e": 3707, "s": 3683, "text": "sudhirdaga19981 day ago" }, { "code": null, "e": 4083, "s": 3707, "text": "bool isValidBST(Node *root,int mini,int maxi) { if(root==NULL) return true; if(root->data > maxi || root->data < mini) return false; return (isValidBST(root->left,mini,root->data) && isValidBST(root->right,root->data,maxi)); } bool isBST(Node* root) { // Your code here return isValidBST(root,INT_MIN,INT_MAX); }" }, { "code": null, "e": 4085, "s": 4083, "text": "0" }, { "code": null, "e": 4109, "s": 4085, "text": "siddhantmedar2 days ago" }, { "code": null, "e": 4545, "s": 4109, "text": " #Function to check whether a Binary Tree is BST or not. def isBST(self, root): #code here def util(root, mn, mx): if not root: return True if root.data < mn or root.data > mx: return False return util(root.left, mn, root.data-1) and util(root.right, root.data+1 ,mx) return util(root, float(\"-inf\"), float(\"inf\")) " }, { "code": null, "e": 4547, "s": 4545, "text": "0" }, { "code": null, "e": 4571, "s": 4547, "text": "neeshumaini554 days ago" }, { "code": null, "e": 5091, "s": 4571, "text": "\t#intition\n #for every node we will define the range of values that \t\t satify the condition\n #condition -- a < root.val < b\n #a -- min_value\n #b -- max_value\n def bst(self,root,int_min,int_max):\n if root is None:\n return True\n if root.data < int_min or root.data > int_max:\n return False\n return self.bst(root.left,int_min,root.data) and self.bst(root.right,root.data,int_max)\n def isBST(self, root):\n return self.bst(root,float('-inf'),float('inf'))" }, { "code": null, "e": 5094, "s": 5091, "text": "+1" }, { "code": null, "e": 5120, "s": 5094, "text": "anshrathore69844 days ago" }, { "code": null, "e": 5740, "s": 5120, "text": "bool isBST(Node* node) { if(node ==NULL) return 1; if(node->left!=NULL && maxValue(node->left,node->data)) return 0; if(node->right!=NULL && minValue(node->right,node->data)) return 0; if (!isBST(node->left) || !isBST(node->right)) return 0; return 1; } bool maxValue(Node* node,int i) { if(node->data > i) return 1; else return 0; } bool minValue(Node* node , int i) { if(node->data < i) return 1; else return 0; }" }, { "code": null, "e": 5763, "s": 5742, "text": "101 test case passed" }, { "code": null, "e": 5767, "s": 5765, "text": "0" }, { "code": null, "e": 5792, "s": 5767, "text": "debojyotisinha5 days ago" }, { "code": null, "e": 5819, "s": 5792, "text": "Programming Language: Java" }, { "code": null, "e": 5848, "s": 5819, "text": "Test Cases Passed: 120 / 120" }, { "code": null, "e": 5876, "s": 5848, "text": "Total Time Taken: 0.39/1.13" }, { "code": null, "e": 6439, "s": 5878, "text": "public class Solution {\n int prev;\n\n boolean inOrder(Node root) {\n if (root != null) {\n boolean check1 = inOrder(root.left);\n \n if(prev <= root.data) {\n prev = root.data;\n } else {\n return false;\n }\n\n boolean check2 = inOrder(root.right);\n \n return check1 && check2;\n }\n \n return true;\n }\n \n boolean isBST(Node root) {\n prev = Integer.MIN_VALUE;\n \n return inOrder(root);\n }\n}" }, { "code": null, "e": 6442, "s": 6439, "text": "-1" }, { "code": null, "e": 6468, "s": 6442, "text": "shubham211019975 days ago" }, { "code": null, "e": 7177, "s": 6468, "text": "class bst{\n boolean isbst;\n int max;\n int min;\n }\n public bst isbst(Node root){\n if(root==null){\n bst bp= new bst();\n bp.isbst=true;\n bp.min=Integer.MAX_VALUE;\n bp.max=Integer.MIN_VALUE;\n return bp;\n }\n bst lp=isbst(root.left);\n bst rp=isbst(root.right);\n \n bst mp=new bst();\n mp.isbst=(root.data>=lp.max && root.data<=rp.min)&&lp.isbst && rp.isbst;\n \n mp.min=Math.min(root.data,Math.min(lp.min,rp.min));\n mp.max=Math.max(root.data,Math.max(lp.max,rp.max));\n return mp;\n }\n \n boolean isBST(Node root)\n {\n bst res=isbst(root);\n return res.isbst;\n }" }, { "code": null, "e": 7179, "s": 7177, "text": "0" }, { "code": null, "e": 7205, "s": 7179, "text": "kkumarakash70111 week ago" }, { "code": null, "e": 7543, "s": 7205, "text": " bool bst(Node*root,int min,int max) { if(root==NULL) return true; if(root->data<min || root->data>max) return false; return bst(root->left,min,root->data)&&bst(root->right,root->data,max); } bool isBST(Node* root) { // Your code here return bst(root,INT_MIN,INT_MAX); }" }, { "code": null, "e": 7689, "s": 7543, "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": 7725, "s": 7689, "text": " Login to access your submissions. " }, { "code": null, "e": 7735, "s": 7725, "text": "\nProblem\n" }, { "code": null, "e": 7745, "s": 7735, "text": "\nContest\n" }, { "code": null, "e": 7808, "s": 7745, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7956, "s": 7808, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8164, "s": 7956, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8270, "s": 8164, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Taking Input from User in R Programming - GeeksforGeeks
07 Jul, 2021 Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. Like other programming languages in R it’s also possible to take input from the user. For doing so, there are two methods in R. Using readline() method Using scan() method In R language readline() method takes input in string format. If one inputs an integer then it is inputted as a string, lets say, one wants to input 255, then it will input as “255”, like a string. So one needs to convert that inputted value to the format that he needs. In this case, string “255” is converted to integer 255. To convert the inputted value to the desired data type, there are some functions in R, as.integer(n); —> convert to integer as.numeric(n); —> convert to numeric type (float, double etc) as.complex(n); —> convert to complex number (i.e 3+2i) as.Date(n) —> convert to date ..., etc Syntax: var = readline(); var = as.integer(var);Note that one can use “<-“ instead of “=” Example: R # R program to illustrate# taking input from the user # taking input using readline()# this command will prompt you# to input a desired valuevar = readline(); # convert the inputted value to integervar = as.integer(var); # print the valueprint(var) Output: 255 [1] 255 One can also show message in the console window to tell the user, what to input in the program. To do this one must use a argument named prompt inside the readline() function. Actually prompt argument facilitates other functions to constructing of files documenting. But prompt is not mandatory to use all the time. Syntax: var1 = readline(prompt = “Enter any number : “); or, var1 = readline(“Enter any number : “); Example: R # R program to illustrate# taking input from the user # taking input with showing the messagevar = readline(prompt = "Enter any number : "); # convert the inputted value to an integervar = as.integer(var); # print the valueprint(var) Output: Enter any number : 255 [1] 255 Taking multiple inputs in R language is same as taking single input, just need to define multiple readline() for inputs. One can use braces for define multiple readline() inside it. Syntax: var1 = readline(“Enter 1st number : “); var2 = readline(“Enter 2nd number : “); var3 = readline(“Enter 3rd number : “); var4 = readline(“Enter 4th number : “);or,{ var1 = readline(“Enter 1st number : “); var2 = readline(“Enter 2nd number : “); var3 = readline(“Enter 3rd number : “); var4 = readline(“Enter 4th number : “); } Example: R # R program to illustrate# taking input from the user # taking multiple inputs# using braces{ var1 = readline("Enter 1st number : "); var2 = readline("Enter 2nd number : "); var3 = readline("Enter 3rd number : "); var4 = readline("Enter 4th number : ");} # converting each valuevar1 = as.integer(var1);var2 = as.integer(var2);var3 = as.integer(var3);var4 = as.integer(var4); # print the sum of the 4 numberprint(var1 + var2 + var3 + var4) Output: Enter 1st number : 12 Enter 2nd number : 13 Enter 3rd number : 14 Enter 4th number : 15 [1] 54 To take string input is the same as an integer. For “String” one doesn’t need to convert the inputted data into a string because R takes input as string always. And for “character”, it needs to be converted to ‘character’. Sometimes it may not cause any error. One can take character input as same as string also, but that inputted data is of type string for the entire program. So the best way to use that inputted data as ‘character’ is to convert the data to a character. Syntax:string: var1 = readline(prompt = “Enter your name : “);character: var1 = readline(prompt = “Enter any character : “); var1 = as.character(var1) Example: R # R program to illustrate# taking input from the user # string inputvar1 = readline(prompt = "Enter your name : "); # character inputvar2 = readline(prompt = "Enter any character : ");# convert to charactervar2 = as.character(var2) # printing valuesprint(var1)print(var2) Output: Enter your name : GeeksforGeeks Enter any character : G [1] "GeeksforGeeks" [1] "G" Another way to take user input in R language is using a method, called scan() method. This method takes input from the console. This method is a very handy method while inputs are needed to taken quickly for any mathematical calculation or for any dataset. This method reads data in the form of a vector or list. This method also uses to reads input from a file also. Syntax: x = scan()scan() method is taking input continuously, to terminate the input process, need to press Enter key 2 times on the console. Example: This is simple method to take input using scan() method, where some integer number is taking as input and print those values in the next line on the console. R # R program to illustrate# taking input from the user # taking input using scan()x = scan()# print the inputted valuesprint(x) Output: 1: 1 2 3 4 5 6 7: 7 8 9 4 5 6 13: Read 12 items [1] 1 2 3 4 5 6 7 8 9 4 5 6 Explanation: Total 12 integers are taking as input in 2 lines when the control goes to 3rd line then by pressing Enter key 2 times the input process will be terminated. To take double, string, character types inputs, specify the type of the inputted value in the scan() method. To do this there is an argument called what, by which one can specify the data type of the inputted value. Syntax: x = scan(what = double()) —-for double x = scan(what = ” “) —-for string x = scan(what = character()) —-for character Example: R # R program to illustrate# taking input from the user # double input using scan()d = scan(what = double()) # string input using 'scan()'s = scan(what = " ") # character input using 'scan()'c = scan(what = character()) # print the inputted valuesprint(d) # doubleprint(s) # stringprint(c) # character Output: 1: 123.321 523.458 632.147 4: 741.25 855.36 6: Read 5 items 1: geeksfor geeks gfg 4: c++ R java python 8: Read 7 items 1: g e e k s f o 8: r g e e k s 14: Read 13 items [1] 123.321 523.458 632.147 741.250 855.360 [1] "geeksfor" "geeks" "gfg" "c++" "R" "java" "python" [1] "g" "e" "e" "k" "s" "f" "o" "r" "g" "e" "e" "k" "s" Explanation: Here, count of double items is 5, count of sorting items is 7, count of character items is 13. To read file using scan() method is same as normal console input, only thing is that, one needs to pass the file name and data type to the scan() method. Syntax: x = scan(“fileDouble.txt”, what = double()) —-for double x = scan(“fileString.txt”, what = ” “) —-for string x = scan(“fileChar.txt”, what = character()) —-for character Example: R # R program to illustrate# taking input from the user # string file input using scan()s = scan("fileString.txt", what = " ") # double file input using scan()d = scan("fileDouble.txt", what = double()) # character file input using scan()c = scan("fileChar.txt", what = character()) # print the inputted valuesprint(s) # stringprint(d) # doubleprint(c) # character Output: Read 7 items Read 5 items Read 13 items [1] "geek" "for" "geeks" "gfg" "c++" "java" "python" [1] 123.321 523.458 632.147 741.250 855.360 [1] "g" "e" "e" "k" "s" "f" "o" "r" "g" "e" "e" "k" "s" Save the data file in the same location where the program is saved for better access. Otherwise total path of the file need to defined inside the scan() method. surindertarika1234 Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30289, "s": 30261, "text": "\n07 Jul, 2021" }, { "code": null, "e": 30622, "s": 30289, "text": "Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. Like other programming languages in R it’s also possible to take input from the user. For doing so, there are two methods in R. " }, { "code": null, "e": 30646, "s": 30622, "text": "Using readline() method" }, { "code": null, "e": 30666, "s": 30646, "text": "Using scan() method" }, { "code": null, "e": 31084, "s": 30668, "text": "In R language readline() method takes input in string format. If one inputs an integer then it is inputted as a string, lets say, one wants to input 255, then it will input as “255”, like a string. So one needs to convert that inputted value to the format that he needs. In this case, string “255” is converted to integer 255. To convert the inputted value to the desired data type, there are some functions in R, " }, { "code": null, "e": 31121, "s": 31084, "text": "as.integer(n); —> convert to integer" }, { "code": null, "e": 31183, "s": 31121, "text": "as.numeric(n); —> convert to numeric type (float, double etc)" }, { "code": null, "e": 31238, "s": 31183, "text": "as.complex(n); —> convert to complex number (i.e 3+2i)" }, { "code": null, "e": 31277, "s": 31238, "text": "as.Date(n) —> convert to date ..., etc" }, { "code": null, "e": 31371, "s": 31279, "text": "Syntax: var = readline(); var = as.integer(var);Note that one can use “<-“ instead of “=” " }, { "code": null, "e": 31382, "s": 31371, "text": "Example: " }, { "code": null, "e": 31384, "s": 31382, "text": "R" }, { "code": "# R program to illustrate# taking input from the user # taking input using readline()# this command will prompt you# to input a desired valuevar = readline(); # convert the inputted value to integervar = as.integer(var); # print the valueprint(var)", "e": 31633, "s": 31384, "text": null }, { "code": null, "e": 31643, "s": 31633, "text": "Output: " }, { "code": null, "e": 31655, "s": 31643, "text": "255\n[1] 255" }, { "code": null, "e": 31974, "s": 31657, "text": "One can also show message in the console window to tell the user, what to input in the program. To do this one must use a argument named prompt inside the readline() function. Actually prompt argument facilitates other functions to constructing of files documenting. But prompt is not mandatory to use all the time. " }, { "code": null, "e": 32075, "s": 31974, "text": "Syntax: var1 = readline(prompt = “Enter any number : “); or, var1 = readline(“Enter any number : “);" }, { "code": null, "e": 32086, "s": 32075, "text": "Example: " }, { "code": null, "e": 32088, "s": 32086, "text": "R" }, { "code": "# R program to illustrate# taking input from the user # taking input with showing the messagevar = readline(prompt = \"Enter any number : \"); # convert the inputted value to an integervar = as.integer(var); # print the valueprint(var)", "e": 32322, "s": 32088, "text": null }, { "code": null, "e": 32332, "s": 32322, "text": "Output: " }, { "code": null, "e": 32363, "s": 32332, "text": "Enter any number : 255\n[1] 255" }, { "code": null, "e": 32548, "s": 32365, "text": "Taking multiple inputs in R language is same as taking single input, just need to define multiple readline() for inputs. One can use braces for define multiple readline() inside it. " }, { "code": null, "e": 32882, "s": 32548, "text": "Syntax: var1 = readline(“Enter 1st number : “); var2 = readline(“Enter 2nd number : “); var3 = readline(“Enter 3rd number : “); var4 = readline(“Enter 4th number : “);or,{ var1 = readline(“Enter 1st number : “); var2 = readline(“Enter 2nd number : “); var3 = readline(“Enter 3rd number : “); var4 = readline(“Enter 4th number : “); }" }, { "code": null, "e": 32893, "s": 32882, "text": "Example: " }, { "code": null, "e": 32895, "s": 32893, "text": "R" }, { "code": "# R program to illustrate# taking input from the user # taking multiple inputs# using braces{ var1 = readline(\"Enter 1st number : \"); var2 = readline(\"Enter 2nd number : \"); var3 = readline(\"Enter 3rd number : \"); var4 = readline(\"Enter 4th number : \");} # converting each valuevar1 = as.integer(var1);var2 = as.integer(var2);var3 = as.integer(var3);var4 = as.integer(var4); # print the sum of the 4 numberprint(var1 + var2 + var3 + var4)", "e": 33346, "s": 32895, "text": null }, { "code": null, "e": 33356, "s": 33346, "text": "Output: " }, { "code": null, "e": 33451, "s": 33356, "text": "Enter 1st number : 12\nEnter 2nd number : 13\nEnter 3rd number : 14\nEnter 4th number : 15\n[1] 54" }, { "code": null, "e": 33930, "s": 33455, "text": "To take string input is the same as an integer. For “String” one doesn’t need to convert the inputted data into a string because R takes input as string always. And for “character”, it needs to be converted to ‘character’. Sometimes it may not cause any error. One can take character input as same as string also, but that inputted data is of type string for the entire program. So the best way to use that inputted data as ‘character’ is to convert the data to a character." }, { "code": null, "e": 34083, "s": 33932, "text": "Syntax:string: var1 = readline(prompt = “Enter your name : “);character: var1 = readline(prompt = “Enter any character : “); var1 = as.character(var1)" }, { "code": null, "e": 34094, "s": 34083, "text": "Example: " }, { "code": null, "e": 34096, "s": 34094, "text": "R" }, { "code": "# R program to illustrate# taking input from the user # string inputvar1 = readline(prompt = \"Enter your name : \"); # character inputvar2 = readline(prompt = \"Enter any character : \");# convert to charactervar2 = as.character(var2) # printing valuesprint(var1)print(var2)", "e": 34368, "s": 34096, "text": null }, { "code": null, "e": 34378, "s": 34368, "text": "Output: " }, { "code": null, "e": 34462, "s": 34378, "text": "Enter your name : GeeksforGeeks\nEnter any character : G\n[1] \"GeeksforGeeks\"\n[1] \"G\"" }, { "code": null, "e": 34834, "s": 34464, "text": "Another way to take user input in R language is using a method, called scan() method. This method takes input from the console. This method is a very handy method while inputs are needed to taken quickly for any mathematical calculation or for any dataset. This method reads data in the form of a vector or list. This method also uses to reads input from a file also. " }, { "code": null, "e": 34976, "s": 34834, "text": "Syntax: x = scan()scan() method is taking input continuously, to terminate the input process, need to press Enter key 2 times on the console." }, { "code": null, "e": 35145, "s": 34976, "text": "Example: This is simple method to take input using scan() method, where some integer number is taking as input and print those values in the next line on the console. " }, { "code": null, "e": 35147, "s": 35145, "text": "R" }, { "code": "# R program to illustrate# taking input from the user # taking input using scan()x = scan()# print the inputted valuesprint(x)", "e": 35274, "s": 35147, "text": null }, { "code": null, "e": 35284, "s": 35274, "text": "Output: " }, { "code": null, "e": 35362, "s": 35284, "text": "1: 1 2 3 4 5 6\n7: 7 8 9 4 5 6\n13: \nRead 12 items\n [1] 1 2 3 4 5 6 7 8 9 4 5 6" }, { "code": null, "e": 35532, "s": 35362, "text": "Explanation: Total 12 integers are taking as input in 2 lines when the control goes to 3rd line then by pressing Enter key 2 times the input process will be terminated. " }, { "code": null, "e": 35749, "s": 35532, "text": "To take double, string, character types inputs, specify the type of the inputted value in the scan() method. To do this there is an argument called what, by which one can specify the data type of the inputted value. " }, { "code": null, "e": 35876, "s": 35749, "text": "Syntax: x = scan(what = double()) —-for double x = scan(what = ” “) —-for string x = scan(what = character()) —-for character " }, { "code": null, "e": 35887, "s": 35876, "text": "Example: " }, { "code": null, "e": 35889, "s": 35887, "text": "R" }, { "code": "# R program to illustrate# taking input from the user # double input using scan()d = scan(what = double()) # string input using 'scan()'s = scan(what = \" \") # character input using 'scan()'c = scan(what = character()) # print the inputted valuesprint(d) # doubleprint(s) # stringprint(c) # character", "e": 36189, "s": 35889, "text": null }, { "code": null, "e": 36199, "s": 36189, "text": "Output: " }, { "code": null, "e": 36552, "s": 36199, "text": "1: 123.321 523.458 632.147\n4: 741.25 855.36\n6: \nRead 5 items\n1: geeksfor geeks gfg\n4: c++ R java python\n8: \nRead 7 items\n1: g e e k s f o\n8: r g e e k s\n14: \nRead 13 items\n[1] 123.321 523.458 632.147 741.250 855.360\n[1] \"geeksfor\" \"geeks\" \"gfg\" \"c++\" \"R\" \"java\" \"python\" \n[1] \"g\" \"e\" \"e\" \"k\" \"s\" \"f\" \"o\" \"r\" \"g\" \"e\" \"e\" \"k\" \"s\"" }, { "code": null, "e": 36661, "s": 36552, "text": "Explanation: Here, count of double items is 5, count of sorting items is 7, count of character items is 13. " }, { "code": null, "e": 36816, "s": 36661, "text": "To read file using scan() method is same as normal console input, only thing is that, one needs to pass the file name and data type to the scan() method. " }, { "code": null, "e": 36994, "s": 36816, "text": "Syntax: x = scan(“fileDouble.txt”, what = double()) —-for double x = scan(“fileString.txt”, what = ” “) —-for string x = scan(“fileChar.txt”, what = character()) —-for character" }, { "code": null, "e": 37005, "s": 36994, "text": "Example: " }, { "code": null, "e": 37007, "s": 37005, "text": "R" }, { "code": "# R program to illustrate# taking input from the user # string file input using scan()s = scan(\"fileString.txt\", what = \" \") # double file input using scan()d = scan(\"fileDouble.txt\", what = double()) # character file input using scan()c = scan(\"fileChar.txt\", what = character()) # print the inputted valuesprint(s) # stringprint(d) # doubleprint(c) # character", "e": 37370, "s": 37007, "text": null }, { "code": null, "e": 37380, "s": 37370, "text": "Output: " }, { "code": null, "e": 37587, "s": 37380, "text": "Read 7 items\nRead 5 items\nRead 13 items\n[1] \"geek\" \"for\" \"geeks\" \"gfg\" \"c++\" \"java\" \"python\"\n[1] 123.321 523.458 632.147 741.250 855.360\n[1] \"g\" \"e\" \"e\" \"k\" \"s\" \"f\" \"o\" \"r\" \"g\" \"e\" \"e\" \"k\" \"s\"" }, { "code": null, "e": 37749, "s": 37587, "text": "Save the data file in the same location where the program is saved for better access. Otherwise total path of the file need to defined inside the scan() method. " }, { "code": null, "e": 37768, "s": 37749, "text": "surindertarika1234" }, { "code": null, "e": 37775, "s": 37768, "text": "Picked" }, { "code": null, "e": 37786, "s": 37775, "text": "R Language" }, { "code": null, "e": 37884, "s": 37786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37929, "s": 37884, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 37987, "s": 37929, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 38039, "s": 37987, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 38071, "s": 38039, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 38134, "s": 38071, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 38178, "s": 38134, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 38230, "s": 38178, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 38295, "s": 38230, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 38330, "s": 38295, "text": "Group by function in R using Dplyr" } ]
PHP echo and print - GeeksforGeeks
06 Dec, 2021 In this article, we will see what is echo & print statements in PHP, along with understanding their basic implementation through the examples. The echo is used to display the output of parameters that are passed to it. It displays the outputs of one or more strings separated by commas. The print accepts one argument at a time & cannot be used as a variable function in PHP. The print outputs only the strings. Note: Both are language constructs in PHP programs that are more or less the same as both are used to output data on the browser screen. The print statement is an alternative to echo. PHP echo statement: It is a language construct and never behaves like a function, hence no parenthesis is required. But the developer can use parenthesis if they want. The end of the echo statement is identified by the semi-colon (‘;’). It output one or more strings. We can use ‘echo‘ to output strings, numbers, variables, values, and results of expressions. Below is some usage of echo statements in PHP: Displaying Strings: We can simply use the keyword echo followed by the string to be displayed within quotes. The below example shows how to display strings with PHP. PHP <?php echo "Hello,This is a display string example!";?> Output: Hello,This is a display string example! Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement instead of a single string argument, separating them by comma (‘,’) operator. For example, if we have two strings i.e “Hello” and “World” then we can pass them as (“Hello”, “World”). PHP <?php echo "Multiple ","argument ","string!";?> Output: Multiple argument string! Displaying Variables: Displaying variables with echo statements is also as easy as displaying normal strings. The below example shows different ways to display variables with the help of a PHP echo statement. PHP <?php // Defining the variables $text = "Hello, World!"; $num1 = 10; $num2 = 20; // Echoing the variables echo $text."\n"; echo $num1."+".$num2."="; echo $num1 + $num2;?> Output: Hello, World! 10+20=30 The (.) operator in the above code can be used to concatenate two strings in PHP and the “\n” is used for a new line and is also known as line-break. We will learn about these in further articles. PHP print statement: The PHP print statement is similar to the echo statement and can be used alternative to echo many times. It is also a language construct, and so we may not use parenthesis i.e print or print(). The main difference between the print and echo statement is that echo does not behave like a function whereas print behaves like a function. The print statement can have only one argument at a time and thus can print a single string. Also, the print statement always returns a value of 1. Like an echo, the print statement can also be used to print strings and variables. Below are some examples of using print statements in PHP: Displaying String of Text: We can display strings with the print statement in the same way we did with echo statements. The only difference is we cannot display multiple strings separated by comma(,) with a single print statement. The below example shows how to display strings with the help of a PHP print statement. PHP <?php print "Hello, world!";?> Output: Hello, world! Displaying Variables: Displaying variables with print statements is also the same as that of echo statements. The example below shows how to display variables with the help of a PHP print statement. PHP <?php // Defining the variables $text = "Hello, World!"; $num1 = 10; $num2 = 20; // Echoing the variables print $text."\n"; print $num1."+".$num2."="; print $num1 + $num2;?> Output: Hello, World! 10+20=30 Difference between echo and print statements in PHP: echo accepts a list of arguments (multiple arguments can be passed), separated by commas. print accepts only one argument at a time. It returns no value or returns void. It returns the value 1. It displays the outputs of one or more strings separated by commas. The print outputs only the strings. It is comparatively faster than the print statement. It is slower than an echo statement. References: http://php.net/manual/en/function.echo.php http://php.net/manual/en/function.print.php This article is contributed by Barun Gupta. 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. Vaishalia ManasChhabra2 geetanjali16 bhaskargeeksforgeeks PHP-basics PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 42163, "s": 42135, "text": "\n06 Dec, 2021" }, { "code": null, "e": 42575, "s": 42163, "text": "In this article, we will see what is echo & print statements in PHP, along with understanding their basic implementation through the examples. The echo is used to display the output of parameters that are passed to it. It displays the outputs of one or more strings separated by commas. The print accepts one argument at a time & cannot be used as a variable function in PHP. The print outputs only the strings." }, { "code": null, "e": 42759, "s": 42575, "text": "Note: Both are language constructs in PHP programs that are more or less the same as both are used to output data on the browser screen. The print statement is an alternative to echo." }, { "code": null, "e": 43169, "s": 42759, "text": "PHP echo statement: It is a language construct and never behaves like a function, hence no parenthesis is required. But the developer can use parenthesis if they want. The end of the echo statement is identified by the semi-colon (‘;’). It output one or more strings. We can use ‘echo‘ to output strings, numbers, variables, values, and results of expressions. Below is some usage of echo statements in PHP: " }, { "code": null, "e": 43335, "s": 43169, "text": "Displaying Strings: We can simply use the keyword echo followed by the string to be displayed within quotes. The below example shows how to display strings with PHP." }, { "code": null, "e": 43339, "s": 43335, "text": "PHP" }, { "code": "<?php echo \"Hello,This is a display string example!\";?>", "e": 43398, "s": 43339, "text": null }, { "code": null, "e": 43406, "s": 43398, "text": "Output:" }, { "code": null, "e": 43446, "s": 43406, "text": "Hello,This is a display string example!" }, { "code": null, "e": 43731, "s": 43446, "text": "Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement instead of a single string argument, separating them by comma (‘,’) operator. For example, if we have two strings i.e “Hello” and “World” then we can pass them as (“Hello”, “World”)." }, { "code": null, "e": 43735, "s": 43731, "text": "PHP" }, { "code": "<?php echo \"Multiple \",\"argument \",\"string!\";?>", "e": 43786, "s": 43735, "text": null }, { "code": null, "e": 43795, "s": 43786, "text": "Output: " }, { "code": null, "e": 43821, "s": 43795, "text": "Multiple argument string!" }, { "code": null, "e": 44030, "s": 43821, "text": "Displaying Variables: Displaying variables with echo statements is also as easy as displaying normal strings. The below example shows different ways to display variables with the help of a PHP echo statement." }, { "code": null, "e": 44034, "s": 44030, "text": "PHP" }, { "code": "<?php // Defining the variables $text = \"Hello, World!\"; $num1 = 10; $num2 = 20; // Echoing the variables echo $text.\"\\n\"; echo $num1.\"+\".$num2.\"=\"; echo $num1 + $num2;?>", "e": 44215, "s": 44034, "text": null }, { "code": null, "e": 44224, "s": 44215, "text": "Output: " }, { "code": null, "e": 44247, "s": 44224, "text": "Hello, World!\n10+20=30" }, { "code": null, "e": 44445, "s": 44247, "text": "The (.) operator in the above code can be used to concatenate two strings in PHP and the “\\n” is used for a new line and is also known as line-break. We will learn about these in further articles. " }, { "code": null, "e": 44661, "s": 44445, "text": "PHP print statement: The PHP print statement is similar to the echo statement and can be used alternative to echo many times. It is also a language construct, and so we may not use parenthesis i.e print or print(). " }, { "code": null, "e": 45092, "s": 44661, "text": "The main difference between the print and echo statement is that echo does not behave like a function whereas print behaves like a function. The print statement can have only one argument at a time and thus can print a single string. Also, the print statement always returns a value of 1. Like an echo, the print statement can also be used to print strings and variables. Below are some examples of using print statements in PHP: " }, { "code": null, "e": 45410, "s": 45092, "text": "Displaying String of Text: We can display strings with the print statement in the same way we did with echo statements. The only difference is we cannot display multiple strings separated by comma(,) with a single print statement. The below example shows how to display strings with the help of a PHP print statement." }, { "code": null, "e": 45414, "s": 45410, "text": "PHP" }, { "code": "<?php print \"Hello, world!\";?>", "e": 45448, "s": 45414, "text": null }, { "code": null, "e": 45457, "s": 45448, "text": "Output: " }, { "code": null, "e": 45471, "s": 45457, "text": "Hello, world!" }, { "code": null, "e": 45670, "s": 45471, "text": "Displaying Variables: Displaying variables with print statements is also the same as that of echo statements. The example below shows how to display variables with the help of a PHP print statement." }, { "code": null, "e": 45674, "s": 45670, "text": "PHP" }, { "code": "<?php // Defining the variables $text = \"Hello, World!\"; $num1 = 10; $num2 = 20; // Echoing the variables print $text.\"\\n\"; print $num1.\"+\".$num2.\"=\"; print $num1 + $num2;?>", "e": 45862, "s": 45674, "text": null }, { "code": null, "e": 45871, "s": 45862, "text": "Output: " }, { "code": null, "e": 45894, "s": 45871, "text": "Hello, World!\n10+20=30" }, { "code": null, "e": 45947, "s": 45894, "text": "Difference between echo and print statements in PHP:" }, { "code": null, "e": 46037, "s": 45947, "text": "echo accepts a list of arguments (multiple arguments can be passed), separated by commas." }, { "code": null, "e": 46080, "s": 46037, "text": "print accepts only one argument at a time." }, { "code": null, "e": 46118, "s": 46080, "text": "It returns no value or returns void. " }, { "code": null, "e": 46142, "s": 46118, "text": "It returns the value 1." }, { "code": null, "e": 46211, "s": 46142, "text": " It displays the outputs of one or more strings separated by commas." }, { "code": null, "e": 46247, "s": 46211, "text": "The print outputs only the strings." }, { "code": null, "e": 46300, "s": 46247, "text": "It is comparatively faster than the print statement." }, { "code": null, "e": 46337, "s": 46300, "text": "It is slower than an echo statement." }, { "code": null, "e": 46349, "s": 46337, "text": "References:" }, { "code": null, "e": 46392, "s": 46349, "text": "http://php.net/manual/en/function.echo.php" }, { "code": null, "e": 46436, "s": 46392, "text": "http://php.net/manual/en/function.print.php" }, { "code": null, "e": 46731, "s": 46436, "text": "This article is contributed by Barun Gupta. 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": 46856, "s": 46731, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 46866, "s": 46856, "text": "Vaishalia" }, { "code": null, "e": 46880, "s": 46866, "text": "ManasChhabra2" }, { "code": null, "e": 46893, "s": 46880, "text": "geetanjali16" }, { "code": null, "e": 46914, "s": 46893, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 46925, "s": 46914, "text": "PHP-basics" }, { "code": null, "e": 46929, "s": 46925, "text": "PHP" }, { "code": null, "e": 46946, "s": 46929, "text": "Web Technologies" }, { "code": null, "e": 46950, "s": 46946, "text": "PHP" }, { "code": null, "e": 47048, "s": 46950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47093, "s": 47048, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 47143, "s": 47093, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 47183, "s": 47143, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 47207, "s": 47183, "text": "PHP in_array() Function" }, { "code": null, "e": 47251, "s": 47207, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 47291, "s": 47251, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 47324, "s": 47291, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 47369, "s": 47324, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47412, "s": 47369, "text": "How to fetch data from an API in ReactJS ?" } ]
Flutter - Rotate Transition - GeeksforGeeks
21 Jan, 2022 In Flutter, the page_transition package is used to create beautiful page transitions. It provides a wide range of effects that can be used from moving from one route to another. It is very convenient to use. In this article, we will explore the same by building a simple application. To build a simple application depicting the use of page_transition package for a Rotate transition follow the below steps: Add page_transition to the dependencies in pubspec.yaml file Import the same dependency in the main.dart file Use a StatelessWidget to give a structure to the application Design the homepage Define the onGenerateRoute property in the MaterialApp widget to transition to from the home page Now, let’s look in the steps in detail: You can add the page_transition dependency to the pubspec.yaml file as follows: To import the dependency to your main.dart file use the following: import 'package:page_transition/page_transition.dart'; The StatelessWidget can be used to give a simple structure to the application that contains an appbar and a body for the content as shown below: Dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ),} A StatelessWidget can also be used to design the Homepage for the app. A button will also be added to the homepage which will have a transition action attached to it when pressed as shown below: Dart class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.greenAccent, appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text('Rotate Transition Button'), onPressed: () { Navigator.push( context, PageTransition( curve: Curves.bounceOut, type: PageTransitionType.rotate, alignment: Alignment.topCenter, child: SecondPage(), ), ); }, ), ], ), ), ); }} The onRouteSettings property is used to extract information from one page and send it to another page (or, route). We will assign the same property to the button action that we added in the homepage that will transition it to the second page as shown below: Dart onGenerateRoute: (settings) { switch (settings.name) { case '/second': return PageTransition( child: SecondPage( ), type: PageTransitionType.fade, settings: settings, ); Complete Source Code: Dart import 'package:flutter/material.dart';import 'package:page_transition/page_transition.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // root of application @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), onGenerateRoute: (settings) { switch (settings.name) { case '/second': return PageTransition( child: SecondPage( ), type: PageTransitionType.fade, settings: settings, ); break; default: return null; } }, ); }} /// Homepageclass MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.greenAccent, appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text('Rotate Transition Button'), onPressed: () { Navigator.push( context, PageTransition( curve: Curves.bounceOut, type: PageTransitionType.rotate, alignment: Alignment.topCenter, child: SecondPage(), ), ); }, ), ], ), ), ); }} //definition of second pageclass SecondPage extends StatelessWidget { final String title; /// constructor of the page const SecondPage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { final args = ModalRoute.of(context).settings.arguments; return Scaffold( appBar: AppBar( title: Text(args ?? "Page Transition Plugin"), ), body: Center( child: Text('Second Page'), ), ); }} Output: varshagumber28 simranarora5sos android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25261, "s": 25233, "text": "\n21 Jan, 2022" }, { "code": null, "e": 25545, "s": 25261, "text": "In Flutter, the page_transition package is used to create beautiful page transitions. It provides a wide range of effects that can be used from moving from one route to another. It is very convenient to use. In this article, we will explore the same by building a simple application." }, { "code": null, "e": 25668, "s": 25545, "text": "To build a simple application depicting the use of page_transition package for a Rotate transition follow the below steps:" }, { "code": null, "e": 25729, "s": 25668, "text": "Add page_transition to the dependencies in pubspec.yaml file" }, { "code": null, "e": 25778, "s": 25729, "text": "Import the same dependency in the main.dart file" }, { "code": null, "e": 25839, "s": 25778, "text": "Use a StatelessWidget to give a structure to the application" }, { "code": null, "e": 25859, "s": 25839, "text": "Design the homepage" }, { "code": null, "e": 25957, "s": 25859, "text": "Define the onGenerateRoute property in the MaterialApp widget to transition to from the home page" }, { "code": null, "e": 25997, "s": 25957, "text": "Now, let’s look in the steps in detail:" }, { "code": null, "e": 26077, "s": 25997, "text": "You can add the page_transition dependency to the pubspec.yaml file as follows:" }, { "code": null, "e": 26144, "s": 26077, "text": "To import the dependency to your main.dart file use the following:" }, { "code": null, "e": 26199, "s": 26144, "text": "import 'package:page_transition/page_transition.dart';" }, { "code": null, "e": 26344, "s": 26199, "text": "The StatelessWidget can be used to give a simple structure to the application that contains an appbar and a body for the content as shown below:" }, { "code": null, "e": 26349, "s": 26344, "text": "Dart" }, { "code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ),}", "e": 26596, "s": 26349, "text": null }, { "code": null, "e": 26791, "s": 26596, "text": "A StatelessWidget can also be used to design the Homepage for the app. A button will also be added to the homepage which will have a transition action attached to it when pressed as shown below:" }, { "code": null, "e": 26796, "s": 26791, "text": "Dart" }, { "code": "class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.greenAccent, appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text('Rotate Transition Button'), onPressed: () { Navigator.push( context, PageTransition( curve: Curves.bounceOut, type: PageTransitionType.rotate, alignment: Alignment.topCenter, child: SecondPage(), ), ); }, ), ], ), ), ); }}", "e": 27727, "s": 26796, "text": null }, { "code": null, "e": 27990, "s": 27732, "text": "The onRouteSettings property is used to extract information from one page and send it to another page (or, route). We will assign the same property to the button action that we added in the homepage that will transition it to the second page as shown below:" }, { "code": null, "e": 27997, "s": 27992, "text": "Dart" }, { "code": "onGenerateRoute: (settings) { switch (settings.name) { case '/second': return PageTransition( child: SecondPage( ), type: PageTransitionType.fade, settings: settings, );", "e": 28257, "s": 27997, "text": null }, { "code": null, "e": 28282, "s": 28260, "text": "Complete Source Code:" }, { "code": null, "e": 28289, "s": 28284, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:page_transition/page_transition.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // root of application @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'GeeksForGeeks', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), onGenerateRoute: (settings) { switch (settings.name) { case '/second': return PageTransition( child: SecondPage( ), type: PageTransitionType.fade, settings: settings, ); break; default: return null; } }, ); }} /// Homepageclass MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.greenAccent, appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text('Rotate Transition Button'), onPressed: () { Navigator.push( context, PageTransition( curve: Curves.bounceOut, type: PageTransitionType.rotate, alignment: Alignment.topCenter, child: SecondPage(), ), ); }, ), ], ), ), ); }} //definition of second pageclass SecondPage extends StatelessWidget { final String title; /// constructor of the page const SecondPage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { final args = ModalRoute.of(context).settings.arguments; return Scaffold( appBar: AppBar( title: Text(args ?? \"Page Transition Plugin\"), ), body: Center( child: Text('Second Page'), ), ); }}", "e": 30469, "s": 28289, "text": null }, { "code": null, "e": 30477, "s": 30469, "text": "Output:" }, { "code": null, "e": 30492, "s": 30477, "text": "varshagumber28" }, { "code": null, "e": 30508, "s": 30492, "text": "simranarora5sos" }, { "code": null, "e": 30516, "s": 30508, "text": "android" }, { "code": null, "e": 30524, "s": 30516, "text": "Flutter" }, { "code": null, "e": 30529, "s": 30524, "text": "Dart" }, { "code": null, "e": 30537, "s": 30529, "text": "Flutter" }, { "code": null, "e": 30635, "s": 30537, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30674, "s": 30635, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30700, "s": 30674, "text": "ListView Class in Flutter" }, { "code": null, "e": 30726, "s": 30700, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 30749, "s": 30726, "text": "Flutter - Stack Widget" }, { "code": null, "e": 30767, "s": 30749, "text": "Flutter - Dialogs" }, { "code": null, "e": 30806, "s": 30767, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30823, "s": 30806, "text": "Flutter Tutorial" }, { "code": null, "e": 30849, "s": 30823, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 30872, "s": 30849, "text": "Flutter - Stack Widget" } ]
Program to find the Sum of each Row and each Column of a Matrix - GeeksforGeeks
13 May, 2021 Given a matrix of order m×n, the task is to find out the sum of each row and each column of a matrix. Examples: Input: array[4][4] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; Output: Sum of the 0 row is = 4 Sum of the 1 row is = 8 Sum of the 2 row is = 12 Sum of the 3 row is = 16 Sum of the 0 column is = 10 Sum of the 1 column is = 10 Sum of the 2 column is = 10 Sum of the 3 column is = 10 Approach: The sum of each row and each column can be calculated by traversing through the matrix and adding up the elements. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ program to find the sum// of each row and column of a matrix #include <iostream>using namespace std; // Get the size m and n#define m 4#define n 4 // Function to calculate sum of each rowvoid row_sum(int arr[m][n]){ int i,j,sum = 0; cout << "\nFinding Sum of each row:\n\n"; // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i][j]; } // Print the row sum cout << "Sum of the row " << i << " = " << sum << endl; // Reset the sum sum = 0; }} // Function to calculate sum of each columnvoid column_sum(int arr[m][n]){ int i,j,sum = 0; cout << "\nFinding Sum of each column:\n\n"; // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j][i]; } // Print the column sum cout << "Sum of the column " << i << " = " << sum << endl; // Reset the sum sum = 0; }} // Driver codeint main(){ int i,j; int arr[m][n]; // Get the matrix elements int x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i][j] = x++; // Get each row sum row_sum(arr); // Get each column sum column_sum(arr); return 0;} // Java program to find the sum// of each row and column of a matrix import java.io.*; class GFG { // Get the size m and n static int m = 4; static int n = 4; // Function to calculate sum of each row static void row_sum(int arr[][]) { int i, j, sum = 0; System.out.print("\nFinding Sum of each row:\n\n"); // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i][j]; } // Print the row sum System.out.println("Sum of the row " + i + " = " + sum); // Reset the sum sum = 0; } } // Function to calculate sum of each column static void column_sum(int arr[][]) { int i, j, sum = 0; System.out.print( "\nFinding Sum of each column:\n\n"); // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j][i]; } // Print the column sum System.out.println("Sum of the column " + i + " = " + sum); // Reset the sum sum = 0; } } // Driver code public static void main(String[] args) { int i, j; int[][] arr = new int[m][n]; // Get the matrix elements int x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i][j] = x++; // Get each row sum row_sum(arr); // Get each column sum column_sum(arr); }}// This code is contributed by inder_verma.. # Python3 program to find the sum# of each row and column of a matrix # import numpy library as np aliasimport numpy as np # Get the size m and nm , n = 4, 4 # Function to calculate sum of each rowdef row_sum(arr) : sum = 0 print("\nFinding Sum of each row:\n") # finding the row sum for i in range(m) : for j in range(n) : # Add the element sum += arr[i][j] # Print the row sum print("Sum of the row",i,"=",sum) # Reset the sum sum = 0 # Function to calculate sum of each columndef column_sum(arr) : sum = 0 print("\nFinding Sum of each column:\n") # finding the column sum for i in range(m) : for j in range(n) : # Add the element sum += arr[j][i] # Print the column sum print("Sum of the column",i,"=",sum) # Reset the sum sum = 0 # Driver code if __name__ == "__main__" : arr = np.zeros((4, 4)) # Get the matrix elements x = 1 for i in range(m) : for j in range(n) : arr[i][j] = x x += 1 # Get each row sum row_sum(arr) # Get each column sum column_sum(arr) # This code is contributed by# ANKITRAI1 // C# program to find the sum// of each row and column of a matrixusing System; class GFG { // Get the size m and n static int m = 4; static int n = 4; // Function to calculate sum of each row static void row_sum(int[, ] arr) { int i, j, sum = 0; Console.Write("\nFinding Sum of each row:\n\n"); // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i, j]; } // Print the row sum Console.WriteLine("Sum of the row " + i + " = " + sum); // Reset the sum sum = 0; } } // Function to calculate sum // of each column static void column_sum(int[, ] arr) { int i, j, sum = 0; Console.Write("\nFinding Sum of each" + " column:\n\n"); // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j, i]; } // Print the column sum Console.WriteLine("Sum of the column " + i + " = " + sum); // Reset the sum sum = 0; } } // Driver code public static void Main() { int i, j; int[, ] arr = new int[m, n]; // Get the matrix elements int x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i, j] = x++; // Get each row sum row_sum(arr); // Get each column sum column_sum(arr); }} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find the sum// of each row and column of a matrix // Get the size m and n$m = 4;$n = 4; // Function to calculate sum of each rowfunction row_sum(&$arr){ $sum = 0; echo "Finding Sum of each row:\n\n"; // finding the row sum for ($i = 0; $i < m; ++$i) { for ($j = 0; $j < n; ++$j) { // Add the element $sum = $sum + $arr[$i][$j]; } // Print the row sum echo "Sum of the row " . $i . " = " . $sum . "\n"; // Reset the sum $sum = 0; }} // Function to calculate sum of each columnfunction column_sum(&$arr){ $sum = 0; echo "\nFinding Sum of each column:\n\n"; // finding the column sum for ($i = 0; $i < m; ++$i) { for ($j = 0; $j < n; ++$j) { // Add the element $sum = $sum + $arr[$j][$i]; } // Print the column sum echo "Sum of the column " . $i . " = " . $sum . "\n"; // Reset the sum $sum = 0; }} // Driver code$arr = array_fill(0, $m, array_fill(0, $n, NULL)); // Get the matrix elements$x = 1;for ($i = 0; $i < $m; $i++) for ($j = 0; $j < $n; $j++) $arr[$i][$j] = $x++; // Get each row sumrow_sum($arr); // Get each column sumcolumn_sum($arr); // This code is contributed by ita_c?> <script>// Get the size m and nvar m= 4;var n= 4; // Function to calculate sum of each rowfunction row_sum( arr){ var i,j,sum = 0; document.write("<br>"+ "\nFinding Sum of each row:"+"<br>"); // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i][j]; } // Print the row sum document.write( "Sum of the row " + i + " = " + sum +"<br>"); // Reset the sum sum = 0; }} // Function to calculate sum of each columnfunction column_sum(arr){ var i,j,sum = 0; document.write( "<br>"+"Finding Sum of each column:"+"<br>"); // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j][i]; } // Print the column sum document.write( "Sum of the column " + i +" = " + sum +"<br>"); // Reset the sum sum = 0; }} var i,j; var arr=new Array(m).fill(0); for(var k=0;k<m;k++) { arr[k]=new Array(n).fill(0); } // Get the matrix elements var x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i][j]= x++; // Get each row sum row_sum(arr);//document.write(arr[0][0]); // Get each column sum column_sum(arr); </script> Finding Sum of each row: Sum of the row 0 = 10 Sum of the row 1 = 26 Sum of the row 2 = 42 Sum of the row 3 = 58 Finding Sum of each column: Sum of the column 0 = 28 Sum of the column 1 = 32 Sum of the column 2 = 36 Sum of the column 3 = 40 inderDuMCA Akanksha_Rai ankthon ukasp le0 akshitsaxenaa09 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Count all possible paths from top left to bottom right of a mXn matrix Maximum size rectangle binary sub-matrix with all 1s Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26492, "s": 26464, "text": "\n13 May, 2021" }, { "code": null, "e": 26594, "s": 26492, "text": "Given a matrix of order m×n, the task is to find out the sum of each row and each column of a matrix." }, { "code": null, "e": 26605, "s": 26594, "text": "Examples: " }, { "code": null, "e": 27031, "s": 26605, "text": "Input: array[4][4] = { {1, 1, 1, 1}, \n {2, 2, 2, 2}, \n {3, 3, 3, 3}, \n {4, 4, 4, 4}};\nOutput: Sum of the 0 row is = 4\n Sum of the 1 row is = 8\n Sum of the 2 row is = 12\n Sum of the 3 row is = 16\n Sum of the 0 column is = 10\n Sum of the 1 column is = 10\n Sum of the 2 column is = 10\n Sum of the 3 column is = 10" }, { "code": null, "e": 27043, "s": 27031, "text": "Approach: " }, { "code": null, "e": 27158, "s": 27043, "text": "The sum of each row and each column can be calculated by traversing through the matrix and adding up the elements." }, { "code": null, "e": 27211, "s": 27158, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27215, "s": 27211, "text": "C++" }, { "code": null, "e": 27220, "s": 27215, "text": "Java" }, { "code": null, "e": 27229, "s": 27220, "text": "Python 3" }, { "code": null, "e": 27232, "s": 27229, "text": "C#" }, { "code": null, "e": 27236, "s": 27232, "text": "PHP" }, { "code": null, "e": 27247, "s": 27236, "text": "Javascript" }, { "code": "// C++ program to find the sum// of each row and column of a matrix #include <iostream>using namespace std; // Get the size m and n#define m 4#define n 4 // Function to calculate sum of each rowvoid row_sum(int arr[m][n]){ int i,j,sum = 0; cout << \"\\nFinding Sum of each row:\\n\\n\"; // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i][j]; } // Print the row sum cout << \"Sum of the row \" << i << \" = \" << sum << endl; // Reset the sum sum = 0; }} // Function to calculate sum of each columnvoid column_sum(int arr[m][n]){ int i,j,sum = 0; cout << \"\\nFinding Sum of each column:\\n\\n\"; // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j][i]; } // Print the column sum cout << \"Sum of the column \" << i << \" = \" << sum << endl; // Reset the sum sum = 0; }} // Driver codeint main(){ int i,j; int arr[m][n]; // Get the matrix elements int x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i][j] = x++; // Get each row sum row_sum(arr); // Get each column sum column_sum(arr); return 0;}", "e": 28652, "s": 27247, "text": null }, { "code": "// Java program to find the sum// of each row and column of a matrix import java.io.*; class GFG { // Get the size m and n static int m = 4; static int n = 4; // Function to calculate sum of each row static void row_sum(int arr[][]) { int i, j, sum = 0; System.out.print(\"\\nFinding Sum of each row:\\n\\n\"); // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i][j]; } // Print the row sum System.out.println(\"Sum of the row \" + i + \" = \" + sum); // Reset the sum sum = 0; } } // Function to calculate sum of each column static void column_sum(int arr[][]) { int i, j, sum = 0; System.out.print( \"\\nFinding Sum of each column:\\n\\n\"); // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j][i]; } // Print the column sum System.out.println(\"Sum of the column \" + i + \" = \" + sum); // Reset the sum sum = 0; } } // Driver code public static void main(String[] args) { int i, j; int[][] arr = new int[m][n]; // Get the matrix elements int x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i][j] = x++; // Get each row sum row_sum(arr); // Get each column sum column_sum(arr); }}// This code is contributed by inder_verma..", "e": 30383, "s": 28652, "text": null }, { "code": "# Python3 program to find the sum# of each row and column of a matrix # import numpy library as np aliasimport numpy as np # Get the size m and nm , n = 4, 4 # Function to calculate sum of each rowdef row_sum(arr) : sum = 0 print(\"\\nFinding Sum of each row:\\n\") # finding the row sum for i in range(m) : for j in range(n) : # Add the element sum += arr[i][j] # Print the row sum print(\"Sum of the row\",i,\"=\",sum) # Reset the sum sum = 0 # Function to calculate sum of each columndef column_sum(arr) : sum = 0 print(\"\\nFinding Sum of each column:\\n\") # finding the column sum for i in range(m) : for j in range(n) : # Add the element sum += arr[j][i] # Print the column sum print(\"Sum of the column\",i,\"=\",sum) # Reset the sum sum = 0 # Driver code if __name__ == \"__main__\" : arr = np.zeros((4, 4)) # Get the matrix elements x = 1 for i in range(m) : for j in range(n) : arr[i][j] = x x += 1 # Get each row sum row_sum(arr) # Get each column sum column_sum(arr) # This code is contributed by# ANKITRAI1", "e": 31636, "s": 30383, "text": null }, { "code": "// C# program to find the sum// of each row and column of a matrixusing System; class GFG { // Get the size m and n static int m = 4; static int n = 4; // Function to calculate sum of each row static void row_sum(int[, ] arr) { int i, j, sum = 0; Console.Write(\"\\nFinding Sum of each row:\\n\\n\"); // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i, j]; } // Print the row sum Console.WriteLine(\"Sum of the row \" + i + \" = \" + sum); // Reset the sum sum = 0; } } // Function to calculate sum // of each column static void column_sum(int[, ] arr) { int i, j, sum = 0; Console.Write(\"\\nFinding Sum of each\" + \" column:\\n\\n\"); // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j, i]; } // Print the column sum Console.WriteLine(\"Sum of the column \" + i + \" = \" + sum); // Reset the sum sum = 0; } } // Driver code public static void Main() { int i, j; int[, ] arr = new int[m, n]; // Get the matrix elements int x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i, j] = x++; // Get each row sum row_sum(arr); // Get each column sum column_sum(arr); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 33370, "s": 31636, "text": null }, { "code": "<?php// PHP program to find the sum// of each row and column of a matrix // Get the size m and n$m = 4;$n = 4; // Function to calculate sum of each rowfunction row_sum(&$arr){ $sum = 0; echo \"Finding Sum of each row:\\n\\n\"; // finding the row sum for ($i = 0; $i < m; ++$i) { for ($j = 0; $j < n; ++$j) { // Add the element $sum = $sum + $arr[$i][$j]; } // Print the row sum echo \"Sum of the row \" . $i . \" = \" . $sum . \"\\n\"; // Reset the sum $sum = 0; }} // Function to calculate sum of each columnfunction column_sum(&$arr){ $sum = 0; echo \"\\nFinding Sum of each column:\\n\\n\"; // finding the column sum for ($i = 0; $i < m; ++$i) { for ($j = 0; $j < n; ++$j) { // Add the element $sum = $sum + $arr[$j][$i]; } // Print the column sum echo \"Sum of the column \" . $i . \" = \" . $sum . \"\\n\"; // Reset the sum $sum = 0; }} // Driver code$arr = array_fill(0, $m, array_fill(0, $n, NULL)); // Get the matrix elements$x = 1;for ($i = 0; $i < $m; $i++) for ($j = 0; $j < $n; $j++) $arr[$i][$j] = $x++; // Get each row sumrow_sum($arr); // Get each column sumcolumn_sum($arr); // This code is contributed by ita_c?>", "e": 34726, "s": 33370, "text": null }, { "code": "<script>// Get the size m and nvar m= 4;var n= 4; // Function to calculate sum of each rowfunction row_sum( arr){ var i,j,sum = 0; document.write(\"<br>\"+ \"\\nFinding Sum of each row:\"+\"<br>\"); // finding the row sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[i][j]; } // Print the row sum document.write( \"Sum of the row \" + i + \" = \" + sum +\"<br>\"); // Reset the sum sum = 0; }} // Function to calculate sum of each columnfunction column_sum(arr){ var i,j,sum = 0; document.write( \"<br>\"+\"Finding Sum of each column:\"+\"<br>\"); // finding the column sum for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { // Add the element sum = sum + arr[j][i]; } // Print the column sum document.write( \"Sum of the column \" + i +\" = \" + sum +\"<br>\"); // Reset the sum sum = 0; }} var i,j; var arr=new Array(m).fill(0); for(var k=0;k<m;k++) { arr[k]=new Array(n).fill(0); } // Get the matrix elements var x = 1; for (i = 0; i < m; i++) for (j = 0; j < n; j++) arr[i][j]= x++; // Get each row sum row_sum(arr);//document.write(arr[0][0]); // Get each column sum column_sum(arr); </script>", "e": 36124, "s": 34726, "text": null }, { "code": null, "e": 36368, "s": 36124, "text": "Finding Sum of each row:\n\nSum of the row 0 = 10\nSum of the row 1 = 26\nSum of the row 2 = 42\nSum of the row 3 = 58\n\nFinding Sum of each column:\n\nSum of the column 0 = 28\nSum of the column 1 = 32\nSum of the column 2 = 36\nSum of the column 3 = 40" }, { "code": null, "e": 36381, "s": 36370, "text": "inderDuMCA" }, { "code": null, "e": 36394, "s": 36381, "text": "Akanksha_Rai" }, { "code": null, "e": 36402, "s": 36394, "text": "ankthon" }, { "code": null, "e": 36408, "s": 36402, "text": "ukasp" }, { "code": null, "e": 36412, "s": 36408, "text": "le0" }, { "code": null, "e": 36428, "s": 36412, "text": "akshitsaxenaa09" }, { "code": null, "e": 36435, "s": 36428, "text": "Matrix" }, { "code": null, "e": 36454, "s": 36435, "text": "School Programming" }, { "code": null, "e": 36461, "s": 36454, "text": "Matrix" }, { "code": null, "e": 36559, "s": 36461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36602, "s": 36559, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 36673, "s": 36602, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 36726, "s": 36673, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 36777, "s": 36726, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 36798, "s": 36777, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 36816, "s": 36798, "text": "Python Dictionary" }, { "code": null, "e": 36832, "s": 36816, "text": "Arrays in C/C++" }, { "code": null, "e": 36851, "s": 36832, "text": "Inheritance in C++" }, { "code": null, "e": 36876, "s": 36851, "text": "Reverse a string in Java" } ]
How to convert a Stream into a Map in Java - GeeksforGeeks
21 Jun, 2020 Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. In this article, the methods to convert a stream into a map is discussed. Method 1: Using Collectors.toMap() Function The Collectors.toMap() method takes two parameters as the input: KeyMapper: This function is used for extracting keys of the Map from stream value.ValueMapper: This function used for extracting the values of the map for the given key. KeyMapper: This function is used for extracting keys of the Map from stream value. ValueMapper: This function used for extracting the values of the map for the given key. The following are the examples of the toMap function to convert the given stream into a map: Example 1: Here, we will convert a string into a Map with the keys as the words of the string and the value as the length of each word.// Program to convert// the Stream to Map import java.io.*;import java.util.stream.*;import java.util.Arrays;import java.util.Map; class GFG { // Function to convert the string // to the map public static Map toMap(String input) { Map<String, Integer> lengthMap = Arrays.stream(input.split(" ")) .collect(Collectors.toMap( value -> value, value -> value.length())); return lengthMap; } public static void main(String[] args) { String input = "Geeks for Geek"; System.out.println(toMap(input)); }}Output:{Geek=4, for=3, Geeks=5} In the above example, the toMap collector takes two lambda functions as parameters:(value -> value): It reads the current stream value and returns it as the key of the Map.(value -> value.length): It reads the current stream value, finds its length and returns the value to the Map for the given key. // Program to convert// the Stream to Map import java.io.*;import java.util.stream.*;import java.util.Arrays;import java.util.Map; class GFG { // Function to convert the string // to the map public static Map toMap(String input) { Map<String, Integer> lengthMap = Arrays.stream(input.split(" ")) .collect(Collectors.toMap( value -> value, value -> value.length())); return lengthMap; } public static void main(String[] args) { String input = "Geeks for Geek"; System.out.println(toMap(input)); }} {Geek=4, for=3, Geeks=5} In the above example, the toMap collector takes two lambda functions as parameters: (value -> value): It reads the current stream value and returns it as the key of the Map.(value -> value.length): It reads the current stream value, finds its length and returns the value to the Map for the given key. (value -> value): It reads the current stream value and returns it as the key of the Map. (value -> value.length): It reads the current stream value, finds its length and returns the value to the Map for the given key. Example 2: Now, lets use the toMap function to perform a bit more complex map conversion. Here, we will convert a list of users into a map where UserId is the key and the User is the value.// Program to convert User[] into// Map<userId, User> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the User classpublic class User { // Attributes of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getters of the user class public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString method // to return the custom string @Override public String toString() { return "User [userId = " + userId + ", name = " + name + ", city = " + city + "]"; }} class GFG { // Function to convert the User // to the map public static Map toMap(User user1, User user2, User user3) { Map<Integer, User> userMap = Arrays.asList(user1, user2, user3) .stream() .collect(Collectors.toMap( user -> user.getUserId(), user -> user)); return userMap; } // Driver code public static void main(String[] args) { // Creating users User user1 = new User(1, "User1", "Pune"); User user2 = new User(2, "User2", "Mumbai"); User user3 = new User(3, "User3", "Nagpur"); System.out.println(toMap(user1, user2, user3)); }}Output:{1=User [userId = 1, name = User1, city = Pune], 2=User [userId = 2, name = User2, city = Mumbai], 3=User [userId = 3, name = User3, city = Nagpur]} // Program to convert User[] into// Map<userId, User> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the User classpublic class User { // Attributes of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getters of the user class public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString method // to return the custom string @Override public String toString() { return "User [userId = " + userId + ", name = " + name + ", city = " + city + "]"; }} class GFG { // Function to convert the User // to the map public static Map toMap(User user1, User user2, User user3) { Map<Integer, User> userMap = Arrays.asList(user1, user2, user3) .stream() .collect(Collectors.toMap( user -> user.getUserId(), user -> user)); return userMap; } // Driver code public static void main(String[] args) { // Creating users User user1 = new User(1, "User1", "Pune"); User user2 = new User(2, "User2", "Mumbai"); User user3 = new User(3, "User3", "Nagpur"); System.out.println(toMap(user1, user2, user3)); }} {1=User [userId = 1, name = User1, city = Pune], 2=User [userId = 2, name = User2, city = Mumbai], 3=User [userId = 3, name = User3, city = Nagpur]} Method 2: Using Collectors The groupingBy collector takes one function as input and creates a group of stream objects using that function. The following are the examples to convert a stream into a map using groupingBy collector. Example 1: In this example, we will convert a user stream into a map whose key is the city and the value is the users living in that city.// Java program to convert the User[]// into Map<city, List<User>> import java.util.Arrays;import java.util.Map;import java.util.List;import java.util.stream.*; // Implementing the User classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor of the User class public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return "User [userId = " + userId + ", name = " + name + ", city = " + city + "]"; }} class GFG { // Function to convert the user // object to the map public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, List<User> > cityUserListMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect(Collectors.groupingBy( User::getCity)); return cityUserListMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, "User1", "Pune"); User user2 = new User(2, "User2", "Mumbai"); User user3 = new User(3, "User3", "Nagpur"); User user4 = new User(4, "User4", "Pune"); User user5 = new User(5, "User5", "Mumbai"); System.out.println(toMap(user1, user2, user3, user4, user5)); }}Output:{Nagpur=[User [userId = 3, name = User3, city = Nagpur]], Pune=[User [userId = 1, name = User1, city = Pune], User [userId = 4, name = User4, city = Pune]], Mumbai=[User [userId = 2, name = User2, city = Mumbai], User [userId = 5, name = User5, city = Mumbai]]} // Java program to convert the User[]// into Map<city, List<User>> import java.util.Arrays;import java.util.Map;import java.util.List;import java.util.stream.*; // Implementing the User classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor of the User class public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return "User [userId = " + userId + ", name = " + name + ", city = " + city + "]"; }} class GFG { // Function to convert the user // object to the map public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, List<User> > cityUserListMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect(Collectors.groupingBy( User::getCity)); return cityUserListMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, "User1", "Pune"); User user2 = new User(2, "User2", "Mumbai"); User user3 = new User(3, "User3", "Nagpur"); User user4 = new User(4, "User4", "Pune"); User user5 = new User(5, "User5", "Mumbai"); System.out.println(toMap(user1, user2, user3, user4, user5)); }} {Nagpur=[User [userId = 3, name = User3, city = Nagpur]], Pune=[User [userId = 1, name = User1, city = Pune], User [userId = 4, name = User4, city = Pune]], Mumbai=[User [userId = 2, name = User2, city = Mumbai], User [userId = 5, name = User5, city = Mumbai]]} Example 2: We can also provide an additional collector to the groupingBy if we need some extra information than the actual object. In this example, we will see how to get the count of the users belonging to each city.// Java program to convert User[]// into Map<city, countOfUser> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the user classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return "User [userId = " + userId + ", name = " + name + ", city = " + city + "]"; }} class GFG { public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, Long> cityUserCountMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect( Collectors.groupingBy( User::getCity, Collectors.counting())); return cityUserCountMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, "User1", "Pune"); User user2 = new User(2, "User2", "Mumbai"); User user3 = new User(3, "User3", "Nagpur"); User user4 = new User(4, "User4", "Pune"); User user5 = new User(5, "User5", "Mumbai"); System.out.println(toMap(user1, user2, user3, user4, user5)); }}Output:{Nagpur=1, Pune=2, Mumbai=2} // Java program to convert User[]// into Map<city, countOfUser> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the user classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return "User [userId = " + userId + ", name = " + name + ", city = " + city + "]"; }} class GFG { public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, Long> cityUserCountMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect( Collectors.groupingBy( User::getCity, Collectors.counting())); return cityUserCountMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, "User1", "Pune"); User user2 = new User(2, "User2", "Mumbai"); User user3 = new User(3, "User3", "Nagpur"); User user4 = new User(4, "User4", "Pune"); User user5 = new User(5, "User5", "Mumbai"); System.out.println(toMap(user1, user2, user3, user4, user5)); }} {Nagpur=1, Pune=2, Mumbai=2} Java 8 Java-Collectors java-map java-stream Java-Stream-Collectors Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25497, "s": 25469, "text": "\n21 Jun, 2020" }, { "code": null, "e": 25695, "s": 25497, "text": "Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result." }, { "code": null, "e": 25769, "s": 25695, "text": "In this article, the methods to convert a stream into a map is discussed." }, { "code": null, "e": 25813, "s": 25769, "text": "Method 1: Using Collectors.toMap() Function" }, { "code": null, "e": 25878, "s": 25813, "text": "The Collectors.toMap() method takes two parameters as the input:" }, { "code": null, "e": 26048, "s": 25878, "text": "KeyMapper: This function is used for extracting keys of the Map from stream value.ValueMapper: This function used for extracting the values of the map for the given key." }, { "code": null, "e": 26131, "s": 26048, "text": "KeyMapper: This function is used for extracting keys of the Map from stream value." }, { "code": null, "e": 26219, "s": 26131, "text": "ValueMapper: This function used for extracting the values of the map for the given key." }, { "code": null, "e": 26312, "s": 26219, "text": "The following are the examples of the toMap function to convert the given stream into a map:" }, { "code": null, "e": 27427, "s": 26312, "text": "Example 1: Here, we will convert a string into a Map with the keys as the words of the string and the value as the length of each word.// Program to convert// the Stream to Map import java.io.*;import java.util.stream.*;import java.util.Arrays;import java.util.Map; class GFG { // Function to convert the string // to the map public static Map toMap(String input) { Map<String, Integer> lengthMap = Arrays.stream(input.split(\" \")) .collect(Collectors.toMap( value -> value, value -> value.length())); return lengthMap; } public static void main(String[] args) { String input = \"Geeks for Geek\"; System.out.println(toMap(input)); }}Output:{Geek=4, for=3, Geeks=5}\nIn the above example, the toMap collector takes two lambda functions as parameters:(value -> value): It reads the current stream value and returns it as the key of the Map.(value -> value.length): It reads the current stream value, finds its length and returns the value to the Map for the given key." }, { "code": "// Program to convert// the Stream to Map import java.io.*;import java.util.stream.*;import java.util.Arrays;import java.util.Map; class GFG { // Function to convert the string // to the map public static Map toMap(String input) { Map<String, Integer> lengthMap = Arrays.stream(input.split(\" \")) .collect(Collectors.toMap( value -> value, value -> value.length())); return lengthMap; } public static void main(String[] args) { String input = \"Geeks for Geek\"; System.out.println(toMap(input)); }}", "e": 28075, "s": 27427, "text": null }, { "code": null, "e": 28101, "s": 28075, "text": "{Geek=4, for=3, Geeks=5}\n" }, { "code": null, "e": 28185, "s": 28101, "text": "In the above example, the toMap collector takes two lambda functions as parameters:" }, { "code": null, "e": 28403, "s": 28185, "text": "(value -> value): It reads the current stream value and returns it as the key of the Map.(value -> value.length): It reads the current stream value, finds its length and returns the value to the Map for the given key." }, { "code": null, "e": 28493, "s": 28403, "text": "(value -> value): It reads the current stream value and returns it as the key of the Map." }, { "code": null, "e": 28622, "s": 28493, "text": "(value -> value.length): It reads the current stream value, finds its length and returns the value to the Map for the given key." }, { "code": null, "e": 30680, "s": 28622, "text": "Example 2: Now, lets use the toMap function to perform a bit more complex map conversion. Here, we will convert a list of users into a map where UserId is the key and the User is the value.// Program to convert User[] into// Map<userId, User> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the User classpublic class User { // Attributes of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getters of the user class public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString method // to return the custom string @Override public String toString() { return \"User [userId = \" + userId + \", name = \" + name + \", city = \" + city + \"]\"; }} class GFG { // Function to convert the User // to the map public static Map toMap(User user1, User user2, User user3) { Map<Integer, User> userMap = Arrays.asList(user1, user2, user3) .stream() .collect(Collectors.toMap( user -> user.getUserId(), user -> user)); return userMap; } // Driver code public static void main(String[] args) { // Creating users User user1 = new User(1, \"User1\", \"Pune\"); User user2 = new User(2, \"User2\", \"Mumbai\"); User user3 = new User(3, \"User3\", \"Nagpur\"); System.out.println(toMap(user1, user2, user3)); }}Output:{1=User [userId = 1, name = User1, city = Pune], 2=User [userId = 2, name = User2, city = Mumbai], 3=User [userId = 3, name = User3, city = Nagpur]}" }, { "code": "// Program to convert User[] into// Map<userId, User> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the User classpublic class User { // Attributes of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getters of the user class public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString method // to return the custom string @Override public String toString() { return \"User [userId = \" + userId + \", name = \" + name + \", city = \" + city + \"]\"; }} class GFG { // Function to convert the User // to the map public static Map toMap(User user1, User user2, User user3) { Map<Integer, User> userMap = Arrays.asList(user1, user2, user3) .stream() .collect(Collectors.toMap( user -> user.getUserId(), user -> user)); return userMap; } // Driver code public static void main(String[] args) { // Creating users User user1 = new User(1, \"User1\", \"Pune\"); User user2 = new User(2, \"User2\", \"Mumbai\"); User user3 = new User(3, \"User3\", \"Nagpur\"); System.out.println(toMap(user1, user2, user3)); }}", "e": 32394, "s": 30680, "text": null }, { "code": null, "e": 32543, "s": 32394, "text": "{1=User [userId = 1, name = User1, city = Pune], 2=User [userId = 2, name = User2, city = Mumbai], 3=User [userId = 3, name = User3, city = Nagpur]}" }, { "code": null, "e": 32570, "s": 32543, "text": "Method 2: Using Collectors" }, { "code": null, "e": 32772, "s": 32570, "text": "The groupingBy collector takes one function as input and creates a group of stream objects using that function. The following are the examples to convert a stream into a map using groupingBy collector." }, { "code": null, "e": 35230, "s": 32772, "text": "Example 1: In this example, we will convert a user stream into a map whose key is the city and the value is the users living in that city.// Java program to convert the User[]// into Map<city, List<User>> import java.util.Arrays;import java.util.Map;import java.util.List;import java.util.stream.*; // Implementing the User classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor of the User class public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return \"User [userId = \" + userId + \", name = \" + name + \", city = \" + city + \"]\"; }} class GFG { // Function to convert the user // object to the map public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, List<User> > cityUserListMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect(Collectors.groupingBy( User::getCity)); return cityUserListMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, \"User1\", \"Pune\"); User user2 = new User(2, \"User2\", \"Mumbai\"); User user3 = new User(3, \"User3\", \"Nagpur\"); User user4 = new User(4, \"User4\", \"Pune\"); User user5 = new User(5, \"User5\", \"Mumbai\"); System.out.println(toMap(user1, user2, user3, user4, user5)); }}Output:{Nagpur=[User [userId = 3, name = User3, city = Nagpur]], Pune=[User [userId = 1, name = User1, city = Pune], User [userId = 4, name = User4, city = Pune]], Mumbai=[User [userId = 2, name = User2, city = Mumbai], User [userId = 5, name = User5, city = Mumbai]]}" }, { "code": "// Java program to convert the User[]// into Map<city, List<User>> import java.util.Arrays;import java.util.Map;import java.util.List;import java.util.stream.*; // Implementing the User classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor of the User class public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return \"User [userId = \" + userId + \", name = \" + name + \", city = \" + city + \"]\"; }} class GFG { // Function to convert the user // object to the map public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, List<User> > cityUserListMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect(Collectors.groupingBy( User::getCity)); return cityUserListMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, \"User1\", \"Pune\"); User user2 = new User(2, \"User2\", \"Mumbai\"); User user3 = new User(3, \"User3\", \"Nagpur\"); User user4 = new User(4, \"User4\", \"Pune\"); User user5 = new User(5, \"User5\", \"Mumbai\"); System.out.println(toMap(user1, user2, user3, user4, user5)); }}", "e": 37282, "s": 35230, "text": null }, { "code": null, "e": 37544, "s": 37282, "text": "{Nagpur=[User [userId = 3, name = User3, city = Nagpur]], Pune=[User [userId = 1, name = User1, city = Pune], User [userId = 4, name = User4, city = Pune]], Mumbai=[User [userId = 2, name = User2, city = Mumbai], User [userId = 5, name = User5, city = Mumbai]]}" }, { "code": null, "e": 39818, "s": 37544, "text": "Example 2: We can also provide an additional collector to the groupingBy if we need some extra information than the actual object. In this example, we will see how to get the count of the users belonging to each city.// Java program to convert User[]// into Map<city, countOfUser> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the user classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return \"User [userId = \" + userId + \", name = \" + name + \", city = \" + city + \"]\"; }} class GFG { public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, Long> cityUserCountMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect( Collectors.groupingBy( User::getCity, Collectors.counting())); return cityUserCountMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, \"User1\", \"Pune\"); User user2 = new User(2, \"User2\", \"Mumbai\"); User user3 = new User(3, \"User3\", \"Nagpur\"); User user4 = new User(4, \"User4\", \"Pune\"); User user5 = new User(5, \"User5\", \"Mumbai\"); System.out.println(toMap(user1, user2, user3, user4, user5)); }}Output:{Nagpur=1, Pune=2, Mumbai=2}\n" }, { "code": "// Java program to convert User[]// into Map<city, countOfUser> import java.util.Arrays;import java.util.Map;import java.util.stream.*; // Implementing the user classpublic class User { // Parameters of the user class private int userId; private String name; private String city; // Constructor public User(int userId, String name, String city) { this.userId = userId; this.name = name; this.city = city; } // Getter functions public int getUserId() { return userId; } public String getName() { return name; } public String getCity() { return city; } // Overriding the toString() method // to create a custom function @Override public String toString() { return \"User [userId = \" + userId + \", name = \" + name + \", city = \" + city + \"]\"; }} class GFG { public static Map toMap(User user1, User user2, User user3, User user4, User user5) { Map<String, Long> cityUserCountMap = Arrays.asList(user1, user2, user3, user4, user5) .stream() .collect( Collectors.groupingBy( User::getCity, Collectors.counting())); return cityUserCountMap; } // Driver code public static void main(String[] args) { // Creating new users User user1 = new User(1, \"User1\", \"Pune\"); User user2 = new User(2, \"User2\", \"Mumbai\"); User user3 = new User(3, \"User3\", \"Nagpur\"); User user4 = new User(4, \"User4\", \"Pune\"); User user5 = new User(5, \"User5\", \"Mumbai\"); System.out.println(toMap(user1, user2, user3, user4, user5)); }}", "e": 41839, "s": 39818, "text": null }, { "code": null, "e": 41869, "s": 41839, "text": "{Nagpur=1, Pune=2, Mumbai=2}\n" }, { "code": null, "e": 41876, "s": 41869, "text": "Java 8" }, { "code": null, "e": 41892, "s": 41876, "text": "Java-Collectors" }, { "code": null, "e": 41901, "s": 41892, "text": "java-map" }, { "code": null, "e": 41913, "s": 41901, "text": "java-stream" }, { "code": null, "e": 41936, "s": 41913, "text": "Java-Stream-Collectors" }, { "code": null, "e": 41941, "s": 41936, "text": "Java" }, { "code": null, "e": 41955, "s": 41941, "text": "Java Programs" }, { "code": null, "e": 41960, "s": 41955, "text": "Java" }, { "code": null, "e": 42058, "s": 41960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42109, "s": 42058, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 42139, "s": 42109, "text": "HashMap in Java with Examples" }, { "code": null, "e": 42158, "s": 42139, "text": "Interfaces in Java" }, { "code": null, "e": 42189, "s": 42158, "text": "How to iterate any Map in Java" }, { "code": null, "e": 42207, "s": 42189, "text": "ArrayList in Java" }, { "code": null, "e": 42235, "s": 42207, "text": "Initializing a List in Java" }, { "code": null, "e": 42279, "s": 42235, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 42305, "s": 42279, "text": "Java Programming Examples" }, { "code": null, "e": 42339, "s": 42305, "text": "Convert Double to Integer in Java" } ]
PyQt5 - How to set the maximum value of progress bar ? - GeeksforGeeks
22 Apr, 2020 In this article we will see how to set the maximum value of progress bar. By default the maximum value of progress bar is 100, but we can change it to our need. In order to do this we will use setMaximum method, this will change the maximum value of progress bar. Note : When we will set the value to progress bar using setValue method, the percentage may or may not be equal to the value passed in it, it depends on the range of progress bar. percentage = ((value_passed - minimum_value)/(maximum_value - minimum_value))*100 Here, minimum_value = 0, value_passed and maximum_value is set by user. Syntax : bar.setMaximum(maximum_value) Argument : It takes argument. Action performed : It will change the maximum value of progress bar. 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, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # setting maximum value of progress bar to 1000 bar.setMaximum(1000) # setting value to progress bar bar.setValue(200) # setting alignment to centre bar.setAlignment(Qt.AlignCenter) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25951, "s": 25923, "text": "\n22 Apr, 2020" }, { "code": null, "e": 26215, "s": 25951, "text": "In this article we will see how to set the maximum value of progress bar. By default the maximum value of progress bar is 100, but we can change it to our need. In order to do this we will use setMaximum method, this will change the maximum value of progress bar." }, { "code": null, "e": 26395, "s": 26215, "text": "Note : When we will set the value to progress bar using setValue method, the percentage may or may not be equal to the value passed in it, it depends on the range of progress bar." }, { "code": null, "e": 26477, "s": 26395, "text": "percentage = ((value_passed - minimum_value)/(maximum_value - minimum_value))*100" }, { "code": null, "e": 26549, "s": 26477, "text": "Here, minimum_value = 0, value_passed and maximum_value is set by user." }, { "code": null, "e": 26588, "s": 26549, "text": "Syntax : bar.setMaximum(maximum_value)" }, { "code": null, "e": 26618, "s": 26588, "text": "Argument : It takes argument." }, { "code": null, "e": 26687, "s": 26618, "text": "Action performed : It will change the maximum value of progress bar." }, { "code": null, "e": 26716, "s": 26687, "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, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # setting maximum value of progress bar to 1000 bar.setMaximum(1000) # setting value to progress bar bar.setValue(200) # setting alignment to centre bar.setAlignment(Qt.AlignCenter) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27762, "s": 26716, "text": null }, { "code": null, "e": 27771, "s": 27762, "text": "Output :" }, { "code": null, "e": 27782, "s": 27771, "text": "Python-gui" }, { "code": null, "e": 27794, "s": 27782, "text": "Python-PyQt" }, { "code": null, "e": 27801, "s": 27794, "text": "Python" }, { "code": null, "e": 27899, "s": 27801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27917, "s": 27899, "text": "Python Dictionary" }, { "code": null, "e": 27952, "s": 27917, "text": "Read a file line by line in Python" }, { "code": null, "e": 27984, "s": 27952, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28006, "s": 27984, "text": "Enumerate() in Python" }, { "code": null, "e": 28048, "s": 28006, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28078, "s": 28048, "text": "Iterate over a list in Python" }, { "code": null, "e": 28104, "s": 28078, "text": "Python String | replace()" }, { "code": null, "e": 28133, "s": 28104, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28177, "s": 28133, "text": "Reading and Writing to text files in Python" } ]
How to parse a CSV File in PHP ? - GeeksforGeeks
21 May, 2021 In this article, we learn to parse a CSV file using PHP code. Approach: Step 1. Add data to an excel file. The following example is given for a sample data having Name and Coding Score as their column headers. Step 2. Convert to CSV file by following the path. Go to File>Export>Change File Type> CSV Type. Save the file in your working folder with name “Book1.csv”. Parsing CSV file using PHP: Step 1. Create a folder and add that CSV file and create a new PHP file in it. file path Step 2. Open the PHP file and write the following code in it which is explained in the following steps. Open dataset of CSV using fopen function.$open = fopen("filename.csv", "r");Read a line using fgetcsv() function.$data = fgetcsv($Open, 1000, ",");Use a loop to iterate in every row of data.while (($data = fgetcsv($Open, 1000, ",")) !== FALSE) { // Read the data }Close that file using PHP fclose() method.fclose($open); Open dataset of CSV using fopen function.$open = fopen("filename.csv", "r"); Open dataset of CSV using fopen function. $open = fopen("filename.csv", "r"); Read a line using fgetcsv() function.$data = fgetcsv($Open, 1000, ","); Read a line using fgetcsv() function. $data = fgetcsv($Open, 1000, ","); Use a loop to iterate in every row of data.while (($data = fgetcsv($Open, 1000, ",")) !== FALSE) { // Read the data } Use a loop to iterate in every row of data. while (($data = fgetcsv($Open, 1000, ",")) !== FALSE) { // Read the data } Close that file using PHP fclose() method.fclose($open); Close that file using PHP fclose() method. fclose($open); Example: PHP <?php if (($open = fopen("Book1.csv", "r")) !== FALSE) { while (($data = fgetcsv($open, 1000, ",")) !== FALSE) { $array[] = $data; } fclose($open); } echo "<pre>"; //To display array data var_dump($array); echo "</pre>"; Output: array(6) { [0]=> array(2) { [0]=> string(5) "Name " [1]=> string(12) "Coding Score" } [1]=> array(2) { [0]=> string(4) "Atul" [1]=> string(3) "200" } [2]=> array(2) { [0]=> string(5) "Danny" [1]=> string(3) "250" } [3]=> array(2) { [0]=> string(6) "Aditya" [1]=> string(3) "150" } [4]=> array(2) { [0]=> string(7) "Avinash" [1]=> string(3) "300" } [5]=> array(2) { [0]=> string(6) "Ashish" [1]=> string(3) "240" } } PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 32677, "s": 32649, "text": "\n21 May, 2021" }, { "code": null, "e": 32739, "s": 32677, "text": "In this article, we learn to parse a CSV file using PHP code." }, { "code": null, "e": 32749, "s": 32739, "text": "Approach:" }, { "code": null, "e": 32887, "s": 32749, "text": "Step 1. Add data to an excel file. The following example is given for a sample data having Name and Coding Score as their column headers." }, { "code": null, "e": 33044, "s": 32887, "text": "Step 2. Convert to CSV file by following the path. Go to File>Export>Change File Type> CSV Type. Save the file in your working folder with name “Book1.csv”." }, { "code": null, "e": 33072, "s": 33044, "text": "Parsing CSV file using PHP:" }, { "code": null, "e": 33151, "s": 33072, "text": "Step 1. Create a folder and add that CSV file and create a new PHP file in it." }, { "code": null, "e": 33161, "s": 33151, "text": "file path" }, { "code": null, "e": 33265, "s": 33161, "text": "Step 2. Open the PHP file and write the following code in it which is explained in the following steps." }, { "code": null, "e": 33593, "s": 33265, "text": "Open dataset of CSV using fopen function.$open = fopen(\"filename.csv\", \"r\");Read a line using fgetcsv() function.$data = fgetcsv($Open, 1000, \",\");Use a loop to iterate in every row of data.while (($data = fgetcsv($Open, 1000, \",\")) !== FALSE) \n{\n // Read the data \n}Close that file using PHP fclose() method.fclose($open);" }, { "code": null, "e": 33670, "s": 33593, "text": "Open dataset of CSV using fopen function.$open = fopen(\"filename.csv\", \"r\");" }, { "code": null, "e": 33712, "s": 33670, "text": "Open dataset of CSV using fopen function." }, { "code": null, "e": 33748, "s": 33712, "text": "$open = fopen(\"filename.csv\", \"r\");" }, { "code": null, "e": 33820, "s": 33748, "text": "Read a line using fgetcsv() function.$data = fgetcsv($Open, 1000, \",\");" }, { "code": null, "e": 33858, "s": 33820, "text": "Read a line using fgetcsv() function." }, { "code": null, "e": 33893, "s": 33858, "text": "$data = fgetcsv($Open, 1000, \",\");" }, { "code": null, "e": 34018, "s": 33893, "text": "Use a loop to iterate in every row of data.while (($data = fgetcsv($Open, 1000, \",\")) !== FALSE) \n{\n // Read the data \n}" }, { "code": null, "e": 34062, "s": 34018, "text": "Use a loop to iterate in every row of data." }, { "code": null, "e": 34144, "s": 34062, "text": "while (($data = fgetcsv($Open, 1000, \",\")) !== FALSE) \n{\n // Read the data \n}" }, { "code": null, "e": 34201, "s": 34144, "text": "Close that file using PHP fclose() method.fclose($open);" }, { "code": null, "e": 34244, "s": 34201, "text": "Close that file using PHP fclose() method." }, { "code": null, "e": 34259, "s": 34244, "text": "fclose($open);" }, { "code": null, "e": 34268, "s": 34259, "text": "Example:" }, { "code": null, "e": 34272, "s": 34268, "text": "PHP" }, { "code": "<?php if (($open = fopen(\"Book1.csv\", \"r\")) !== FALSE) { while (($data = fgetcsv($open, 1000, \",\")) !== FALSE) { $array[] = $data; } fclose($open); } echo \"<pre>\"; //To display array data var_dump($array); echo \"</pre>\";", "e": 34534, "s": 34272, "text": null }, { "code": null, "e": 34542, "s": 34534, "text": "Output:" }, { "code": null, "e": 35090, "s": 34542, "text": "array(6) {\n [0]=>\n array(2) {\n [0]=>\n string(5) \"Name \"\n [1]=>\n string(12) \"Coding Score\"\n }\n [1]=>\n array(2) {\n [0]=>\n string(4) \"Atul\"\n [1]=>\n string(3) \"200\"\n }\n [2]=>\n array(2) {\n [0]=>\n string(5) \"Danny\"\n [1]=>\n string(3) \"250\"\n }\n [3]=>\n array(2) {\n [0]=>\n string(6) \"Aditya\"\n [1]=>\n string(3) \"150\"\n }\n [4]=>\n array(2) {\n [0]=>\n string(7) \"Avinash\"\n [1]=>\n string(3) \"300\"\n }\n [5]=>\n array(2) {\n [0]=>\n string(6) \"Ashish\"\n [1]=>\n string(3) \"240\"\n }\n}" }, { "code": null, "e": 35103, "s": 35090, "text": "PHP-function" }, { "code": null, "e": 35117, "s": 35103, "text": "PHP-Questions" }, { "code": null, "e": 35124, "s": 35117, "text": "Picked" }, { "code": null, "e": 35128, "s": 35124, "text": "PHP" }, { "code": null, "e": 35145, "s": 35128, "text": "Web Technologies" }, { "code": null, "e": 35149, "s": 35145, "text": "PHP" }, { "code": null, "e": 35247, "s": 35149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35292, "s": 35247, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 35342, "s": 35292, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 35382, "s": 35342, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 35406, "s": 35382, "text": "PHP in_array() Function" }, { "code": null, "e": 35450, "s": 35406, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 35490, "s": 35450, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35523, "s": 35490, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35568, "s": 35523, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35611, "s": 35568, "text": "How to fetch data from an API in ReactJS ?" } ]
Draw moving object using Turtle in Python - GeeksforGeeks
13 Oct, 2020 Turtle is an inbuilt module in python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc. Following steps are used: Import Turtle package. Set screen with dimensions and color. Form turtle object with color. Form the object (ball – made of colored circle). Call the function for making object again and again and clear the screen. Below is the implementation : # import turtle package import turtle # function for movement of an object def moving_object(move): # to fill the color in ball move.fillcolor('orange') # start color filling move.begin_fill() # draw circle move.circle(20) # end color filling move.end_fill() # Driver Code if __name__ == "__main__" : # create a screen object screen = turtle.Screen() # set screen size screen.setup(600,600) # screen background color screen.bgcolor('green') # screen updaion screen.tracer(0) # create a turtle object object move = turtle.Turtle() # set a turtle object color move.color('orange') # set turtle object speed move.speed(0) # set turtle object width move.width(2) # hide turtle object move.hideturtle() # turtle object in air move.penup() # set initial position move.goto(-250, 0) # move turtle object to surface move.pendown() # infinite loop while True : # clear turtle work move.clear() # call function to draw ball moving_object(move) # update screen screen.update() # forward motion by turtle object move.forward(0.5) Example 2: Move the Object (box) Following steps are used: Import Turtle package. Set screen with dimensions and color. Form turtle object with color. Form the object (box – made of colored square). Call the function for making object again and again and clear the screen. Below is the implementation:- import turtle screen = turtle.Screen() screen.setup(500,500) screen.bgcolor('Green') # tell screen to not # show automatically screen.tracer(0) t = turtle.Turtle() t.speed(0) t.width(3) # hide donatello, we # only want to see the drawing t.hideturtle() def draw_square() : t.fillcolor("Orange") t.begin_fill() for side in range(4) : t.forward(100) t.left(90) t.end_fill() t.penup() t.goto(-350, 0) t.pendown() while True : t.clear() draw_square() # only now show the screen, # as one of the frames screen.update() t.forward(0.02) # This code is contributed by pulkitagarwal03pulkit Output: pulkitagarwal03pulkit Python-projects Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON? isupper(), islower(), lower(), upper() in Python and their applications Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Graph Plotting in Python | Set 1
[ { "code": null, "e": 25777, "s": 25749, "text": "\n13 Oct, 2020" }, { "code": null, "e": 26015, "s": 25777, "text": "Turtle is an inbuilt module in python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc." }, { "code": null, "e": 26041, "s": 26015, "text": "Following steps are used:" }, { "code": null, "e": 26064, "s": 26041, "text": "Import Turtle package." }, { "code": null, "e": 26102, "s": 26064, "text": "Set screen with dimensions and color." }, { "code": null, "e": 26133, "s": 26102, "text": "Form turtle object with color." }, { "code": null, "e": 26182, "s": 26133, "text": "Form the object (ball – made of colored circle)." }, { "code": null, "e": 26256, "s": 26182, "text": "Call the function for making object again and again and clear the screen." }, { "code": null, "e": 26287, "s": 26256, "text": "Below is the implementation :" }, { "code": null, "e": 27681, "s": 26287, "text": "# import turtle package\nimport turtle\n\n\n# function for movement of an object \ndef moving_object(move):\n \n # to fill the color in ball\n move.fillcolor('orange') \n \n # start color filling\n move.begin_fill() \n \n # draw circle\n move.circle(20) \n \n # end color filling\n move.end_fill() \n\n# Driver Code\nif __name__ == \"__main__\" :\n \n # create a screen object\n screen = turtle.Screen() \n\n # set screen size\n screen.setup(600,600) \n\n # screen background color\n screen.bgcolor('green') \n\n # screen updaion \n screen.tracer(0) \n\n # create a turtle object object\n move = turtle.Turtle() \n\n # set a turtle object color\n move.color('orange')\n\n # set turtle object speed\n move.speed(0) \n\n # set turtle object width\n move.width(2) \n\n # hide turtle object\n move.hideturtle() \n\n # turtle object in air\n move.penup() \n\n # set initial position\n move.goto(-250, 0) \n\n # move turtle object to surface\n move.pendown() \n\n # infinite loop\n while True :\n \n # clear turtle work\n move.clear() \n \n # call function to draw ball\n moving_object(move) \n \n # update screen\n screen.update() \n \n # forward motion by turtle object\n move.forward(0.5) \n" }, { "code": null, "e": 27715, "s": 27681, "text": "Example 2: Move the Object (box)" }, { "code": null, "e": 27741, "s": 27715, "text": "Following steps are used:" }, { "code": null, "e": 27764, "s": 27741, "text": "Import Turtle package." }, { "code": null, "e": 27802, "s": 27764, "text": "Set screen with dimensions and color." }, { "code": null, "e": 27833, "s": 27802, "text": "Form turtle object with color." }, { "code": null, "e": 27881, "s": 27833, "text": "Form the object (box – made of colored square)." }, { "code": null, "e": 27955, "s": 27881, "text": "Call the function for making object again and again and clear the screen." }, { "code": null, "e": 27985, "s": 27955, "text": "Below is the implementation:-" }, { "code": null, "e": 28673, "s": 27985, "text": "import turtle\n\nscreen = turtle.Screen()\nscreen.setup(500,500)\nscreen.bgcolor('Green')\n\n# tell screen to not \n# show automatically\nscreen.tracer(0) \n\nt = turtle.Turtle()\nt.speed(0)\nt.width(3)\n\n# hide donatello, we\n# only want to see the drawing\nt.hideturtle() \n\ndef draw_square() :\n t.fillcolor(\"Orange\")\n t.begin_fill()\n for side in range(4) :\n t.forward(100)\n t.left(90)\n t.end_fill()\nt.penup()\nt.goto(-350, 0)\nt.pendown()\n\nwhile True :\n t.clear()\n draw_square()\n \n # only now show the screen,\n # as one of the frames\n screen.update() \n t.forward(0.02)\n \n# This code is contributed by pulkitagarwal03pulkit" }, { "code": null, "e": 28681, "s": 28673, "text": "Output:" }, { "code": null, "e": 28703, "s": 28681, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 28719, "s": 28703, "text": "Python-projects" }, { "code": null, "e": 28733, "s": 28719, "text": "Python-turtle" }, { "code": null, "e": 28740, "s": 28733, "text": "Python" }, { "code": null, "e": 28838, "s": 28740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28870, "s": 28838, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28899, "s": 28870, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28936, "s": 28899, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28978, "s": 28936, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29014, "s": 28978, "text": "Convert integer to string in Python" }, { "code": null, "e": 29056, "s": 29014, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29128, "s": 29056, "text": "isupper(), islower(), lower(), upper() in Python and their applications" }, { "code": null, "e": 29155, "s": 29128, "text": "Python Classes and Objects" }, { "code": null, "e": 29211, "s": 29155, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Modify Linked List by replacing each node by nearest multiple of K - GeeksforGeeks
08 Dec, 2021 Given a singly Linked List L consisting of N nodes and an integer K, the task is to modify the value of each node of the given Linked List to its nearest multiple of K, not exceeding the value of the node. Examples: Input: LL: 1 -> 2 -> 3 -> 5, K = 2 Output: 0 -> 2 -> 2 -> 4Explanation:The resultant LL has values having less than the original LL value and is a multiple of K(= 2). Input: LL:13 -> 14 -> 26 -> 29 -> 40, K = 13Output: 13 -> 13 -> 26 -> 26 -> 39 Approach: The given problem can be solved by traversing the given Linked List and for each node traversed, find the floor value, say val, of the node value divided by K and update the node values to val*K. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <iostream>using namespace std; // Structure of nodestruct node { int data; node* next;}; // Function to replace the node N// by the nearest multiple of Knode* EvalNearestMult(node* N, int K){ node* temp = N; int t; // Traverse the Linked List while (N != NULL) { // If data is less than K if (N->data < K) N->data = 0; else { // If the data of current // node is same as K if (N->data == K) N->data = K; // Otherwise change the value else { N->data = (N->data / K) * K; } } // Move to the next node N = N->next; } // Return the updated LL return temp;} // Function to print the nodes of// the Linked Listvoid printList(node* N){ // Traverse the LL while (N != NULL) { // Print the node's data cout << N->data << " "; N = N->next; }} // Driver Codeint main(){ // Given Linked List node* head = NULL; node* second = NULL; node* third = NULL; head = new node(); second = new node(); third = new node(); head->data = 3; head->next = second; second->data = 4; second->next = third; third->data = 8; third->next = NULL; node* t = EvalNearestMult(head, 3); printList(t); return 0;} // Java program for the above approachimport java.io.*; class GFG { // Structure of node static class node { int data; node next; node(int d) { data = d; } } // Function to replace the node N // by the nearest multiple of K static node EvalNearestMult(node N, int K) { node temp = N; int t; // Traverse the Linked List while (N != null) { // If data is less than K if (N.data < K) N.data = 0; else { // If the data of current // node is same as K if (N.data == K) N.data = K; // Otherwise change the value else { N.data = (N.data / K) * K; } } // Move to the next node N = N.next; } // Return the updated LL return temp; } // Function to print the nodes of // the Linked List static void printList(node N) { // Traverse the LL while (N != null) { // Print the node's data System.out.print(N.data + " "); N = N.next; } } // Driver Code public static void main(String[] args) { // Given Linked List node head = new node(3); head.next = new node(5); head.next.next = new node(8); node t = EvalNearestMult(head, 3); printList(t); }} // This code is contributed by Dharanendra L V # Python program for the above approach # Structure of Nodeclass Node: def __init__(self, data): self.data = data; self.next = None; # Function to replace the Node N# by the nearest multiple of Kdef EvalNearestMult(N, K): temp = N; t; # Traverse the Linked List while (N != None): # If data is less than K if (N.data < K): N.data = 0; else: # If the data of current # Node is same as K if (N.data == K): N.data = K; # Otherwise change the value else: N.data = (N.data // K) * K; # Move to the next Node N = N.next; # Return the updated LL return temp; # Function to print Nodes of# the Linked Listdef printList(N): # Traverse the LL while (N != None): # Print Node's data print(N.data , end=" "); N = N.next; # Driver Codeif __name__ == '__main__': # Given Linked List head = Node(3); head.next = Node(5); head.next.next = Node(8); t = None; t = EvalNearestMult(head, 3); printList(t); # This code is contributed by gauravrajput1 // C# program for the above approachusing System; public class GFG{ // Structure of node public class node { public int data; public node next; public node(int d) { data = d; } } // Function to replace the node N // by the nearest multiple of K static node EvalNearestMult(node N, int K) { node temp = N; // Traverse the Linked List while (N != null) { // If data is less than K if (N.data < K) N.data = 0; else { // If the data of current // node is same as K if (N.data == K) N.data = K; // Otherwise change the value else { N.data = (N.data / K) * K; } } // Move to the next node N = N.next; } // Return the updated LL return temp; } // Function to print the nodes of // the Linked List static void printList(node N) { // Traverse the LL while (N != null) { // Print the node's data Console.Write(N.data + " "); N = N.next; } } // Driver Code public static void Main(String[] args) { // Given Linked List node head = new node(3); head.next = new node(5); head.next.next = new node(8); node t = EvalNearestMult(head, 3); printList(t); }} // This code is contributed by gauravrajput1 <script>// Javascript program for the above approach // Structure of nodeclass node { constructor() { this.data = 0; this.next = null; }}; // Function to replace the node N// by the nearest multiple of Kfunction EvalNearestMult(N, K){ var temp = N; var t; // Traverse the Linked List while (N != null) { // If data is less than K if (N.data < K) N.data = 0; else { // If the data of current // node is same as K if (N.data == K) N.data = K; // Otherwise change the value else { N.data = parseInt(N.data / K) * K; } } // Move to the next node N = N.next; } // Return the updated LL return temp;} // Function to print the nodes of// the Linked Listfunction printList(N){ // Traverse the LL while (N != null) { // Print the node's data document.write( N.data + " "); N = N.next; }} // Driver Code// Given Linked Listvar head = null;var second = null;var third = null;head = new node();second = new node();third = new node();head.data = 3;head.next = second;second.data = 4;second.next = third;third.data = 8;third.next = null;var t = EvalNearestMult(head, 3);printList(t); // This code is contributed by rrrtnx. </script> 3 3 6 Time Complexity: O(N)Auxiliary Space: O(1) dharanendralv23 rrrtnx GauravRajput1 khushboogoyal499 Linked List Mathematical Linked List Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Program to implement Singly Linked List in C++ using class Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26179, "s": 26151, "text": "\n08 Dec, 2021" }, { "code": null, "e": 26385, "s": 26179, "text": "Given a singly Linked List L consisting of N nodes and an integer K, the task is to modify the value of each node of the given Linked List to its nearest multiple of K, not exceeding the value of the node." }, { "code": null, "e": 26395, "s": 26385, "text": "Examples:" }, { "code": null, "e": 26562, "s": 26395, "text": "Input: LL: 1 -> 2 -> 3 -> 5, K = 2 Output: 0 -> 2 -> 2 -> 4Explanation:The resultant LL has values having less than the original LL value and is a multiple of K(= 2)." }, { "code": null, "e": 26641, "s": 26562, "text": "Input: LL:13 -> 14 -> 26 -> 29 -> 40, K = 13Output: 13 -> 13 -> 26 -> 26 -> 39" }, { "code": null, "e": 26847, "s": 26641, "text": "Approach: The given problem can be solved by traversing the given Linked List and for each node traversed, find the floor value, say val, of the node value divided by K and update the node values to val*K." }, { "code": null, "e": 26898, "s": 26847, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26902, "s": 26898, "text": "C++" }, { "code": null, "e": 26907, "s": 26902, "text": "Java" }, { "code": null, "e": 26915, "s": 26907, "text": "Python3" }, { "code": null, "e": 26918, "s": 26915, "text": "C#" }, { "code": null, "e": 26929, "s": 26918, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <iostream>using namespace std; // Structure of nodestruct node { int data; node* next;}; // Function to replace the node N// by the nearest multiple of Knode* EvalNearestMult(node* N, int K){ node* temp = N; int t; // Traverse the Linked List while (N != NULL) { // If data is less than K if (N->data < K) N->data = 0; else { // If the data of current // node is same as K if (N->data == K) N->data = K; // Otherwise change the value else { N->data = (N->data / K) * K; } } // Move to the next node N = N->next; } // Return the updated LL return temp;} // Function to print the nodes of// the Linked Listvoid printList(node* N){ // Traverse the LL while (N != NULL) { // Print the node's data cout << N->data << \" \"; N = N->next; }} // Driver Codeint main(){ // Given Linked List node* head = NULL; node* second = NULL; node* third = NULL; head = new node(); second = new node(); third = new node(); head->data = 3; head->next = second; second->data = 4; second->next = third; third->data = 8; third->next = NULL; node* t = EvalNearestMult(head, 3); printList(t); return 0;}", "e": 28319, "s": 26929, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG { // Structure of node static class node { int data; node next; node(int d) { data = d; } } // Function to replace the node N // by the nearest multiple of K static node EvalNearestMult(node N, int K) { node temp = N; int t; // Traverse the Linked List while (N != null) { // If data is less than K if (N.data < K) N.data = 0; else { // If the data of current // node is same as K if (N.data == K) N.data = K; // Otherwise change the value else { N.data = (N.data / K) * K; } } // Move to the next node N = N.next; } // Return the updated LL return temp; } // Function to print the nodes of // the Linked List static void printList(node N) { // Traverse the LL while (N != null) { // Print the node's data System.out.print(N.data + \" \"); N = N.next; } } // Driver Code public static void main(String[] args) { // Given Linked List node head = new node(3); head.next = new node(5); head.next.next = new node(8); node t = EvalNearestMult(head, 3); printList(t); }} // This code is contributed by Dharanendra L V", "e": 29864, "s": 28319, "text": null }, { "code": "# Python program for the above approach # Structure of Nodeclass Node: def __init__(self, data): self.data = data; self.next = None; # Function to replace the Node N# by the nearest multiple of Kdef EvalNearestMult(N, K): temp = N; t; # Traverse the Linked List while (N != None): # If data is less than K if (N.data < K): N.data = 0; else: # If the data of current # Node is same as K if (N.data == K): N.data = K; # Otherwise change the value else: N.data = (N.data // K) * K; # Move to the next Node N = N.next; # Return the updated LL return temp; # Function to print Nodes of# the Linked Listdef printList(N): # Traverse the LL while (N != None): # Print Node's data print(N.data , end=\" \"); N = N.next; # Driver Codeif __name__ == '__main__': # Given Linked List head = Node(3); head.next = Node(5); head.next.next = Node(8); t = None; t = EvalNearestMult(head, 3); printList(t); # This code is contributed by gauravrajput1", "e": 31059, "s": 29864, "text": null }, { "code": "// C# program for the above approachusing System; public class GFG{ // Structure of node public class node { public int data; public node next; public node(int d) { data = d; } } // Function to replace the node N // by the nearest multiple of K static node EvalNearestMult(node N, int K) { node temp = N; // Traverse the Linked List while (N != null) { // If data is less than K if (N.data < K) N.data = 0; else { // If the data of current // node is same as K if (N.data == K) N.data = K; // Otherwise change the value else { N.data = (N.data / K) * K; } } // Move to the next node N = N.next; } // Return the updated LL return temp; } // Function to print the nodes of // the Linked List static void printList(node N) { // Traverse the LL while (N != null) { // Print the node's data Console.Write(N.data + \" \"); N = N.next; } } // Driver Code public static void Main(String[] args) { // Given Linked List node head = new node(3); head.next = new node(5); head.next.next = new node(8); node t = EvalNearestMult(head, 3); printList(t); }} // This code is contributed by gauravrajput1", "e": 32362, "s": 31059, "text": null }, { "code": "<script>// Javascript program for the above approach // Structure of nodeclass node { constructor() { this.data = 0; this.next = null; }}; // Function to replace the node N// by the nearest multiple of Kfunction EvalNearestMult(N, K){ var temp = N; var t; // Traverse the Linked List while (N != null) { // If data is less than K if (N.data < K) N.data = 0; else { // If the data of current // node is same as K if (N.data == K) N.data = K; // Otherwise change the value else { N.data = parseInt(N.data / K) * K; } } // Move to the next node N = N.next; } // Return the updated LL return temp;} // Function to print the nodes of// the Linked Listfunction printList(N){ // Traverse the LL while (N != null) { // Print the node's data document.write( N.data + \" \"); N = N.next; }} // Driver Code// Given Linked Listvar head = null;var second = null;var third = null;head = new node();second = new node();third = new node();head.data = 3;head.next = second;second.data = 4;second.next = third;third.data = 8;third.next = null;var t = EvalNearestMult(head, 3);printList(t); // This code is contributed by rrrtnx. </script>", "e": 33718, "s": 32362, "text": null }, { "code": null, "e": 33726, "s": 33718, "text": "3 3 6" }, { "code": null, "e": 33771, "s": 33728, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 33787, "s": 33771, "text": "dharanendralv23" }, { "code": null, "e": 33794, "s": 33787, "text": "rrrtnx" }, { "code": null, "e": 33808, "s": 33794, "text": "GauravRajput1" }, { "code": null, "e": 33825, "s": 33808, "text": "khushboogoyal499" }, { "code": null, "e": 33837, "s": 33825, "text": "Linked List" }, { "code": null, "e": 33850, "s": 33837, "text": "Mathematical" }, { "code": null, "e": 33862, "s": 33850, "text": "Linked List" }, { "code": null, "e": 33875, "s": 33862, "text": "Mathematical" }, { "code": null, "e": 33973, "s": 33875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34014, "s": 33973, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 34064, "s": 34014, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 34123, "s": 34064, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 34163, "s": 34123, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 34234, "s": 34163, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 34264, "s": 34234, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34324, "s": 34264, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34339, "s": 34324, "text": "C++ Data Types" }, { "code": null, "e": 34382, "s": 34339, "text": "Set in C++ Standard Template Library (STL)" } ]
How to get data of any size from the EEPROM with Arduino?
Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data. In this article, we will see how to get data of any size (not just a byte) from the EEPROM. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from − File → Examples → EEPROM. We will look at the eeprom_get example. This example assumes that you've pre-set the data in Arduino's EEPROM by running the code in the eeprom_put example. In other words, the eeprom_put example is a precursor to this example. The main function of interest is EEPROM.get(). It takes two arguments, the starting address from which to start reading data, and the variable in which the read data is to be stored (which can be of a primitive type, like float, or a custom struct). Examples of other primitive data types are short, int, long, char, double, etc. This function determines the number of bytes to read based on the size of the variable in which the read data is to be stored. We begin with the inclusion of the library. #include <EEPROM.h> There is a global struct defined later in the code. struct MyObject { float field1; byte field2; char name[10]; }; Within the Setup, we first initialize Serial, and read a float from the beginning of the EEPROM (address = 0). We then read a struct in the secondTest() function (where we first move the EEPROM read address by the size of a float, then create an object of the type struct, and read into it. We then print the fields within the struct one by one. void setup() { float f = 0.00f; //Variable to store data read from EEPROM. int eeAddress = 0; //EEPROM address to start reading from Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.print("Read float from EEPROM: "); //Get the float data from the EEPROM at position 'eeAddress' EEPROM.get(eeAddress, f); Serial.println(f, 3); //This may print 'ovf, nan' if the data inside the EEPROM is not a valid float. /*** As get also returns a reference to 'f', you can use it inline. E.g: Serial.print( EEPROM.get( eeAddress, f ) ); ***/ /*** Get can be used with custom structures too. I have separated this into an extra function. ***/ secondTest(); //Run the next test. } void secondTest() { int eeAddress = sizeof(float); //Move address to the next byte after float 'f'. MyObject customVar; //Variable to store custom object read from EEPROM. EEPROM.get(eeAddress, customVar); Serial.println("Read custom object from EEPROM: "); Serial.println(customVar.field1); Serial.println(customVar.field2); Serial.println(customVar.name); } Nothing happens in the loop. void loop() { /* Empty loop */ }
[ { "code": null, "e": 1344, "s": 1062, "text": "Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data." }, { "code": null, "e": 1563, "s": 1344, "text": "In this article, we will see how to get data of any size (not just a byte) from the EEPROM. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from − File → Examples → EEPROM." }, { "code": null, "e": 1791, "s": 1563, "text": "We will look at the eeprom_get example. This example assumes that you've pre-set the data in Arduino's EEPROM by running the code in the eeprom_put example. In other words, the eeprom_put example is a precursor to this example." }, { "code": null, "e": 2248, "s": 1791, "text": "The main function of interest is EEPROM.get(). It takes two arguments, the starting address from which to start reading data, and the variable in which the read data is to be stored (which can be of a primitive type, like float, or a custom struct). Examples of other primitive data types are short, int, long, char, double, etc. This function determines the number of bytes to read based on the size of the variable in which the read data is to be stored." }, { "code": null, "e": 2292, "s": 2248, "text": "We begin with the inclusion of the library." }, { "code": null, "e": 2312, "s": 2292, "text": "#include <EEPROM.h>" }, { "code": null, "e": 2364, "s": 2312, "text": "There is a global struct defined later in the code." }, { "code": null, "e": 2436, "s": 2364, "text": "struct MyObject {\n float field1;\n byte field2;\n char name[10];\n};" }, { "code": null, "e": 2782, "s": 2436, "text": "Within the Setup, we first initialize Serial, and read a float from the beginning of the EEPROM (address = 0). We then read a struct in the secondTest() function (where we first move the EEPROM read address by the size of a float, then create an object of the type struct, and read into it. We then print the fields within the struct one by one." }, { "code": null, "e": 3971, "s": 2782, "text": "void setup() {\n float f = 0.00f; //Variable to store data read from EEPROM.\n int eeAddress = 0; //EEPROM address to start reading from\n\n Serial.begin(9600);\n while (!Serial) {\n ; // wait for serial port to connect. Needed for native USB port only\n }\n Serial.print(\"Read float from EEPROM: \");\n\n //Get the float data from the EEPROM at position 'eeAddress' EEPROM.get(eeAddress, f);\n Serial.println(f, 3); //This may print 'ovf, nan' if the data inside the EEPROM is not a valid float.\n\n /***\n As get also returns a reference to 'f', you can use it inline.\n E.g: Serial.print( EEPROM.get( eeAddress, f ) );\n ***/\n /***\n Get can be used with custom structures too.\n I have separated this into an extra function.\n ***/\n\n secondTest(); //Run the next test.\n}\n\nvoid secondTest() {\n int eeAddress = sizeof(float); //Move address to the next byte after float 'f'.\n MyObject customVar; //Variable to store custom object read from EEPROM.\n EEPROM.get(eeAddress, customVar);\n\n Serial.println(\"Read custom object from EEPROM: \");\n Serial.println(customVar.field1);\n Serial.println(customVar.field2);\n Serial.println(customVar.name);\n}" }, { "code": null, "e": 4000, "s": 3971, "text": "Nothing happens in the loop." }, { "code": null, "e": 4036, "s": 4000, "text": "void loop() {\n /* Empty loop */\n}" } ]
How to visualize high frequency financial data using Plotly and R | by Pedro Lealdino Filho | Towards Data Science
In this article I show how to use the Plotly package to visualize financial data in high frequency using R. To perform analysis and develop trading algorithms, it is necessary to obtain data in very high frequencies to be able to take quick and accurate actions to maximize the profits earned in the trades. Today, more than 40% of the operations carried out on American stock exchanges are carried out by robots programmed to analyze the market and buy or sell according to market indicators. Today we are going to learn how to create a candlestick chart from a Brazilian asset data called “mini-index,” widely used by daytraders. There are several ways to collect high-frequency data from the exchange. But today, since we will not analyze the data in real-time, we will collect the data using Metatrader, a tool for conducting free trades, which enables the purchase and sale of assets. The first step is to open the tool and choose the asset from which we want to collect it. In our case, it is June, and the mini-index asset for that month is WINM20. After selecting the asset, we choose the chart’s time frame. Please select the time of one minute so that we can collect the data in seconds. After, click on file and save. The asset data will be saved in .csv format.Ready, data collection is done! Let’s go to the data processing! I use R, a powerful and free statistical programming language, along with some graphic libraries to perform my analysis. After opening RStudio, I create a. RScript file. We started by importing the necessary libraries library(plotly) #para plotar os gráficoslibrary(xts) #para trabalhar com dados de séries temporaislibrary(tidyverse) #jeito magnífico de trabalhar com dados Afterwards, we import the data of our asset that is named “WINM20M1.csv” data <- read.csv("WINM20M1.csv", header = FALSE, sep = ",", fileEncoding = "UTF-16LE", dec = ".")head(data) We see seven variables that have no name yet. Thus, we create a vector with the name of the variables using the OHLC standard (Open, High, Low, Close) and assign this vector to the name of the data.frame columns. colnames_ <- c("Date", "Open", "High", "Low", "Close", "Tick", "Volume") colnames(data) <- colnames_head(data) Now that we have our data appropriately renamed, we need to change the type of the variable, Date, to type Date. But before changing it, we must make a change to the string to replace the “.” per “-” . data$Date <- gsub("\\.", "-", data$Date)data$Date <- as.POSIXct(data$Date)head(data) Okay, now for the data visualization. Finally, to visualize the data, we use the Plotly library, perfect for this type of task. First, we create a fig variable to store our graph. I will only use the last 20 minutes so that the visualization is not too dense fig <- tail(data, 20) %>% plot_ly(x = ~Date, type = "candlestick", open = ~Open, close = ~Close, high = ~High, low = ~Low)fig <- fig %>% layout(title = "Candles de Mini Ídice")fig Voilà! Questions or comments, please contact! Hug! Don’t forget to subscribe to our newsletter to receive weekly content on data science, mathematics, and finance.
[ { "code": null, "e": 480, "s": 172, "text": "In this article I show how to use the Plotly package to visualize financial data in high frequency using R. To perform analysis and develop trading algorithms, it is necessary to obtain data in very high frequencies to be able to take quick and accurate actions to maximize the profits earned in the trades." }, { "code": null, "e": 804, "s": 480, "text": "Today, more than 40% of the operations carried out on American stock exchanges are carried out by robots programmed to analyze the market and buy or sell according to market indicators. Today we are going to learn how to create a candlestick chart from a Brazilian asset data called “mini-index,” widely used by daytraders." }, { "code": null, "e": 1062, "s": 804, "text": "There are several ways to collect high-frequency data from the exchange. But today, since we will not analyze the data in real-time, we will collect the data using Metatrader, a tool for conducting free trades, which enables the purchase and sale of assets." }, { "code": null, "e": 1228, "s": 1062, "text": "The first step is to open the tool and choose the asset from which we want to collect it. In our case, it is June, and the mini-index asset for that month is WINM20." }, { "code": null, "e": 1370, "s": 1228, "text": "After selecting the asset, we choose the chart’s time frame. Please select the time of one minute so that we can collect the data in seconds." }, { "code": null, "e": 1510, "s": 1370, "text": "After, click on file and save. The asset data will be saved in .csv format.Ready, data collection is done! Let’s go to the data processing!" }, { "code": null, "e": 1680, "s": 1510, "text": "I use R, a powerful and free statistical programming language, along with some graphic libraries to perform my analysis. After opening RStudio, I create a. RScript file." }, { "code": null, "e": 1728, "s": 1680, "text": "We started by importing the necessary libraries" }, { "code": null, "e": 1888, "s": 1728, "text": "library(plotly) #para plotar os gráficoslibrary(xts) #para trabalhar com dados de séries temporaislibrary(tidyverse) #jeito magnífico de trabalhar com dados" }, { "code": null, "e": 1961, "s": 1888, "text": "Afterwards, we import the data of our asset that is named “WINM20M1.csv”" }, { "code": null, "e": 2069, "s": 1961, "text": "data <- read.csv(\"WINM20M1.csv\", header = FALSE, sep = \",\", fileEncoding = \"UTF-16LE\", dec = \".\")head(data)" }, { "code": null, "e": 2282, "s": 2069, "text": "We see seven variables that have no name yet. Thus, we create a vector with the name of the variables using the OHLC standard (Open, High, Low, Close) and assign this vector to the name of the data.frame columns." }, { "code": null, "e": 2355, "s": 2282, "text": "colnames_ <- c(\"Date\", \"Open\", \"High\", \"Low\", \"Close\", \"Tick\", \"Volume\")" }, { "code": null, "e": 2393, "s": 2355, "text": "colnames(data) <- colnames_head(data)" }, { "code": null, "e": 2595, "s": 2393, "text": "Now that we have our data appropriately renamed, we need to change the type of the variable, Date, to type Date. But before changing it, we must make a change to the string to replace the “.” per “-” ." }, { "code": null, "e": 2680, "s": 2595, "text": "data$Date <- gsub(\"\\\\.\", \"-\", data$Date)data$Date <- as.POSIXct(data$Date)head(data)" }, { "code": null, "e": 2718, "s": 2680, "text": "Okay, now for the data visualization." }, { "code": null, "e": 2939, "s": 2718, "text": "Finally, to visualize the data, we use the Plotly library, perfect for this type of task. First, we create a fig variable to store our graph. I will only use the last 20 minutes so that the visualization is not too dense" }, { "code": null, "e": 3139, "s": 2939, "text": "fig <- tail(data, 20) %>% plot_ly(x = ~Date, type = \"candlestick\", open = ~Open, close = ~Close, high = ~High, low = ~Low)fig <- fig %>% layout(title = \"Candles de Mini Ídice\")fig" }, { "code": null, "e": 3147, "s": 3139, "text": "Voilà!" } ]
Order by last 3 chars in MySQL?
You can use ORDER BY RIGHT() function to order by last 3 chars in MySQL. The syntax is as follows − SELECT *FROM yourTableName ORDER BY RIGHT(yourColumnName,3) yourSortingOrder; Just replace the ‘yourSortingOrder’ to ASC or DESC to set the ascending or descending order respectively. To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table OrderByLast3Chars -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT, -> EmployeeName varchar(20), -> EmployeeAge int, -> PRIMARY KEY(EmployeeId) -> ); Query OK, 0 rows affected (0.56 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Carol_901',24); Query OK, 1 row affected (0.14 sec) mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Bob_101',21); Query OK, 1 row affected (0.19 sec) mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Sam_107',22); Query OK, 1 row affected (0.20 sec) mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Mile_677',26); Query OK, 1 row affected (0.19 sec) mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('John_978',27); Query OK, 1 row affected (0.75 sec) mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('David_876',29); Query OK, 1 row affected (0.28 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from OrderByLast3Chars; The following is the output − +------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | Carol_901 | 24 | | 2 | Bob_101 | 21 | | 3 | Sam_107 | 22 | | 4 | Mile_677 | 26 | | 5 | John_978 | 27 | | 6 | David_876 | 29 | +------------+--------------+-------------+ 6 rows in set (0.00 sec) Here is the query to order by last 3 chars. Case 1 − Get the result in ascending order. The query is as follows − mysql> select *from OrderByLast3Chars -> order by RIGHT(EmployeeName,3) asc; The following is the output − +------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | Carol_901 | 24 | | 2 | Bob_101 | 21 | | 3 | Sam_107 | 22 | | 4 | Mile_677 | 26 | | 5 | John_978 | 27 | | 6 | David_876 | 29 | +------------+--------------+-------------+ 6 rows in set (0.00 sec) Case 2 − Get the result in descending order. The query is as follows − mysql> select *from OrderByLast3Chars -> order by RIGHT(EmployeeName,3) desc; The following is the output − +------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 5 | John_978 | 27 | | 1 | Carol_901 | 24 | | 6 | David_876 | 29 | | 4 | Mile_677 | 26 | | 3 | Sam_107 | 22 | | 2 | Bob_101 | 21 | +------------+--------------+-------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1162, "s": 1062, "text": "You can use ORDER BY RIGHT() function to order by last 3 chars in MySQL. The syntax is as follows −" }, { "code": null, "e": 1240, "s": 1162, "text": "SELECT *FROM yourTableName\nORDER BY RIGHT(yourColumnName,3) yourSortingOrder;" }, { "code": null, "e": 1346, "s": 1240, "text": "Just replace the ‘yourSortingOrder’ to ASC or DESC to set the ascending or descending order respectively." }, { "code": null, "e": 1445, "s": 1346, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1668, "s": 1445, "text": "mysql> create table OrderByLast3Chars\n -> (\n -> EmployeeId int NOT NULL AUTO_INCREMENT,\n -> EmployeeName varchar(20),\n -> EmployeeAge int,\n -> PRIMARY KEY(EmployeeId)\n -> );\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1749, "s": 1668, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2486, "s": 1749, "text": "mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Carol_901',24);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Bob_101',21);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Sam_107',22);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Mile_677',26);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('John_978',27);\nQuery OK, 1 row affected (0.75 sec)\n\nmysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('David_876',29);\nQuery OK, 1 row affected (0.28 sec)" }, { "code": null, "e": 2571, "s": 2486, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2610, "s": 2571, "text": "mysql> select *from OrderByLast3Chars;" }, { "code": null, "e": 2640, "s": 2610, "text": "The following is the output −" }, { "code": null, "e": 3105, "s": 2640, "text": "+------------+--------------+-------------+\n| EmployeeId | EmployeeName | EmployeeAge |\n+------------+--------------+-------------+\n| 1 | Carol_901 | 24 |\n| 2 | Bob_101 | 21 |\n| 3 | Sam_107 | 22 |\n| 4 | Mile_677 | 26 |\n| 5 | John_978 | 27 |\n| 6 | David_876 | 29 |\n+------------+--------------+-------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3149, "s": 3105, "text": "Here is the query to order by last 3 chars." }, { "code": null, "e": 3193, "s": 3149, "text": "Case 1 − Get the result in ascending order." }, { "code": null, "e": 3219, "s": 3193, "text": "The query is as follows −" }, { "code": null, "e": 3299, "s": 3219, "text": "mysql> select *from OrderByLast3Chars\n -> order by RIGHT(EmployeeName,3) asc;" }, { "code": null, "e": 3329, "s": 3299, "text": "The following is the output −" }, { "code": null, "e": 3794, "s": 3329, "text": "+------------+--------------+-------------+\n| EmployeeId | EmployeeName | EmployeeAge |\n+------------+--------------+-------------+\n| 1 | Carol_901 | 24 |\n| 2 | Bob_101 | 21 |\n| 3 | Sam_107 | 22 |\n| 4 | Mile_677 | 26 |\n| 5 | John_978 | 27 |\n| 6 | David_876 | 29 |\n+------------+--------------+-------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3865, "s": 3794, "text": "Case 2 − Get the result in descending order. The query is as follows −" }, { "code": null, "e": 3946, "s": 3865, "text": "mysql> select *from OrderByLast3Chars\n -> order by RIGHT(EmployeeName,3) desc;" }, { "code": null, "e": 3976, "s": 3946, "text": "The following is the output −" }, { "code": null, "e": 4441, "s": 3976, "text": "+------------+--------------+-------------+\n| EmployeeId | EmployeeName | EmployeeAge |\n+------------+--------------+-------------+\n| 5 | John_978 | 27 |\n| 1 | Carol_901 | 24 |\n| 6 | David_876 | 29 |\n| 4 | Mile_677 | 26 |\n| 3 | Sam_107 | 22 |\n| 2 | Bob_101 | 21 |\n+------------+--------------+-------------+\n6 rows in set (0.00 sec)" } ]
Euphoria - Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Euphoria has some standard types that are used to define the operations possible on them and the storage method for each of them. Euphoria has following four standard data types − integer atom sequence object The understanding of atoms and sequences is the key to understanding Euphoria. Euphoria integer data types store numeric values. They are declared and defined as follows − integer var1, var2 var1 = 1 var2 = 100 The variables declared with type integer must be atoms with integer values from -1073741824 to +1073741823 inclusive. You can perform exact calculations on larger integer values, up to about 15 decimal digits, but declare them as atom, rather than integer. All data objects in Euphoria are either atoms or sequences. An atom is a single numeric value. Atoms can have any integer or double-precision floating point value. Euphoria atoms are declared and defined as follows− atom var1, var2, var3 var1 = 1000 var2 = 198.6121324234 var3 = 'E' The atoms can range from approximately -1e300 to +1e300 with 15 decimal digits of accuracy. An individual character is an atom which must may be entered using single quotes. For example, all the following statements are legal − -- Following is equivalent to the atom 66 - the ASCII code for B char = 'B' -- Following is equivalent to the sequence {66} sentence = "B" A sequence is a collection of numeric values which can be accessed through their index. All data objects in Euphoria are either atoms or sequences. Sequence index starts from 1 unlike other programming languages where array index starts from 0. Euphoria sequences are declared and defined as follows − sequence var1, var2, var3, var4 var1 = {2, 3, 5, 7, 11, 13, 17, 19} var2 = {1, 2, {3, 3, 3}, 4, {5, {6}}} var3 = {{"zara", "ali"}, 52389, 97.25} var4 = {} -- the 0 element sequence A character string is just a sequence of characters which may be entered using double quotes. For example, all the following statements are legal − word = 'word' sentence = "ABCDEFG" Character strings may be manipulated and operated upon just like any other sequences. For example, the above string is entirely equivalent to the sequence − sentence = {65, 66, 67, 68, 69, 70, 71} You will learn more about sequence in Euphoria − Sequences. This is a super data type in Euphoria which may take on any value including atoms, sequences, or integers. Euphoria objects are declared and defined as follows − object var1, var2, var3 var1 = {2, 3, 5, 7, 11, 13, 17, 19} var2 = 100 var3 = 'E' An object may have one of the following values − a sequence a sequence an atom an atom an integer an integer an integer used as a file number an integer used as a file number a string sequence, or single-character atom a string sequence, or single-character atom Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 1967, "text": "The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters." }, { "code": null, "e": 2263, "s": 2133, "text": "Euphoria has some standard types that are used to define the operations possible on them and the storage method for each of them." }, { "code": null, "e": 2313, "s": 2263, "text": "Euphoria has following four standard data types −" }, { "code": null, "e": 2321, "s": 2313, "text": "integer" }, { "code": null, "e": 2326, "s": 2321, "text": "atom" }, { "code": null, "e": 2335, "s": 2326, "text": "sequence" }, { "code": null, "e": 2342, "s": 2335, "text": "object" }, { "code": null, "e": 2421, "s": 2342, "text": "The understanding of atoms and sequences is the key to understanding Euphoria." }, { "code": null, "e": 2514, "s": 2421, "text": "Euphoria integer data types store numeric values. They are declared and defined as follows −" }, { "code": null, "e": 2554, "s": 2514, "text": "integer var1, var2\n\nvar1 = 1\nvar2 = 100" }, { "code": null, "e": 2811, "s": 2554, "text": "The variables declared with type integer must be atoms with integer values from -1073741824 to +1073741823 inclusive. You can perform exact calculations on larger integer values, up to about 15 decimal digits, but declare them as atom, rather than integer." }, { "code": null, "e": 3027, "s": 2811, "text": "All data objects in Euphoria are either atoms or sequences. An atom is a single numeric value. Atoms can have any integer or double-precision floating point value. Euphoria atoms are declared and defined as follows−" }, { "code": null, "e": 3102, "s": 3027, "text": "atom var1, var2, var3\n\nvar1 = 1000\nvar2 = 198.6121324234\nvar3 = 'E' " }, { "code": null, "e": 3330, "s": 3102, "text": "The atoms can range from approximately -1e300 to +1e300 with 15 decimal digits of accuracy. An individual character is an atom which must may be entered using single quotes. For example, all the following statements are legal −" }, { "code": null, "e": 3471, "s": 3330, "text": "-- Following is equivalent to the atom 66 - the ASCII code for B\nchar = 'B'\n\n-- Following is equivalent to the sequence {66}\nsentence = \"B\"\n" }, { "code": null, "e": 3619, "s": 3471, "text": "A sequence is a collection of numeric values which can be accessed through their index. All data objects in Euphoria are either atoms or sequences." }, { "code": null, "e": 3773, "s": 3619, "text": "Sequence index starts from 1 unlike other programming languages where array index starts from 0. Euphoria sequences are declared and defined as follows −" }, { "code": null, "e": 3960, "s": 3773, "text": "sequence var1, var2, var3, var4\n\nvar1 = {2, 3, 5, 7, 11, 13, 17, 19}\nvar2 = {1, 2, {3, 3, 3}, 4, {5, {6}}}\nvar3 = {{\"zara\", \"ali\"}, 52389, 97.25} \nvar4 = {} -- the 0 element sequence" }, { "code": null, "e": 4108, "s": 3960, "text": "A character string is just a sequence of characters which may be entered using double quotes. For example, all the following statements are legal −" }, { "code": null, "e": 4143, "s": 4108, "text": "word = 'word'\nsentence = \"ABCDEFG\"" }, { "code": null, "e": 4300, "s": 4143, "text": "Character strings may be manipulated and operated upon just like any other sequences. For example, the above string is entirely equivalent to the sequence −" }, { "code": null, "e": 4340, "s": 4300, "text": "sentence = {65, 66, 67, 68, 69, 70, 71}" }, { "code": null, "e": 4400, "s": 4340, "text": "You will learn more about sequence in Euphoria − Sequences." }, { "code": null, "e": 4562, "s": 4400, "text": "This is a super data type in Euphoria which may take on any value including atoms, sequences, or integers. Euphoria objects are declared and defined as follows −" }, { "code": null, "e": 4650, "s": 4562, "text": "object var1, var2, var3\n\nvar1 = {2, 3, 5, 7, 11, 13, 17, 19}\nvar2 = 100\nvar3 = 'E' " }, { "code": null, "e": 4699, "s": 4650, "text": "An object may have one of the following values −" }, { "code": null, "e": 4710, "s": 4699, "text": "a sequence" }, { "code": null, "e": 4721, "s": 4710, "text": "a sequence" }, { "code": null, "e": 4729, "s": 4721, "text": "an atom" }, { "code": null, "e": 4737, "s": 4729, "text": "an atom" }, { "code": null, "e": 4748, "s": 4737, "text": "an integer" }, { "code": null, "e": 4759, "s": 4748, "text": "an integer" }, { "code": null, "e": 4792, "s": 4759, "text": "an integer used as a file number" }, { "code": null, "e": 4825, "s": 4792, "text": "an integer used as a file number" }, { "code": null, "e": 4869, "s": 4825, "text": "a string sequence, or single-character atom" }, { "code": null, "e": 4913, "s": 4869, "text": "a string sequence, or single-character atom" }, { "code": null, "e": 4920, "s": 4913, "text": " Print" }, { "code": null, "e": 4931, "s": 4920, "text": " Add Notes" } ]
Change Axis Labels of Boxplot in R - GeeksforGeeks
06 Jun, 2021 A box graph is a chart that is used to display information in the form of distribution by drawing boxplots for each of them. Boxplots help us to visualize the distribution of the data by quartile and detect the presence of outliers. Adding axis labels for Boxplot will help the readability of the boxplot. In this article, we will discuss how to change the axis labels of boxplot in R Programming Language. Boxplots are created in R Programming Language by using the boxplot() function. Syntax: boxplot(x, data, notch, varwidth, names, main) Parameters: x: This parameter sets as a vector or a formula. data: This parameter sets the data frame. notch: This parameter is the label for horizontal axis. varwidth: This parameter is a logical value. Set as true to draw width of the box proportionate to the sample size. main: This parameter is the title of the chart. names: This parameter are the group labels that will be showed under each boxplot. If made with basic R, we use the names parameter of the boxplot() function. For this boxplot data, has to be first initialized and the name which has to be added to axis is passed as vector. Then boxplot() is called with data and names parameter set to this vector. Example: R # sample data for plottinggeeksforgeeks=c(120,26,39,49,15)scripter=c(115,34,30,92,81)writer=c(100,20,15,32,23) # labels for Axislabel=c("geeksforgeeks","scripter","writer") # boxplot with names parameter for labelsboxplot(geeksforgeeks, scripter, writer, names=label) Output: Boxplot with Axis Label This can also be done to Horizontal boxplots very easily. To convert this to horizontal boxplot add parameter Horizontal=True and rest of the task remains the same. For this, labels will appear on y-axis. Example: R # sample data for plottinggeeksforgeeks=c(120,26,39,49,15)scripter=c(115,34,30,92,81)writer=c(100,20,15,32,23) # labels for Axislabel=c("geeksforgeeks","scripter","writer") # boxplot with names parameter for labelsboxplot(geeksforgeeks, scripter, writer, names=label, horizontal=TRUE) Output: Horizontal boxplot with changed labels If made with ggplot2, we change the label data in our dataset itself before drawing the boxplot. Reshape module is used to convert sample data from wide format to long format and ggplot2 will be used to draw boxplot. After data is created, convert data from wide format to long format using melt function. Now, change the variable name in the dataset and simply draw the boxplot. Example: R # load package reshape2 and ggplot2library("reshape2") library("ggplot2") # Create sample data set.seed(97364) sample <- data.frame(x1 = rnorm(200), x2 = rnorm(200, 2), x3 = rnorm(200, 3, 3)) # Reshape sample data to long formsample_main <- melt(sample) # Add variable parameter for axis label in datasetlevels(sample_main$variable) <- c("geeksforgeeks","scripter","writer") # Draw boxplotggplot(sample_main, aes(variable, value)) + geom_boxplot() Output: Boxplot with changed label This can be done to Horizontal boxplots very easily. To convert this to Horizontal Boxplot add coord_flip() in the boxplot code, and rest remains the same as above. Syntax: geom_boxplot() + coord_flip() Example: R # load package reshape2 and ggplot2library("reshape2") library("ggplot2") # Create sample data set.seed(97364) sample <- data.frame(x1 = rnorm(200), x2 = rnorm(200, 2), x3 = rnorm(200, 3, 3)) # Reshape sample data to long formsample_main <- melt(sample) # Add variable parameter for axis label in datasetlevels(sample_main$variable) <- c("geeksforgeeks","scripter","writer") # Draw boxplotggplot(sample_main, aes(variable, value)) + geom_boxplot() + coord_flip() Output: Horizontal boxplot using ggplot2 with changed label Picked R-Charts R-ggplot R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24877, "s": 24849, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25183, "s": 24877, "text": "A box graph is a chart that is used to display information in the form of distribution by drawing boxplots for each of them. Boxplots help us to visualize the distribution of the data by quartile and detect the presence of outliers. Adding axis labels for Boxplot will help the readability of the boxplot." }, { "code": null, "e": 25284, "s": 25183, "text": "In this article, we will discuss how to change the axis labels of boxplot in R Programming Language." }, { "code": null, "e": 25364, "s": 25284, "text": "Boxplots are created in R Programming Language by using the boxplot() function." }, { "code": null, "e": 25372, "s": 25364, "text": "Syntax:" }, { "code": null, "e": 25419, "s": 25372, "text": "boxplot(x, data, notch, varwidth, names, main)" }, { "code": null, "e": 25431, "s": 25419, "text": "Parameters:" }, { "code": null, "e": 25480, "s": 25431, "text": "x: This parameter sets as a vector or a formula." }, { "code": null, "e": 25522, "s": 25480, "text": "data: This parameter sets the data frame." }, { "code": null, "e": 25578, "s": 25522, "text": "notch: This parameter is the label for horizontal axis." }, { "code": null, "e": 25694, "s": 25578, "text": "varwidth: This parameter is a logical value. Set as true to draw width of the box proportionate to the sample size." }, { "code": null, "e": 25742, "s": 25694, "text": "main: This parameter is the title of the chart." }, { "code": null, "e": 25825, "s": 25742, "text": "names: This parameter are the group labels that will be showed under each boxplot." }, { "code": null, "e": 26092, "s": 25825, "text": "If made with basic R, we use the names parameter of the boxplot() function. For this boxplot data, has to be first initialized and the name which has to be added to axis is passed as vector. Then boxplot() is called with data and names parameter set to this vector. " }, { "code": null, "e": 26101, "s": 26092, "text": "Example:" }, { "code": null, "e": 26103, "s": 26101, "text": "R" }, { "code": "# sample data for plottinggeeksforgeeks=c(120,26,39,49,15)scripter=c(115,34,30,92,81)writer=c(100,20,15,32,23) # labels for Axislabel=c(\"geeksforgeeks\",\"scripter\",\"writer\") # boxplot with names parameter for labelsboxplot(geeksforgeeks, scripter, writer, names=label)", "e": 26373, "s": 26103, "text": null }, { "code": null, "e": 26381, "s": 26373, "text": "Output:" }, { "code": null, "e": 26405, "s": 26381, "text": "Boxplot with Axis Label" }, { "code": null, "e": 26610, "s": 26405, "text": "This can also be done to Horizontal boxplots very easily. To convert this to horizontal boxplot add parameter Horizontal=True and rest of the task remains the same. For this, labels will appear on y-axis." }, { "code": null, "e": 26619, "s": 26610, "text": "Example:" }, { "code": null, "e": 26621, "s": 26619, "text": "R" }, { "code": "# sample data for plottinggeeksforgeeks=c(120,26,39,49,15)scripter=c(115,34,30,92,81)writer=c(100,20,15,32,23) # labels for Axislabel=c(\"geeksforgeeks\",\"scripter\",\"writer\") # boxplot with names parameter for labelsboxplot(geeksforgeeks, scripter, writer, names=label, horizontal=TRUE)", "e": 26916, "s": 26621, "text": null }, { "code": null, "e": 26924, "s": 26916, "text": "Output:" }, { "code": null, "e": 26963, "s": 26924, "text": "Horizontal boxplot with changed labels" }, { "code": null, "e": 27060, "s": 26963, "text": "If made with ggplot2, we change the label data in our dataset itself before drawing the boxplot." }, { "code": null, "e": 27343, "s": 27060, "text": "Reshape module is used to convert sample data from wide format to long format and ggplot2 will be used to draw boxplot. After data is created, convert data from wide format to long format using melt function. Now, change the variable name in the dataset and simply draw the boxplot." }, { "code": null, "e": 27352, "s": 27343, "text": "Example:" }, { "code": null, "e": 27354, "s": 27352, "text": "R" }, { "code": "# load package reshape2 and ggplot2library(\"reshape2\") library(\"ggplot2\") # Create sample data set.seed(97364) sample <- data.frame(x1 = rnorm(200), x2 = rnorm(200, 2), x3 = rnorm(200, 3, 3)) # Reshape sample data to long formsample_main <- melt(sample) # Add variable parameter for axis label in datasetlevels(sample_main$variable) <- c(\"geeksforgeeks\",\"scripter\",\"writer\") # Draw boxplotggplot(sample_main, aes(variable, value)) + geom_boxplot()", "e": 27872, "s": 27354, "text": null }, { "code": null, "e": 27880, "s": 27872, "text": "Output:" }, { "code": null, "e": 27907, "s": 27880, "text": "Boxplot with changed label" }, { "code": null, "e": 28072, "s": 27907, "text": "This can be done to Horizontal boxplots very easily. To convert this to Horizontal Boxplot add coord_flip() in the boxplot code, and rest remains the same as above." }, { "code": null, "e": 28081, "s": 28072, "text": "Syntax: " }, { "code": null, "e": 28111, "s": 28081, "text": "geom_boxplot() + coord_flip()" }, { "code": null, "e": 28120, "s": 28111, "text": "Example:" }, { "code": null, "e": 28122, "s": 28120, "text": "R" }, { "code": "# load package reshape2 and ggplot2library(\"reshape2\") library(\"ggplot2\") # Create sample data set.seed(97364) sample <- data.frame(x1 = rnorm(200), x2 = rnorm(200, 2), x3 = rnorm(200, 3, 3)) # Reshape sample data to long formsample_main <- melt(sample) # Add variable parameter for axis label in datasetlevels(sample_main$variable) <- c(\"geeksforgeeks\",\"scripter\",\"writer\") # Draw boxplotggplot(sample_main, aes(variable, value)) + geom_boxplot() + coord_flip()", "e": 28655, "s": 28122, "text": null }, { "code": null, "e": 28663, "s": 28655, "text": "Output:" }, { "code": null, "e": 28715, "s": 28663, "text": "Horizontal boxplot using ggplot2 with changed label" }, { "code": null, "e": 28722, "s": 28715, "text": "Picked" }, { "code": null, "e": 28731, "s": 28722, "text": "R-Charts" }, { "code": null, "e": 28740, "s": 28731, "text": "R-ggplot" }, { "code": null, "e": 28749, "s": 28740, "text": "R-Graphs" }, { "code": null, "e": 28757, "s": 28749, "text": "R-plots" }, { "code": null, "e": 28768, "s": 28757, "text": "R Language" }, { "code": null, "e": 28866, "s": 28768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28875, "s": 28866, "text": "Comments" }, { "code": null, "e": 28888, "s": 28875, "text": "Old Comments" }, { "code": null, "e": 28940, "s": 28888, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28978, "s": 28940, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29013, "s": 28978, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29071, "s": 29013, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29114, "s": 29071, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29163, "s": 29114, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29213, "s": 29163, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29230, "s": 29213, "text": "R - if statement" }, { "code": null, "e": 29267, "s": 29230, "text": "How to import an Excel File into R ?" } ]
Python - Move() function in wxPython - GeeksforGeeks
10 May, 2020 In this particular article we will learn, how can we move our window to a particular point. This can be achieved using Move() function in wx.Window class of wxPython.Move() takes x and y points to move window to a particularx, y point. Syntax : wx.Move(self, x, y, flags=SIZE_USE_EXISTING) Parameters : Code Example #1: # import wxPythonimport wx # frame classclass MoveWindow(wx.Frame): def __init__(self, parent, title): super(MoveWindow, self).__init__(parent, title = title, size =(300, 200)) # move window using Move() function self.Move((500, 250)) def main(): app = wx.App() move = MoveWindow(None, title ='Move()') move.Show() app.MainLoop() if __name__ == '__main__': main() Output: Code Example #2: # import wxPythonimport wx # frame classclass MoveWindow(wx.Frame): def __init__(self, parent, title): super(MoveWindow, self).__init__(parent, title = title, size =(300, 200)) # move window to (900, 600) using Move() function self.Move((900, 600)) def main(): app = wx.App() move = MoveWindow(None, title ='Move()') move.Show() app.MainLoop() if __name__ == '__main__': main() Output: Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24212, "s": 24184, "text": "\n10 May, 2020" }, { "code": null, "e": 24448, "s": 24212, "text": "In this particular article we will learn, how can we move our window to a particular point. This can be achieved using Move() function in wx.Window class of wxPython.Move() takes x and y points to move window to a particularx, y point." }, { "code": null, "e": 24457, "s": 24448, "text": "Syntax :" }, { "code": null, "e": 24503, "s": 24457, "text": "wx.Move(self, x, y, flags=SIZE_USE_EXISTING)\n" }, { "code": null, "e": 24516, "s": 24503, "text": "Parameters :" }, { "code": null, "e": 24533, "s": 24516, "text": "Code Example #1:" }, { "code": "# import wxPythonimport wx # frame classclass MoveWindow(wx.Frame): def __init__(self, parent, title): super(MoveWindow, self).__init__(parent, title = title, size =(300, 200)) # move window using Move() function self.Move((500, 250)) def main(): app = wx.App() move = MoveWindow(None, title ='Move()') move.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 24957, "s": 24533, "text": null }, { "code": null, "e": 24965, "s": 24957, "text": "Output:" }, { "code": null, "e": 24982, "s": 24965, "text": "Code Example #2:" }, { "code": "# import wxPythonimport wx # frame classclass MoveWindow(wx.Frame): def __init__(self, parent, title): super(MoveWindow, self).__init__(parent, title = title, size =(300, 200)) # move window to (900, 600) using Move() function self.Move((900, 600)) def main(): app = wx.App() move = MoveWindow(None, title ='Move()') move.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 25420, "s": 24982, "text": null }, { "code": null, "e": 25428, "s": 25420, "text": "Output:" }, { "code": null, "e": 25439, "s": 25428, "text": "Python-gui" }, { "code": null, "e": 25455, "s": 25439, "text": "Python-wxPython" }, { "code": null, "e": 25462, "s": 25455, "text": "Python" }, { "code": null, "e": 25560, "s": 25462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25569, "s": 25560, "text": "Comments" }, { "code": null, "e": 25582, "s": 25569, "text": "Old Comments" }, { "code": null, "e": 25614, "s": 25582, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25669, "s": 25614, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25725, "s": 25669, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25764, "s": 25725, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25806, "s": 25764, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25848, "s": 25806, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25879, "s": 25848, "text": "Python | os.path.join() method" }, { "code": null, "e": 25901, "s": 25879, "text": "Defaultdict in Python" }, { "code": null, "e": 25930, "s": 25901, "text": "Create a directory in Python" } ]
Python - Extract Dictionary values list to List - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with dictionary records, we can have problems in which we need to extract all the dictionary values into a single separate list. This can have possible application in data domains and web-development. Lets discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expressionThe combination of above functionalities can be used to solve this problem. In this, we perform the task of extraction of values using generator expression and map() is used to reconstruct the value lists. # Python3 code to demonstrate working of # Extracting Dictionary values list to List# Using map() + generator expression # initializing dictionarytest_dict = {'gfg' : [4, 6, 7, 8], 'is' : [3, 8, 4, 2, 1], 'best' : [9, 5, 2, 1, 0]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Extracting Dictionary values to List# Using map() + generator expressionres = list(map(list, (ele for ele in test_dict.values()))) # printing result print("The list of dictionary values : " + str(res)) The original dictionary is : {‘is’: [3, 8, 4, 2, 1], ‘gfg’: [4, 6, 7, 8], ‘best’: [9, 5, 2, 1, 0]}The list of dictionary values : [[3, 8, 4, 2, 1], [4, 6, 7, 8], [9, 5, 2, 1, 0]] Method #2 : Using map()The combination of above functions can be used to solve this problem. In this we perform the task of extraction and remaking using map(). # Python3 code to demonstrate working of # Extracting Dictionary values list to List# Using map() # initializing dictionarytest_dict = {'gfg' : [4, 6, 7, 8], 'is' : [3, 8, 4, 2, 1], 'best' : [9, 5, 2, 1, 0]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Extracting Dictionary values to List# Using map()res = list(map(list, (test_dict.values()))) # printing result print("The list of dictionary values : " + str(res)) The original dictionary is : {‘is’: [3, 8, 4, 2, 1], ‘gfg’: [4, 6, 7, 8], ‘best’: [9, 5, 2, 1, 0]}The list of dictionary values : [[3, 8, 4, 2, 1], [4, 6, 7, 8], [9, 5, 2, 1, 0]] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python? Python | Convert string dictionary to dictionary
[ { "code": null, "e": 26119, "s": 26091, "text": "\n22 Apr, 2020" }, { "code": null, "e": 26408, "s": 26119, "text": "Sometimes, while working with dictionary records, we can have problems in which we need to extract all the dictionary values into a single separate list. This can have possible application in data domains and web-development. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 26660, "s": 26408, "text": "Method #1 : Using map() + generator expressionThe combination of above functionalities can be used to solve this problem. In this, we perform the task of extraction of values using generator expression and map() is used to reconstruct the value lists." }, { "code": "# Python3 code to demonstrate working of # Extracting Dictionary values list to List# Using map() + generator expression # initializing dictionarytest_dict = {'gfg' : [4, 6, 7, 8], 'is' : [3, 8, 4, 2, 1], 'best' : [9, 5, 2, 1, 0]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Extracting Dictionary values to List# Using map() + generator expressionres = list(map(list, (ele for ele in test_dict.values()))) # printing result print(\"The list of dictionary values : \" + str(res)) ", "e": 27214, "s": 26660, "text": null }, { "code": null, "e": 27393, "s": 27214, "text": "The original dictionary is : {‘is’: [3, 8, 4, 2, 1], ‘gfg’: [4, 6, 7, 8], ‘best’: [9, 5, 2, 1, 0]}The list of dictionary values : [[3, 8, 4, 2, 1], [4, 6, 7, 8], [9, 5, 2, 1, 0]]" }, { "code": null, "e": 27556, "s": 27395, "text": "Method #2 : Using map()The combination of above functions can be used to solve this problem. In this we perform the task of extraction and remaking using map()." }, { "code": "# Python3 code to demonstrate working of # Extracting Dictionary values list to List# Using map() # initializing dictionarytest_dict = {'gfg' : [4, 6, 7, 8], 'is' : [3, 8, 4, 2, 1], 'best' : [9, 5, 2, 1, 0]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Extracting Dictionary values to List# Using map()res = list(map(list, (test_dict.values()))) # printing result print(\"The list of dictionary values : \" + str(res)) ", "e": 28049, "s": 27556, "text": null }, { "code": null, "e": 28228, "s": 28049, "text": "The original dictionary is : {‘is’: [3, 8, 4, 2, 1], ‘gfg’: [4, 6, 7, 8], ‘best’: [9, 5, 2, 1, 0]}The list of dictionary values : [[3, 8, 4, 2, 1], [4, 6, 7, 8], [9, 5, 2, 1, 0]]" }, { "code": null, "e": 28255, "s": 28228, "text": "Python dictionary-programs" }, { "code": null, "e": 28262, "s": 28255, "text": "Python" }, { "code": null, "e": 28278, "s": 28262, "text": "Python Programs" }, { "code": null, "e": 28376, "s": 28278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28394, "s": 28376, "text": "Python Dictionary" }, { "code": null, "e": 28426, "s": 28394, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28448, "s": 28426, "text": "Enumerate() in Python" }, { "code": null, "e": 28490, "s": 28448, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28516, "s": 28490, "text": "Python String | replace()" }, { "code": null, "e": 28538, "s": 28516, "text": "Defaultdict in Python" }, { "code": null, "e": 28584, "s": 28538, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28622, "s": 28584, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 28662, "s": 28622, "text": "How to print without newline in Python?" } ]
Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character - GeeksforGeeks
26 Nov, 2020 In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair. Key-value is provided in the dictionary to make it more optimized. Examples: Input: Hello World Output: {'H': ['Hello'], 'W': ['World']} Input: Welcome to GeeksForGeeks Output: {'W': ['Welcome'], 't': ['to'], 'G': ['GeeksForGeeks']} We will save the string in a variable and declare an empty dictionary. Then we will split the string into words and form a list of those words. For each word, we will check if the key for that word is present or not. If it is not then we will add that key and word to the dictionary and if it is already present then we will append that word to that key’s sublist. Below is the implementation of the above approach: Python3 # Python program to Create a Dictionary with Key as First# Character and Value as Words Starting with that Character # Driver Code # Declaring String Datastring_input = '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.''' # Storing words in the input as a listwords = string_input.split() # Declaring empty dictionarydictionary = {} for word in words: # If key is not present in the dictionary then we # will add the key and word to the dictionary. if (word[0] not in dictionary.keys()): # Creating a sublist to store words with same # key value and adding it to the list. dictionary[word[0]] = [] dictionary[word[0]].append(word) # If key is present then checking for the word else: # If word is not present in the sublist then # adding it to the sublist of the proper key # value if (word not in dictionary[word[0]]): dictionary[word[0]].append(word) # Printing the dictionaryprint(dictionary) Output: {'G': ['GeeksforGeeks'], 'i': ['is'], 'a': ['a', 'and', 'articles,'], 'C': ['Computer'], 'S': ['Science'], 'p': ['portal', 'programming'], 'f': ['for'], 'g': ['geeks.'], 'I': ['It'], 'c': ['contains', 'computer'], 'w': ['well', 'written,'], 't': ['thought'], 'e': ['explained', 'etc.'], 's': ['science'], 'q': ['quizzes']} You can see that in the above program’s output the words starting with G have two keys ‘G‘ and ‘g‘ so to remove that issue and make the code case-insensitive we will make use of the lower() function in python. We will save all keys with the lower case so that whenever we will check for the key both the words starting with ‘G‘ and ‘g‘ both will come under the same key. Below is the implementation: Python3 # Python program to Create a Dictionary with Key as First# Character and Value as Words Starting with that Character # Driver Code # Declaring String Datastring_input = '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.''' # Storing words in the input as a listwords = string_input.split() # Declaring empty dictionarydictionary = {} for word in words: # If key is not present in the dictionary then we # will add the key and word to the dictionary. if (word[0].lower() not in dictionary.keys()): # Creating a sublist to store words with same # key value and adding it to the list. dictionary[word[0].lower()] = [] dictionary[word[0].lower()].append(word) # If key is present then checking for the word else: # If word is not present in the sublist then # adding it to the sublist of the proper key # value if (word not in dictionary[word[0].lower()]): dictionary[word[0].lower()].append(word) # Printing the dictionaryprint(dictionary) Output: {'g': ['GeeksforGeeks', 'geeks.'], 'i': ['is', 'It'], 'a': ['a', 'and', 'articles,'], 'c': ['Computer', 'contains', 'computer'], 's': ['Science', 'science'], 'p': ['portal', 'programming'], 'f': ['for'], 'w': ['well', 'written,'], 't': ['thought'], 'e': ['explained', 'etc.'], 'q': ['quizzes']} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Nov, 2020" }, { "code": null, "e": 25692, "s": 25537, "text": "In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character." }, { "code": null, "e": 25974, "s": 25692, "text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair. Key-value is provided in the dictionary to make it more optimized." }, { "code": null, "e": 25984, "s": 25974, "text": "Examples:" }, { "code": null, "e": 26173, "s": 25984, "text": "Input: Hello World\nOutput: {'H': ['Hello'], \n 'W': ['World']}\n\nInput: Welcome to GeeksForGeeks\nOutput: {'W': ['Welcome'], \n 't': ['to'], \n 'G': ['GeeksForGeeks']}\n\n" }, { "code": null, "e": 26244, "s": 26173, "text": "We will save the string in a variable and declare an empty dictionary." }, { "code": null, "e": 26317, "s": 26244, "text": "Then we will split the string into words and form a list of those words." }, { "code": null, "e": 26390, "s": 26317, "text": "For each word, we will check if the key for that word is present or not." }, { "code": null, "e": 26538, "s": 26390, "text": "If it is not then we will add that key and word to the dictionary and if it is already present then we will append that word to that key’s sublist." }, { "code": null, "e": 26589, "s": 26538, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26597, "s": 26589, "text": "Python3" }, { "code": "# Python program to Create a Dictionary with Key as First# Character and Value as Words Starting with that Character # Driver Code # Declaring String Datastring_input = '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.''' # Storing words in the input as a listwords = string_input.split() # Declaring empty dictionarydictionary = {} for word in words: # If key is not present in the dictionary then we # will add the key and word to the dictionary. if (word[0] not in dictionary.keys()): # Creating a sublist to store words with same # key value and adding it to the list. dictionary[word[0]] = [] dictionary[word[0]].append(word) # If key is present then checking for the word else: # If word is not present in the sublist then # adding it to the sublist of the proper key # value if (word not in dictionary[word[0]]): dictionary[word[0]].append(word) # Printing the dictionaryprint(dictionary)", "e": 27723, "s": 26597, "text": null }, { "code": null, "e": 27731, "s": 27723, "text": "Output:" }, { "code": null, "e": 28081, "s": 27731, "text": "{'G': ['GeeksforGeeks'], \n 'i': ['is'], \n 'a': ['a', 'and', 'articles,'], \n 'C': ['Computer'],\n 'S': ['Science'], \n 'p': ['portal', 'programming'], \n 'f': ['for'], \n 'g': ['geeks.'], \n 'I': ['It'], \n 'c': ['contains', 'computer'], \n 'w': ['well', 'written,'], \n 't': ['thought'],\n 'e': ['explained', 'etc.'], \n 's': ['science'], \n 'q': ['quizzes']}\n" }, { "code": null, "e": 28481, "s": 28081, "text": "You can see that in the above program’s output the words starting with G have two keys ‘G‘ and ‘g‘ so to remove that issue and make the code case-insensitive we will make use of the lower() function in python. We will save all keys with the lower case so that whenever we will check for the key both the words starting with ‘G‘ and ‘g‘ both will come under the same key. Below is the implementation:" }, { "code": null, "e": 28489, "s": 28481, "text": "Python3" }, { "code": "# Python program to Create a Dictionary with Key as First# Character and Value as Words Starting with that Character # Driver Code # Declaring String Datastring_input = '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.''' # Storing words in the input as a listwords = string_input.split() # Declaring empty dictionarydictionary = {} for word in words: # If key is not present in the dictionary then we # will add the key and word to the dictionary. if (word[0].lower() not in dictionary.keys()): # Creating a sublist to store words with same # key value and adding it to the list. dictionary[word[0].lower()] = [] dictionary[word[0].lower()].append(word) # If key is present then checking for the word else: # If word is not present in the sublist then # adding it to the sublist of the proper key # value if (word not in dictionary[word[0].lower()]): dictionary[word[0].lower()].append(word) # Printing the dictionaryprint(dictionary)", "e": 29655, "s": 28489, "text": null }, { "code": null, "e": 29663, "s": 29655, "text": "Output:" }, { "code": null, "e": 29977, "s": 29663, "text": "{'g': ['GeeksforGeeks', 'geeks.'],\n 'i': ['is', 'It'],\n 'a': ['a', 'and', 'articles,'], \n 'c': ['Computer', 'contains', 'computer'], \n 's': ['Science', 'science'], \n 'p': ['portal', 'programming'], \n 'f': ['for'], \n 'w': ['well', 'written,'], \n 't': ['thought'], \n 'e': ['explained', 'etc.'], \n 'q': ['quizzes']}\n" }, { "code": null, "e": 30004, "s": 29977, "text": "Python dictionary-programs" }, { "code": null, "e": 30011, "s": 30004, "text": "Python" }, { "code": null, "e": 30027, "s": 30011, "text": "Python Programs" }, { "code": null, "e": 30125, "s": 30027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30157, "s": 30125, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30199, "s": 30157, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30241, "s": 30199, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30297, "s": 30241, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30324, "s": 30297, "text": "Python Classes and Objects" }, { "code": null, "e": 30346, "s": 30324, "text": "Defaultdict in Python" }, { "code": null, "e": 30385, "s": 30346, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 30431, "s": 30385, "text": "Python | Split string into list of characters" }, { "code": null, "e": 30469, "s": 30431, "text": "Python | Convert a list to dictionary" } ]
Python - All possible pairs in List - GeeksforGeeks
03 Jul, 2020 Sometimes, while working with Python list, we can have a problem in which we need to extract all the possible pairs that can be performed from integers from list. This kind of problem can occur in many domains such as day-day programming and web development. Let’s discuss certain ways in which this task can be performed. Input : test_list = [1, 7, 4]Output : [(1, 7), (1, 4), (7, 4)] Input : test_list = [7, 4]Output : [(7, 4)] Method #1 : Using list comprehension + enumerate()This is one of the ways in which this task can be performed. In this, we perform the task of pairing using nested loops in list comprehension recipe, and enumerate() is used to check with the next indices while iteration. # Python3 code to demonstrate working of # All possible pairs in List# Using list comprehension + enumerate() # initializing listtest_list = [1, 7, 4, 3] # printing original list print("The original list : " + str(test_list)) # All possible pairs in List# Using list comprehension + enumerate()res = [(a, b) for idx, a in enumerate(test_list) for b in test_list[idx + 1:]] # printing result print("All possible pairs : " + str(res)) The original list : [1, 7, 4, 3] All possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)] Method #2 : Using combinations()This is one of the ways in which this task can be performed. In this, we just using inbuild function for pairing and sending 2 as value for making pairs of size 2. # Python3 code to demonstrate working of # All possible pairs in List# Using combinations()from itertools import combinations # initializing listtest_list = [1, 7, 4, 3] # printing original list print("The original list : " + str(test_list)) # All possible pairs in List# Using combinations()res = list(combinations(test_list, 2)) # printing result print("All possible pairs : " + str(res)) The original list : [1, 7, 4, 3] All possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25555, "s": 25527, "text": "\n03 Jul, 2020" }, { "code": null, "e": 25878, "s": 25555, "text": "Sometimes, while working with Python list, we can have a problem in which we need to extract all the possible pairs that can be performed from integers from list. This kind of problem can occur in many domains such as day-day programming and web development. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 25941, "s": 25878, "text": "Input : test_list = [1, 7, 4]Output : [(1, 7), (1, 4), (7, 4)]" }, { "code": null, "e": 25985, "s": 25941, "text": "Input : test_list = [7, 4]Output : [(7, 4)]" }, { "code": null, "e": 26257, "s": 25985, "text": "Method #1 : Using list comprehension + enumerate()This is one of the ways in which this task can be performed. In this, we perform the task of pairing using nested loops in list comprehension recipe, and enumerate() is used to check with the next indices while iteration." }, { "code": "# Python3 code to demonstrate working of # All possible pairs in List# Using list comprehension + enumerate() # initializing listtest_list = [1, 7, 4, 3] # printing original list print(\"The original list : \" + str(test_list)) # All possible pairs in List# Using list comprehension + enumerate()res = [(a, b) for idx, a in enumerate(test_list) for b in test_list[idx + 1:]] # printing result print(\"All possible pairs : \" + str(res))", "e": 26694, "s": 26257, "text": null }, { "code": null, "e": 26798, "s": 26694, "text": "The original list : [1, 7, 4, 3]\nAll possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]\n" }, { "code": null, "e": 26996, "s": 26800, "text": "Method #2 : Using combinations()This is one of the ways in which this task can be performed. In this, we just using inbuild function for pairing and sending 2 as value for making pairs of size 2." }, { "code": "# Python3 code to demonstrate working of # All possible pairs in List# Using combinations()from itertools import combinations # initializing listtest_list = [1, 7, 4, 3] # printing original list print(\"The original list : \" + str(test_list)) # All possible pairs in List# Using combinations()res = list(combinations(test_list, 2)) # printing result print(\"All possible pairs : \" + str(res))", "e": 27391, "s": 26996, "text": null }, { "code": null, "e": 27495, "s": 27391, "text": "The original list : [1, 7, 4, 3]\nAll possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]\n" }, { "code": null, "e": 27516, "s": 27495, "text": "Python list-programs" }, { "code": null, "e": 27523, "s": 27516, "text": "Python" }, { "code": null, "e": 27539, "s": 27523, "text": "Python Programs" }, { "code": null, "e": 27637, "s": 27539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27669, "s": 27637, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27711, "s": 27669, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27753, "s": 27711, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27809, "s": 27753, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27836, "s": 27809, "text": "Python Classes and Objects" }, { "code": null, "e": 27858, "s": 27836, "text": "Defaultdict in Python" }, { "code": null, "e": 27897, "s": 27858, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27943, "s": 27897, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27981, "s": 27943, "text": "Python | Convert a list to dictionary" } ]
LEX program to print the longest string and to find average of given numbers - GeeksforGeeks
03 Aug, 2021 Lex :The Lex program has purpose of generating lexical analyzer. Lex analyzers are a program that transform input streams into sequence of tokens. A C program implements the lexical analyzer to read input stream and produce output as the source code. Commands to be used – lex file_name.l // To produce a c program cc lex.yy.c -lfl // To compile the c program and produces object program a.out. ./a.out // To transforms an input stream into a sequence of tokens. 1. Longest string :In this we are finding the length of longest string by using the function called ( It returns the length of a given string). And we are storing this returned value in the variable . To print what string or word is longest we are using and function. We are storing the string or word in a variable of type char that is . Program – C %{ //to find longest string and its length #include<stdio.h> #include<string.h> int longest = 0; char longestString[30];%}%%[a-zA-Z]+ {if(yyleng>longest){ longest = yyleng; strcpy(longestString,yytext);}} %% int main(void){ yylex(); printf("The longest string is %s \n", longestString); printf("Length of a longest string is %d \n",longest);} Output – 2. Average of given numbers :So, first we have to calculate sum of all numbers that are given by user. Store sum in a variable sum. Then count number of integers(numbers that are given by the user). Store this count in a variable n.After this, just divide the sum and count of numbers. You will get your result.Here, we are using inbuild function atoi(). A string of characters can be passed into atoi() function, which will convert them into an integer. The input string is a text string that can be converted into a numeric value. When first character in input string is not part of a number, atoi() function stops reading it. This could be null character at the end of string. It does not support exponents and decimals.The atoi() function removes all the Whitespace in string at beginning. Program – C %{ //Average of given numbers. #include<stdio.h> #include<math.h>%}digit[0-9]+%%{digit} return atoi(yytext);%% int main(){ float sum=0, num, n=0; while((num=yylex())>0){ sum = sum+num; n = n+1;}printf("The sum of given numbers is %f\n",sum);printf("Average of given numbers is %f\n",sum/n);yylex();return 0;} Output – Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. NPDA for accepting the language L = {an bn | n>=1} Construct Pushdown Automata for all length palindrome NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's} NPDA for accepting the language L = {wwR | w ∈ (a,b)*} Construct a Turing Machine for language L = {ww | w ∈ {0,1}} Pushdown Automata Acceptance by Final State Ambiguity in Context free Grammar and Context free Languages Halting Problem in Theory of Computation Decidability and Undecidability in TOC Decidable and Undecidable problems in Theory of Computation
[ { "code": null, "e": 26105, "s": 26077, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26356, "s": 26105, "text": "Lex :The Lex program has purpose of generating lexical analyzer. Lex analyzers are a program that transform input streams into sequence of tokens. A C program implements the lexical analyzer to read input stream and produce output as the source code." }, { "code": null, "e": 26379, "s": 26356, "text": " Commands to be used –" }, { "code": null, "e": 26586, "s": 26379, "text": "lex file_name.l // To produce a c program\ncc lex.yy.c -lfl // To compile the c program and produces object program a.out.\n./a.out // To transforms an input stream into a sequence of tokens. " }, { "code": null, "e": 26927, "s": 26586, "text": "1. Longest string :In this we are finding the length of longest string by using the function called ( It returns the length of a given string). And we are storing this returned value in the variable . To print what string or word is longest we are using and function. We are storing the string or word in a variable of type char that is ." }, { "code": null, "e": 26937, "s": 26927, "text": "Program –" }, { "code": null, "e": 26939, "s": 26937, "text": "C" }, { "code": "%{ //to find longest string and its length #include<stdio.h> #include<string.h> int longest = 0; char longestString[30];%}%%[a-zA-Z]+ {if(yyleng>longest){ longest = yyleng; strcpy(longestString,yytext);}} %% int main(void){ yylex(); printf(\"The longest string is %s \\n\", longestString); printf(\"Length of a longest string is %d \\n\",longest);}", "e": 27313, "s": 26939, "text": null }, { "code": null, "e": 27322, "s": 27313, "text": "Output –" }, { "code": null, "e": 28116, "s": 27322, "text": "2. Average of given numbers :So, first we have to calculate sum of all numbers that are given by user. Store sum in a variable sum. Then count number of integers(numbers that are given by the user). Store this count in a variable n.After this, just divide the sum and count of numbers. You will get your result.Here, we are using inbuild function atoi(). A string of characters can be passed into atoi() function, which will convert them into an integer. The input string is a text string that can be converted into a numeric value. When first character in input string is not part of a number, atoi() function stops reading it. This could be null character at the end of string. It does not support exponents and decimals.The atoi() function removes all the Whitespace in string at beginning." }, { "code": null, "e": 28126, "s": 28116, "text": "Program –" }, { "code": null, "e": 28128, "s": 28126, "text": "C" }, { "code": "%{ //Average of given numbers. #include<stdio.h> #include<math.h>%}digit[0-9]+%%{digit} return atoi(yytext);%% int main(){ float sum=0, num, n=0; while((num=yylex())>0){ sum = sum+num; n = n+1;}printf(\"The sum of given numbers is %f\\n\",sum);printf(\"Average of given numbers is %f\\n\",sum/n);yylex();return 0;}", "e": 28459, "s": 28128, "text": null }, { "code": null, "e": 28468, "s": 28459, "text": "Output –" }, { "code": null, "e": 28501, "s": 28468, "text": "Theory of Computation & Automata" }, { "code": null, "e": 28599, "s": 28501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28650, "s": 28599, "text": "NPDA for accepting the language L = {an bn | n>=1}" }, { "code": null, "e": 28704, "s": 28650, "text": "Construct Pushdown Automata for all length palindrome" }, { "code": null, "e": 28778, "s": 28704, "text": "NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's}" }, { "code": null, "e": 28833, "s": 28778, "text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}" }, { "code": null, "e": 28894, "s": 28833, "text": "Construct a Turing Machine for language L = {ww | w ∈ {0,1}}" }, { "code": null, "e": 28938, "s": 28894, "text": "Pushdown Automata Acceptance by Final State" }, { "code": null, "e": 28999, "s": 28938, "text": "Ambiguity in Context free Grammar and Context free Languages" }, { "code": null, "e": 29040, "s": 28999, "text": "Halting Problem in Theory of Computation" }, { "code": null, "e": 29079, "s": 29040, "text": "Decidability and Undecidability in TOC" } ]
Network Security - GeeksforGeeks
22 Oct, 2021 Network Security refers to the measures taken by any enterprise or organisation to secure its computer network and data using both hardware and software systems. This aims at securing the confidentiality and accessibility of the data and network. Every company or organisation that handles large amount of data, has a degree of solutions against many cyber threats. The most basic example of Network Security is password protection where the user of the network oneself chooses. In the recent times, Network Security has become the central topic of cyber security with many organisations inviting applications of people who have skills in this area. The network security solutions protect various vulnerabilities of the computer systems such as: 1. Users 2. Locations 3. Data 4. Devices 5. Applications Network Security : Working The basic principle of network security is protecting huge stored data and network in layers that ensures a bedding of rules and regulations that have to be acknowledged before performing any activity on the data. These levels are: 1. Physical 2. Technical 3. Administrative These are explained as following below. Physical Network Security: This is the most basic level that includes protecting the data and network though unauthorized personnel from acquiring the control over the confidentiality of the network. These includes external peripherals and routers might be used for cable connections. The same can be achieved by using devices like bio-metric systems. Technical Network Security: It primarily focuses on protecting the data stored in the network or data involved in transitions through the network. This type serves two purposes. One, protection from the unauthorized users and the other being protection from malicious activities. Administrative Network Security: This level of network security protects user behavior like how the permission has been granted and how the authorization process takes place. This also ensures the level of sophistication the network might need for protecting it through all the attacks. This level also suggests necessary amendments that have to be done over the infrastructure. Physical Network Security: This is the most basic level that includes protecting the data and network though unauthorized personnel from acquiring the control over the confidentiality of the network. These includes external peripherals and routers might be used for cable connections. The same can be achieved by using devices like bio-metric systems. Technical Network Security: It primarily focuses on protecting the data stored in the network or data involved in transitions through the network. This type serves two purposes. One, protection from the unauthorized users and the other being protection from malicious activities. Administrative Network Security: This level of network security protects user behavior like how the permission has been granted and how the authorization process takes place. This also ensures the level of sophistication the network might need for protecting it through all the attacks. This level also suggests necessary amendments that have to be done over the infrastructure. Types of Network Security: The few types of network securities are discussed as below : Access Control: Not every person should have complete allowance to the accessibility to the network or its data. The one way to examine this is by going through each personnel’s details. This is done through Network Access Control which ensures that only a handful of authorized personnel must be able to work with allowed amount of resources. Antivirus and Anti-malware Software: This type of network security ensures that any malicious software does not enter the network and jeopardize the security of the data. The malicious software like Viruses, Trojans, Worms are handled by the same. This ensure that not only the entry of the malware is protected but also that the system is well equipped to fight once it has entered. Cloud Security: Now a day, a lot many organisations are joining hands with the cloud technology where a large amount of important data is stored over the internet. This is very vulnerable to the malpractices that few unauthorized dealers might pertain. This data must be protected an it should be ensured that this protection is not jeopardize over anything. Many businesses embrace SaaS applications for providing some of its employees the allowance of accessing the data stored over the cloud. This type of security ensures in creating gaps in visibility of the data. Access Control: Not every person should have complete allowance to the accessibility to the network or its data. The one way to examine this is by going through each personnel’s details. This is done through Network Access Control which ensures that only a handful of authorized personnel must be able to work with allowed amount of resources. Antivirus and Anti-malware Software: This type of network security ensures that any malicious software does not enter the network and jeopardize the security of the data. The malicious software like Viruses, Trojans, Worms are handled by the same. This ensure that not only the entry of the malware is protected but also that the system is well equipped to fight once it has entered. Cloud Security: Now a day, a lot many organisations are joining hands with the cloud technology where a large amount of important data is stored over the internet. This is very vulnerable to the malpractices that few unauthorized dealers might pertain. This data must be protected an it should be ensured that this protection is not jeopardize over anything. Many businesses embrace SaaS applications for providing some of its employees the allowance of accessing the data stored over the cloud. This type of security ensures in creating gaps in visibility of the data. simmytarika5 Cyber-security Information-Security Network-security Technical Scripter 2019 Computer Networks Technical Scripter Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. RSA Algorithm in Cryptography Differences between TCP and UDP TCP Server-Client implementation in C Data encryption standard (DES) | Set 1 Differences between IPv4 and IPv6 Socket Programming in Python Types of Network Topology TCP 3-Way Handshake Process Implementation of Diffie-Hellman Algorithm Types of Transmission Media
[ { "code": null, "e": 25583, "s": 25555, "text": "\n22 Oct, 2021" }, { "code": null, "e": 25950, "s": 25583, "text": "Network Security refers to the measures taken by any enterprise or organisation to secure its computer network and data using both hardware and software systems. This aims at securing the confidentiality and accessibility of the data and network. Every company or organisation that handles large amount of data, has a degree of solutions against many cyber threats. " }, { "code": null, "e": 26332, "s": 25950, "text": "The most basic example of Network Security is password protection where the user of the network oneself chooses. In the recent times, Network Security has become the central topic of cyber security with many organisations inviting applications of people who have skills in this area. The network security solutions protect various vulnerabilities of the computer systems such as: " }, { "code": null, "e": 26390, "s": 26332, "text": "1. Users\n2. Locations\n3. Data\n4. Devices\n5. Applications " }, { "code": null, "e": 26651, "s": 26390, "text": "Network Security : Working The basic principle of network security is protecting huge stored data and network in layers that ensures a bedding of rules and regulations that have to be acknowledged before performing any activity on the data. These levels are: " }, { "code": null, "e": 26696, "s": 26651, "text": "1. Physical\n2. Technical \n3. Administrative " }, { "code": null, "e": 26737, "s": 26696, "text": "These are explained as following below. " }, { "code": null, "e": 27751, "s": 26737, "text": "Physical Network Security: This is the most basic level that includes protecting the data and network though unauthorized personnel from acquiring the control over the confidentiality of the network. These includes external peripherals and routers might be used for cable connections. The same can be achieved by using devices like bio-metric systems. Technical Network Security: It primarily focuses on protecting the data stored in the network or data involved in transitions through the network. This type serves two purposes. One, protection from the unauthorized users and the other being protection from malicious activities. Administrative Network Security: This level of network security protects user behavior like how the permission has been granted and how the authorization process takes place. This also ensures the level of sophistication the network might need for protecting it through all the attacks. This level also suggests necessary amendments that have to be done over the infrastructure. " }, { "code": null, "e": 28105, "s": 27751, "text": "Physical Network Security: This is the most basic level that includes protecting the data and network though unauthorized personnel from acquiring the control over the confidentiality of the network. These includes external peripherals and routers might be used for cable connections. The same can be achieved by using devices like bio-metric systems. " }, { "code": null, "e": 28387, "s": 28105, "text": "Technical Network Security: It primarily focuses on protecting the data stored in the network or data involved in transitions through the network. This type serves two purposes. One, protection from the unauthorized users and the other being protection from malicious activities. " }, { "code": null, "e": 28767, "s": 28387, "text": "Administrative Network Security: This level of network security protects user behavior like how the permission has been granted and how the authorization process takes place. This also ensures the level of sophistication the network might need for protecting it through all the attacks. This level also suggests necessary amendments that have to be done over the infrastructure. " }, { "code": null, "e": 28856, "s": 28767, "text": "Types of Network Security: The few types of network securities are discussed as below : " }, { "code": null, "e": 30157, "s": 28856, "text": "Access Control: Not every person should have complete allowance to the accessibility to the network or its data. The one way to examine this is by going through each personnel’s details. This is done through Network Access Control which ensures that only a handful of authorized personnel must be able to work with allowed amount of resources. Antivirus and Anti-malware Software: This type of network security ensures that any malicious software does not enter the network and jeopardize the security of the data. The malicious software like Viruses, Trojans, Worms are handled by the same. This ensure that not only the entry of the malware is protected but also that the system is well equipped to fight once it has entered. Cloud Security: Now a day, a lot many organisations are joining hands with the cloud technology where a large amount of important data is stored over the internet. This is very vulnerable to the malpractices that few unauthorized dealers might pertain. This data must be protected an it should be ensured that this protection is not jeopardize over anything. Many businesses embrace SaaS applications for providing some of its employees the allowance of accessing the data stored over the cloud. This type of security ensures in creating gaps in visibility of the data. " }, { "code": null, "e": 30503, "s": 30157, "text": "Access Control: Not every person should have complete allowance to the accessibility to the network or its data. The one way to examine this is by going through each personnel’s details. This is done through Network Access Control which ensures that only a handful of authorized personnel must be able to work with allowed amount of resources. " }, { "code": null, "e": 30889, "s": 30503, "text": "Antivirus and Anti-malware Software: This type of network security ensures that any malicious software does not enter the network and jeopardize the security of the data. The malicious software like Viruses, Trojans, Worms are handled by the same. This ensure that not only the entry of the malware is protected but also that the system is well equipped to fight once it has entered. " }, { "code": null, "e": 31460, "s": 30889, "text": "Cloud Security: Now a day, a lot many organisations are joining hands with the cloud technology where a large amount of important data is stored over the internet. This is very vulnerable to the malpractices that few unauthorized dealers might pertain. This data must be protected an it should be ensured that this protection is not jeopardize over anything. Many businesses embrace SaaS applications for providing some of its employees the allowance of accessing the data stored over the cloud. This type of security ensures in creating gaps in visibility of the data. " }, { "code": null, "e": 31473, "s": 31460, "text": "simmytarika5" }, { "code": null, "e": 31488, "s": 31473, "text": "Cyber-security" }, { "code": null, "e": 31509, "s": 31488, "text": "Information-Security" }, { "code": null, "e": 31526, "s": 31509, "text": "Network-security" }, { "code": null, "e": 31550, "s": 31526, "text": "Technical Scripter 2019" }, { "code": null, "e": 31568, "s": 31550, "text": "Computer Networks" }, { "code": null, "e": 31587, "s": 31568, "text": "Technical Scripter" }, { "code": null, "e": 31605, "s": 31587, "text": "Computer Networks" }, { "code": null, "e": 31703, "s": 31605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31733, "s": 31703, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 31765, "s": 31733, "text": "Differences between TCP and UDP" }, { "code": null, "e": 31803, "s": 31765, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 31842, "s": 31803, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 31876, "s": 31842, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 31905, "s": 31876, "text": "Socket Programming in Python" }, { "code": null, "e": 31931, "s": 31905, "text": "Types of Network Topology" }, { "code": null, "e": 31959, "s": 31931, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 32002, "s": 31959, "text": "Implementation of Diffie-Hellman Algorithm" } ]
How to get a variable name as a string in PHP? - GeeksforGeeks
15 May, 2019 Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below: Method 1: Using $GLOBALS: It is used to reference all variables available in global scope. It is an associative array which contains the reference of all variables which are currently defined in the global scope. Example: This example uses $GLOBAL reference to get the variable name as a string. <?php // Declare and initialize a variable$test = "This is a string"; // Function that returns the variable namefunction getVariavleName($var) { foreach($GLOBALS as $varName => $value) { if ($value === $var) { return $varName; } } return;} // Function call and display the// variable nameprint getVariavleName($test); ?> test Method 2: Using $$ Operator: The $$var_name is known as reference variable where $var_name is a normal variable. The $$var_name used to refer to the variable with the name as value of the variable $var_name.Example: This example uses $$ operator to get the variable name as a string. <?php // Declare and initialize a variable$name = "test"; // Reference variable to store string$$name = "This is a string"; // Display resultprint($name); ?> test PHP-string Picked PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP Download file from URL using PHP
[ { "code": null, "e": 26137, "s": 26109, "text": "\n15 May, 2019" }, { "code": null, "e": 26269, "s": 26137, "text": "Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below:" }, { "code": null, "e": 26482, "s": 26269, "text": "Method 1: Using $GLOBALS: It is used to reference all variables available in global scope. It is an associative array which contains the reference of all variables which are currently defined in the global scope." }, { "code": null, "e": 26565, "s": 26482, "text": "Example: This example uses $GLOBAL reference to get the variable name as a string." }, { "code": "<?php // Declare and initialize a variable$test = \"This is a string\"; // Function that returns the variable namefunction getVariavleName($var) { foreach($GLOBALS as $varName => $value) { if ($value === $var) { return $varName; } } return;} // Function call and display the// variable nameprint getVariavleName($test); ?>", "e": 26924, "s": 26565, "text": null }, { "code": null, "e": 26930, "s": 26924, "text": "test\n" }, { "code": null, "e": 27214, "s": 26930, "text": "Method 2: Using $$ Operator: The $$var_name is known as reference variable where $var_name is a normal variable. The $$var_name used to refer to the variable with the name as value of the variable $var_name.Example: This example uses $$ operator to get the variable name as a string." }, { "code": "<?php // Declare and initialize a variable$name = \"test\"; // Reference variable to store string$$name = \"This is a string\"; // Display resultprint($name); ?>", "e": 27376, "s": 27214, "text": null }, { "code": null, "e": 27382, "s": 27376, "text": "test\n" }, { "code": null, "e": 27393, "s": 27382, "text": "PHP-string" }, { "code": null, "e": 27400, "s": 27393, "text": "Picked" }, { "code": null, "e": 27404, "s": 27400, "text": "PHP" }, { "code": null, "e": 27408, "s": 27404, "text": "PHP" }, { "code": null, "e": 27506, "s": 27408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27556, "s": 27506, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27596, "s": 27556, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27657, "s": 27596, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27707, "s": 27657, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27752, "s": 27707, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27779, "s": 27752, "text": "Comparing two dates in PHP" }, { "code": null, "e": 27815, "s": 27779, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 27857, "s": 27815, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27909, "s": 27857, "text": "Split a comma delimited string into an array in PHP" } ]
Haversine formula to find distance between two points on a sphere - GeeksforGeeks
12 May, 2021 The Haversine formula calculates the shortest distance between two points on a sphere using their latitudes and longitudes measured along the surface. It is important for use in navigation. The haversine can be expressed in trigonometric function as: The haversine of the central angle (which is d/r) is calculated by the following formula:where r is the radius of the earth(6371 km), d is the distance between two points, is the latitude of the two points, and is the longitude of the two points respectively.Solving d by applying the inverse haversine or by using the inverse sine function, we get: or The distance between Big Ben in London (51.5007° N, 0.1246° W) and The Statue of Liberty in New York (40.6892° N, 74.0445° W) is 5574.8 km. This is not the exact measurement because the formula assumes that the Earth is a perfect sphere when in fact it is an oblate spheroid.Below is the implementation of the above formulae: C++ Java Python 3 C# PHP Javascript // C++ program for the haversine formula// C++ program for the// haversine formula#include <iostream>#include <cmath>using namespace std; static double haversine(double lat1, double lon1, double lat2, double lon2) { // distance between latitudes // and longitudes double dLat = (lat2 - lat1) * M_PI / 180.0; double dLon = (lon2 - lon1) * M_PI / 180.0; // convert to radians lat1 = (lat1) * M_PI / 180.0; lat2 = (lat2) * M_PI / 180.0; // apply formulae double a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2); double rad = 6371; double c = 2 * asin(sqrt(a)); return rad * c; } // Driver codeint main(){ double lat1 = 51.5007; double lon1 = 0.1246; double lat2 = 40.6892; double lon2 = 74.0445; cout << haversine(lat1, lon1, lat2, lon2) << " K.M."; return 0;} // This code is contributed// by Mahadev. // Java program for the haversine formulapublic class Haversine { static double haversine(double lat1, double lon1, double lat2, double lon2) { // distance between latitudes and longitudes double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); // convert to radians lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); // apply formulae double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double rad = 6371; double c = 2 * Math.asin(Math.sqrt(a)); return rad * c; } // Driver Code public static void main(String[] args) { double lat1 = 51.5007; double lon1 = 0.1246; double lat2 = 40.6892; double lon2 = 74.0445; System.out.println(haversine(lat1, lon1, lat2, lon2) + " K.M."); }} # Python 3 program for the# haversine formulaimport math # Python 3 program for the# haversine formuladef haversine(lat1, lon1, lat2, lon2): # distance between latitudes # and longitudes dLat = (lat2 - lat1) * math.pi / 180.0 dLon = (lon2 - lon1) * math.pi / 180.0 # convert to radians lat1 = (lat1) * math.pi / 180.0 lat2 = (lat2) * math.pi / 180.0 # apply formulae a = (pow(math.sin(dLat / 2), 2) + pow(math.sin(dLon / 2), 2) * math.cos(lat1) * math.cos(lat2)); rad = 6371 c = 2 * math.asin(math.sqrt(a)) return rad * c # Driver codeif __name__ == "__main__": lat1 = 51.5007 lon1 = 0.1246 lat2 = 40.6892 lon2 = 74.0445 print(haversine(lat1, lon1,lat2, lon2), "K.M.") # This code is contributed# by ChitraNayal // C# program for the haversine formulausing System;class GFG{ static double haversine(double lat1, double lon1, double lat2, double lon2){ // distance between latitudes and longitudes double dLat = (Math.PI / 180) * (lat2 - lat1); double dLon = (Math.PI / 180) * (lon2 - lon1); // convert to radians lat1 = (Math.PI / 180) * (lat1); lat2 = (Math.PI / 180) * (lat2); // apply formulae double a = Math.Pow(Math.Sin(dLat / 2), 2) + Math.Pow(Math.Sin(dLon / 2), 2) * Math.Cos(lat1) * Math.Cos(lat2); double rad = 6371; double c = 2 * Math.Asin(Math.Sqrt(a)); return rad * c;} // Driver Codepublic static void Main(){ double lat1 = 51.5007; double lon1 = 0.1246; double lat2 = 40.6892; double lon2 = 74.0445; Console.WriteLine(haversine(lat1, lon1, lat2, lon2) + " K.M.");}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program for the// haversine formula function haversine($lat1, $lon1, $lat2, $lon2){ // distance between latitudes // and longitudes $dLat = ($lat2 - $lat1) * M_PI / 180.0; $dLon = ($lon2 - $lon1) * M_PI / 180.0; // convert to radians $lat1 = ($lat1) * M_PI / 180.0; $lat2 = ($lat2) * M_PI / 180.0; // apply formulae $a = pow(sin($dLat / 2), 2) + pow(sin($dLon / 2), 2) * cos($lat1) * cos($lat2); $rad = 6371; $c = 2 * asin(sqrt($a)); return $rad * $c;} // Driver code$lat1 = 51.5007;$lon1 = 0.1246;$lat2 = 40.6892;$lon2 = 74.0445; echo haversine($lat1, $lon1, $lat2, $lon2) . " K.M."; // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program for the haversine formula function haversine(lat1, lon1, lat2, lon2) { // distance between latitudes // and longitudes let dLat = (lat2 - lat1) * Math.PI / 180.0; let dLon = (lon2 - lon1) * Math.PI / 180.0; // convert to radiansa lat1 = (lat1) * Math.PI / 180.0; lat2 = (lat2) * Math.PI / 180.0; // apply formulae let a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); let rad = 6371; let c = 2 * Math.asin(Math.sqrt(a)); return rad * c; } // Driver Code let lat1 = 51.5007; let lon1 = 0.1246; let lat2 = 40.6892; let lon2 = 74.0445; document.write(haversine(lat1, lon1, lat2, lon2) + " K.M."); // This code is contributed by avanitrachhadiya2155</script> 5574.840456848555 K.M. Mahadev99 Akanksha_Rai ukasp avanitrachhadiya2155 math Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check whether a given point lies inside a triangle or not Optimum location of point to minimize total distance Given n line segments, find if any two segments intersect Convex Hull using Divide and Conquer Algorithm Polygon Clipping | Sutherland–Hodgman Algorithm Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26352, "s": 26324, "text": "\n12 May, 2021" }, { "code": null, "e": 26955, "s": 26352, "text": "The Haversine formula calculates the shortest distance between two points on a sphere using their latitudes and longitudes measured along the surface. It is important for use in navigation. The haversine can be expressed in trigonometric function as: The haversine of the central angle (which is d/r) is calculated by the following formula:where r is the radius of the earth(6371 km), d is the distance between two points, is the latitude of the two points, and is the longitude of the two points respectively.Solving d by applying the inverse haversine or by using the inverse sine function, we get: " }, { "code": null, "e": 26958, "s": 26955, "text": "or" }, { "code": null, "e": 27286, "s": 26958, "text": "The distance between Big Ben in London (51.5007° N, 0.1246° W) and The Statue of Liberty in New York (40.6892° N, 74.0445° W) is 5574.8 km. This is not the exact measurement because the formula assumes that the Earth is a perfect sphere when in fact it is an oblate spheroid.Below is the implementation of the above formulae: " }, { "code": null, "e": 27290, "s": 27286, "text": "C++" }, { "code": null, "e": 27295, "s": 27290, "text": "Java" }, { "code": null, "e": 27304, "s": 27295, "text": "Python 3" }, { "code": null, "e": 27307, "s": 27304, "text": "C#" }, { "code": null, "e": 27311, "s": 27307, "text": "PHP" }, { "code": null, "e": 27322, "s": 27311, "text": "Javascript" }, { "code": "// C++ program for the haversine formula// C++ program for the// haversine formula#include <iostream>#include <cmath>using namespace std; static double haversine(double lat1, double lon1, double lat2, double lon2) { // distance between latitudes // and longitudes double dLat = (lat2 - lat1) * M_PI / 180.0; double dLon = (lon2 - lon1) * M_PI / 180.0; // convert to radians lat1 = (lat1) * M_PI / 180.0; lat2 = (lat2) * M_PI / 180.0; // apply formulae double a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2); double rad = 6371; double c = 2 * asin(sqrt(a)); return rad * c; } // Driver codeint main(){ double lat1 = 51.5007; double lon1 = 0.1246; double lat2 = 40.6892; double lon2 = 74.0445; cout << haversine(lat1, lon1, lat2, lon2) << \" K.M.\"; return 0;} // This code is contributed// by Mahadev.", "e": 28384, "s": 27322, "text": null }, { "code": "// Java program for the haversine formulapublic class Haversine { static double haversine(double lat1, double lon1, double lat2, double lon2) { // distance between latitudes and longitudes double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); // convert to radians lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); // apply formulae double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double rad = 6371; double c = 2 * Math.asin(Math.sqrt(a)); return rad * c; } // Driver Code public static void main(String[] args) { double lat1 = 51.5007; double lon1 = 0.1246; double lat2 = 40.6892; double lon2 = 74.0445; System.out.println(haversine(lat1, lon1, lat2, lon2) + \" K.M.\"); }}", "e": 29379, "s": 28384, "text": null }, { "code": "# Python 3 program for the# haversine formulaimport math # Python 3 program for the# haversine formuladef haversine(lat1, lon1, lat2, lon2): # distance between latitudes # and longitudes dLat = (lat2 - lat1) * math.pi / 180.0 dLon = (lon2 - lon1) * math.pi / 180.0 # convert to radians lat1 = (lat1) * math.pi / 180.0 lat2 = (lat2) * math.pi / 180.0 # apply formulae a = (pow(math.sin(dLat / 2), 2) + pow(math.sin(dLon / 2), 2) * math.cos(lat1) * math.cos(lat2)); rad = 6371 c = 2 * math.asin(math.sqrt(a)) return rad * c # Driver codeif __name__ == \"__main__\": lat1 = 51.5007 lon1 = 0.1246 lat2 = 40.6892 lon2 = 74.0445 print(haversine(lat1, lon1,lat2, lon2), \"K.M.\") # This code is contributed# by ChitraNayal", "e": 30174, "s": 29379, "text": null }, { "code": "// C# program for the haversine formulausing System;class GFG{ static double haversine(double lat1, double lon1, double lat2, double lon2){ // distance between latitudes and longitudes double dLat = (Math.PI / 180) * (lat2 - lat1); double dLon = (Math.PI / 180) * (lon2 - lon1); // convert to radians lat1 = (Math.PI / 180) * (lat1); lat2 = (Math.PI / 180) * (lat2); // apply formulae double a = Math.Pow(Math.Sin(dLat / 2), 2) + Math.Pow(Math.Sin(dLon / 2), 2) * Math.Cos(lat1) * Math.Cos(lat2); double rad = 6371; double c = 2 * Math.Asin(Math.Sqrt(a)); return rad * c;} // Driver Codepublic static void Main(){ double lat1 = 51.5007; double lon1 = 0.1246; double lat2 = 40.6892; double lon2 = 74.0445; Console.WriteLine(haversine(lat1, lon1, lat2, lon2) + \" K.M.\");}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 31134, "s": 30174, "text": null }, { "code": "<?php// PHP program for the// haversine formula function haversine($lat1, $lon1, $lat2, $lon2){ // distance between latitudes // and longitudes $dLat = ($lat2 - $lat1) * M_PI / 180.0; $dLon = ($lon2 - $lon1) * M_PI / 180.0; // convert to radians $lat1 = ($lat1) * M_PI / 180.0; $lat2 = ($lat2) * M_PI / 180.0; // apply formulae $a = pow(sin($dLat / 2), 2) + pow(sin($dLon / 2), 2) * cos($lat1) * cos($lat2); $rad = 6371; $c = 2 * asin(sqrt($a)); return $rad * $c;} // Driver code$lat1 = 51.5007;$lon1 = 0.1246;$lat2 = 40.6892;$lon2 = 74.0445; echo haversine($lat1, $lon1, $lat2, $lon2) . \" K.M.\"; // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 31947, "s": 31134, "text": null }, { "code": "<script> // Javascript program for the haversine formula function haversine(lat1, lon1, lat2, lon2) { // distance between latitudes // and longitudes let dLat = (lat2 - lat1) * Math.PI / 180.0; let dLon = (lon2 - lon1) * Math.PI / 180.0; // convert to radiansa lat1 = (lat1) * Math.PI / 180.0; lat2 = (lat2) * Math.PI / 180.0; // apply formulae let a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); let rad = 6371; let c = 2 * Math.asin(Math.sqrt(a)); return rad * c; } // Driver Code let lat1 = 51.5007; let lon1 = 0.1246; let lat2 = 40.6892; let lon2 = 74.0445; document.write(haversine(lat1, lon1, lat2, lon2) + \" K.M.\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 32894, "s": 31947, "text": null }, { "code": null, "e": 32917, "s": 32894, "text": "5574.840456848555 K.M." }, { "code": null, "e": 32929, "s": 32919, "text": "Mahadev99" }, { "code": null, "e": 32942, "s": 32929, "text": "Akanksha_Rai" }, { "code": null, "e": 32948, "s": 32942, "text": "ukasp" }, { "code": null, "e": 32969, "s": 32948, "text": "avanitrachhadiya2155" }, { "code": null, "e": 32974, "s": 32969, "text": "math" }, { "code": null, "e": 32984, "s": 32974, "text": "Geometric" }, { "code": null, "e": 32997, "s": 32984, "text": "Mathematical" }, { "code": null, "e": 33010, "s": 32997, "text": "Mathematical" }, { "code": null, "e": 33020, "s": 33010, "text": "Geometric" }, { "code": null, "e": 33118, "s": 33020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33176, "s": 33118, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 33229, "s": 33176, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 33287, "s": 33229, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 33334, "s": 33287, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 33382, "s": 33334, "text": "Polygon Clipping | Sutherland–Hodgman Algorithm" }, { "code": null, "e": 33412, "s": 33382, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33472, "s": 33412, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33487, "s": 33472, "text": "C++ Data Types" }, { "code": null, "e": 33530, "s": 33487, "text": "Set in C++ Standard Template Library (STL)" } ]
C# | ListBox Class - GeeksforGeeks
05 Sep, 2019 In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. The ListBox class is used to represent the windows list box and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace. The ListBox class contains three different types of collection classes, i.e. ListBox.ObjectCollection: This class holds all the elements contained in the ListBox control. ListBox.SelectedObjectCollection: This class holds a collection of the selected items which is a subset of the items contained in the ListBox control. ListBox.SelectedIndexCollection: This class holds a collection of the selected indexes, which is a subset of the indexes of the ListBox.ObjectCollection and these indexes specify elements that are selected. In C# you can create a ListBox in the windows form by using two different ways: 1. Design-Time: It is the easiest way to create a ListBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the ListBox control from the toolbox to the form. Step 3: After drag and drop you will go to the properties of the ListBox control to modify ListBox according to your requirement.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a ListBox control programmatically with the help of syntax provided by the ListBox class. The following steps show how to set the create ListBox dynamically: Step 1: Create a ListBox control using the ListBox() constructor is provided by the ListBox class.// Creating a ListBox control ListBox mylist = new ListBox(); // Creating a ListBox control ListBox mylist = new ListBox(); Step 2: After creating ListBox control, set the property of the ListBox control provided by the ListBox class.ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); Step 3: And last add this ListBox control to the form using the following statement:// Adding ListBox control // to the form this.Controls.Add(mylist); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control // to the form this.Controls.Add(mylist); }}}Output: // Adding ListBox control // to the form this.Controls.Add(mylist); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control // to the form this.Controls.Add(mylist); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25331, "s": 25303, "text": "\n05 Sep, 2019" }, { "code": null, "e": 25780, "s": 25331, "text": "In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. The ListBox class is used to represent the windows list box and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace. The ListBox class contains three different types of collection classes, i.e." }, { "code": null, "e": 25874, "s": 25780, "text": "ListBox.ObjectCollection: This class holds all the elements contained in the ListBox control." }, { "code": null, "e": 26025, "s": 25874, "text": "ListBox.SelectedObjectCollection: This class holds a collection of the selected items which is a subset of the items contained in the ListBox control." }, { "code": null, "e": 26232, "s": 26025, "text": "ListBox.SelectedIndexCollection: This class holds a collection of the selected indexes, which is a subset of the indexes of the ListBox.ObjectCollection and these indexes specify elements that are selected." }, { "code": null, "e": 26312, "s": 26232, "text": "In C# you can create a ListBox in the windows form by using two different ways:" }, { "code": null, "e": 26403, "s": 26312, "text": "1. Design-Time: It is the easiest way to create a ListBox as shown in the following steps:" }, { "code": null, "e": 26519, "s": 26403, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26597, "s": 26519, "text": "Step 2: Next, drag and drop the ListBox control from the toolbox to the form." }, { "code": null, "e": 26734, "s": 26597, "text": "Step 3: After drag and drop you will go to the properties of the ListBox control to modify ListBox according to your requirement.Output:" }, { "code": null, "e": 26742, "s": 26734, "text": "Output:" }, { "code": null, "e": 26995, "s": 26742, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a ListBox control programmatically with the help of syntax provided by the ListBox class. The following steps show how to set the create ListBox dynamically:" }, { "code": null, "e": 27157, "s": 26995, "text": "Step 1: Create a ListBox control using the ListBox() constructor is provided by the ListBox class.// Creating a ListBox control\nListBox mylist = new ListBox(); \n" }, { "code": null, "e": 27221, "s": 27157, "text": "// Creating a ListBox control\nListBox mylist = new ListBox(); \n" }, { "code": null, "e": 27592, "s": 27221, "text": "Step 2: After creating ListBox control, set the property of the ListBox control provided by the ListBox class.ListBox mylist = new ListBox(); \n mylist.Location = new Point(287, 109); \n mylist.Size = new Size(120, 95); \n mylist.ForeColor = Color.Purple; \n mylist.Items.Add(123); \n mylist.Items.Add(456); \n mylist.Items.Add(789);\n" }, { "code": null, "e": 27853, "s": 27592, "text": "ListBox mylist = new ListBox(); \n mylist.Location = new Point(287, 109); \n mylist.Size = new Size(120, 95); \n mylist.ForeColor = Color.Purple; \n mylist.Items.Add(123); \n mylist.Items.Add(456); \n mylist.Items.Add(789);\n" }, { "code": null, "e": 28840, "s": 27853, "text": "Step 3: And last add this ListBox control to the form using the following statement:// Adding ListBox control \n// to the form \nthis.Controls.Add(mylist);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control // to the form this.Controls.Add(mylist); }}}Output:" }, { "code": null, "e": 28911, "s": 28840, "text": "// Adding ListBox control \n// to the form \nthis.Controls.Add(mylist);\n" }, { "code": null, "e": 28920, "s": 28911, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control // to the form this.Controls.Add(mylist); }}}", "e": 29738, "s": 28920, "text": null }, { "code": null, "e": 29746, "s": 29738, "text": "Output:" }, { "code": null, "e": 29777, "s": 29746, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 29780, "s": 29777, "text": "C#" }, { "code": null, "e": 29878, "s": 29780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29906, "s": 29878, "text": "C# Dictionary with examples" }, { "code": null, "e": 29921, "s": 29906, "text": "C# | Delegates" }, { "code": null, "e": 29944, "s": 29921, "text": "C# | Method Overriding" }, { "code": null, "e": 29966, "s": 29944, "text": "C# | Abstract Classes" }, { "code": null, "e": 30012, "s": 29966, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30035, "s": 30012, "text": "Extension Method in C#" }, { "code": null, "e": 30057, "s": 30035, "text": "C# | Class and Object" }, { "code": null, "e": 30075, "s": 30057, "text": "C# | Constructors" }, { "code": null, "e": 30115, "s": 30075, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
C# | How to change the CursorSize of the Console - GeeksforGeeks
28 Jan, 2019 Given the normal Console in C#, the task is to change the CursorSize of the Console. Approach: This can be done using the CursorSize property in the Console class of the System package in C#. It gets or sets the height of the cursor within a character cell in percentage. Program 1: Getting the value of CursorSize // C# program to illustrate the// Console.CursorSize Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the CursorSize Console.WriteLine("Current CursorSize: {0}", Console.CursorSize); }}} Output: Program 2: Setting the value of CursorSize // C# program to illustrate the// Console.CursorSize Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { // Main Method static void Main(string[] args) { // Get the CursorSize Console.WriteLine("Current CursorSize: {0}", Console.CursorSize); // Set the CursorSize Console.CursorSize = 100; // Get the CursorSize Console.Write("Current CursorSize: {0}", Console.CursorSize); }}} Output: Note: See the width of the Cursor in both the images. CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 26319, "s": 26291, "text": "\n28 Jan, 2019" }, { "code": null, "e": 26404, "s": 26319, "text": "Given the normal Console in C#, the task is to change the CursorSize of the Console." }, { "code": null, "e": 26591, "s": 26404, "text": "Approach: This can be done using the CursorSize property in the Console class of the System package in C#. It gets or sets the height of the cursor within a character cell in percentage." }, { "code": null, "e": 26634, "s": 26591, "text": "Program 1: Getting the value of CursorSize" }, { "code": "// C# program to illustrate the// Console.CursorSize Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the CursorSize Console.WriteLine(\"Current CursorSize: {0}\", Console.CursorSize); }}}", "e": 27025, "s": 26634, "text": null }, { "code": null, "e": 27033, "s": 27025, "text": "Output:" }, { "code": null, "e": 27076, "s": 27033, "text": "Program 2: Setting the value of CursorSize" }, { "code": "// C# program to illustrate the// Console.CursorSize Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { // Main Method static void Main(string[] args) { // Get the CursorSize Console.WriteLine(\"Current CursorSize: {0}\", Console.CursorSize); // Set the CursorSize Console.CursorSize = 100; // Get the CursorSize Console.Write(\"Current CursorSize: {0}\", Console.CursorSize); }}}", "e": 27676, "s": 27076, "text": null }, { "code": null, "e": 27684, "s": 27676, "text": "Output:" }, { "code": null, "e": 27738, "s": 27684, "text": "Note: See the width of the Cursor in both the images." }, { "code": null, "e": 27759, "s": 27738, "text": "CSharp-Console-Class" }, { "code": null, "e": 27762, "s": 27759, "text": "C#" }, { "code": null, "e": 27860, "s": 27762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27888, "s": 27860, "text": "C# Dictionary with examples" }, { "code": null, "e": 27903, "s": 27888, "text": "C# | Delegates" }, { "code": null, "e": 27926, "s": 27903, "text": "C# | Method Overriding" }, { "code": null, "e": 27948, "s": 27926, "text": "C# | Abstract Classes" }, { "code": null, "e": 27994, "s": 27948, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28017, "s": 27994, "text": "Extension Method in C#" }, { "code": null, "e": 28039, "s": 28017, "text": "C# | Class and Object" }, { "code": null, "e": 28057, "s": 28039, "text": "C# | Constructors" }, { "code": null, "e": 28097, "s": 28057, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
JavaTuples getValue() method - GeeksforGeeks
27 Aug, 2018 The getValue() method in org.javatuples is used to fetch the value of the TupleClassObject from the index passed as the parameter. This method can be used to any tuple class object of javatuples library. It returns a Object value which is the element present at the index, passed as parameter, of the TupleClassObject. Since the returned Value is of Object type, hence using getValue() loses the type-safety. Method Declaration: public final Object getValue(int pos) Syntax: Object val = TupleClassObject.getValue(int pos) Here TupleClassObject represents the JavaTuple Class object used like Unit, Quintet, Decade, etc. Parameters: This method takes pos as parameter where: pos– is the index at which the value of the TupleClassObject is to be known. TupleClassObject– represents the JavaTuple Class object used like Unit, Quintet, Decade, etc. Return Value: This method returns a Object value which is the element present at the index, passed as parameter, of the TupleClassObject. Below programs illustrate the various ways to use getValue() method: Program 1: Using getValue() with Unit class: // Below is a Java program to use getValue() method import java.util.*;import org.javatuples.Unit; class GfG { public static void main(String[] args) { // Creating an Unit with one value Unit<String> unit = Unit.with("GeeksforGeeks"); // Using getValue() method Object val = unit.getValue(0); System.out.println("Value at 0 = " + val); }} Output: Value at 0 = GeeksforGeeks Program 2: Using getValue() with Quartet class: // Below is a Java program to use getValue() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { Quartet<String, String, String, String> quartet = Quartet.with("GeeksforGeeks", "A computer portal", "for geeks", "by Sandeep Jain"); // Using getValue() method Object val = quartet.getValue(2); System.out.println("Value at 2 = " + val); }} Output: Value at 2 = for geeks Note: Similarly, it can be used with any other JavaTuple Class. Java-Functions JavaTuples Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 25559, "s": 25531, "text": "\n27 Aug, 2018" }, { "code": null, "e": 25968, "s": 25559, "text": "The getValue() method in org.javatuples is used to fetch the value of the TupleClassObject from the index passed as the parameter. This method can be used to any tuple class object of javatuples library. It returns a Object value which is the element present at the index, passed as parameter, of the TupleClassObject. Since the returned Value is of Object type, hence using getValue() loses the type-safety." }, { "code": null, "e": 25988, "s": 25968, "text": "Method Declaration:" }, { "code": null, "e": 26026, "s": 25988, "text": "public final Object getValue(int pos)" }, { "code": null, "e": 26034, "s": 26026, "text": "Syntax:" }, { "code": null, "e": 26082, "s": 26034, "text": "Object val = TupleClassObject.getValue(int pos)" }, { "code": null, "e": 26180, "s": 26082, "text": "Here TupleClassObject represents the JavaTuple Class object used like Unit, Quintet, Decade, etc." }, { "code": null, "e": 26234, "s": 26180, "text": "Parameters: This method takes pos as parameter where:" }, { "code": null, "e": 26311, "s": 26234, "text": "pos– is the index at which the value of the TupleClassObject is to be known." }, { "code": null, "e": 26405, "s": 26311, "text": "TupleClassObject– represents the JavaTuple Class object used like Unit, Quintet, Decade, etc." }, { "code": null, "e": 26543, "s": 26405, "text": "Return Value: This method returns a Object value which is the element present at the index, passed as parameter, of the TupleClassObject." }, { "code": null, "e": 26612, "s": 26543, "text": "Below programs illustrate the various ways to use getValue() method:" }, { "code": null, "e": 26657, "s": 26612, "text": "Program 1: Using getValue() with Unit class:" }, { "code": "// Below is a Java program to use getValue() method import java.util.*;import org.javatuples.Unit; class GfG { public static void main(String[] args) { // Creating an Unit with one value Unit<String> unit = Unit.with(\"GeeksforGeeks\"); // Using getValue() method Object val = unit.getValue(0); System.out.println(\"Value at 0 = \" + val); }}", "e": 27046, "s": 26657, "text": null }, { "code": null, "e": 27054, "s": 27046, "text": "Output:" }, { "code": null, "e": 27081, "s": 27054, "text": "Value at 0 = GeeksforGeeks" }, { "code": null, "e": 27129, "s": 27081, "text": "Program 2: Using getValue() with Quartet class:" }, { "code": "// Below is a Java program to use getValue() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { Quartet<String, String, String, String> quartet = Quartet.with(\"GeeksforGeeks\", \"A computer portal\", \"for geeks\", \"by Sandeep Jain\"); // Using getValue() method Object val = quartet.getValue(2); System.out.println(\"Value at 2 = \" + val); }}", "e": 27657, "s": 27129, "text": null }, { "code": null, "e": 27665, "s": 27657, "text": "Output:" }, { "code": null, "e": 27688, "s": 27665, "text": "Value at 2 = for geeks" }, { "code": null, "e": 27752, "s": 27688, "text": "Note: Similarly, it can be used with any other JavaTuple Class." }, { "code": null, "e": 27767, "s": 27752, "text": "Java-Functions" }, { "code": null, "e": 27778, "s": 27767, "text": "JavaTuples" }, { "code": null, "e": 27783, "s": 27778, "text": "Java" }, { "code": null, "e": 27788, "s": 27783, "text": "Java" }, { "code": null, "e": 27886, "s": 27788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27937, "s": 27886, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27952, "s": 27937, "text": "Stream In Java" }, { "code": null, "e": 27971, "s": 27952, "text": "Interfaces in Java" }, { "code": null, "e": 28002, "s": 27971, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28020, "s": 28002, "text": "ArrayList in Java" }, { "code": null, "e": 28052, "s": 28020, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28072, "s": 28052, "text": "Stack Class in Java" }, { "code": null, "e": 28104, "s": 28072, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28128, "s": 28104, "text": "Singleton Class in Java" } ]
Summation of GCD of all the pairs up to N - GeeksforGeeks
27 Dec, 2018 Given a number N, find sum of all GCDs that can be formed by selecting all the pairs from 1 to N.Examples: Input : 4 Output : 7 Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4 Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7 Input : 12 Output : 105 Input : 1 Output : 0 Input : 2 Output : 1 A Naive approach is to run two loops one inside the other. Select all pairs one by one, find GCD of every pair and then find sum of these GCDs. Time complexity of this approach is O(N2 * log(N)) Efficient Approach is based on following concepts: Euler’s Totient function ?(n) for an input n is count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively prime to 4, 2 numbers smaller or equal to 3 that are relatively prime to 3. And 4 numbers smaller than or equal to 5 that are relatively prime to 5.The idea is to convert given problem into sum of Euler Totient Functions.Sum of all GCDs where j is a part of pair is and j is greater element in pair: Sumj = ?(i=1 to j-1) gcd(i, j) Our final result is Result = ?(j=1 to N) Sumj The above equation can be written as : Sumj = ? g * count(g) For every possible GCD 'g' of j. Here count(g) represents count of pairs having GCD equals to g. For every such pair(i, j), we can write : gcd(i/g, j/g) = 1 We can re-write our previous equation as Sumj = ? d * phi(j/d) For every divisor d of j and phi[] is Euler Totient number Example : j = 12 and d = 3 is one of divisor of j so in order to calculate the sum of count of all pairs having 3 as gcd we can simple write it as => 3*phi[12/3] => 3*phi[4] => 3*2 => 6 Therefore sum of GCDs of all pairs where 12 is greater part of pair and 3 is GCD. GCD(3, 12) + GCD(9, 12) = 6. Complete Example : N = 4 Sum1 = 0 Sum2 = 1 [GCD(1, 2)] Sum3 = 2 [GCD(1, 3) + GCD(2, 3)] Sum4 = 4 [GCD(1, 4) + GCD(3, 4) + GCD(2, 4)] Result = Sum1 + Sum2 + Sum3 + Sum4 = 0 + 1 + 2 + 4 = 7 Below is the implementation of above idea. We pre-compute Euler Totient Functions and result for all numbers till a maximum value. The idea used in implementation is based this post.C++JavaPython3C#PHPC++// C++ approach of finding sum of GCD of all pairs#include<bits/stdc++.h>using namespace std; #define MAX 100001 // phi[i] stores euler totient function for i// result[j] stores result for value jlong long phi[MAX], result[MAX]; // Precomputation of phi[] numbers. Refer below link// for details : https://goo.gl/LUqdtYvoid computeTotient(){ // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i=2; i<MAX; i++) { if (!phi[i]) { phi[i] = i-1; for (int j = (i<<1); j<MAX; j+=i) { if (!phi[j]) phi[j] = j; phi[j] = (phi[j]/i)*(i-1); } } }} // Precomputes result for all numbers till MAXvoid sumOfGcdPairs(){ // Precompute all phi value computeTotient(); for (int i=1; i<MAX; ++i) { // Iterate throght all the divisors // of i. for (int j=2; i*j<MAX; ++j) result[i*j] += i*phi[j]; } // Add summation of previous calculated sum for (int i=2; i<MAX; i++) result[i] += result[i-1];} // Driver codeint main(){ // Function to calculate sum of all the GCD // pairs sumOfGcdPairs(); int N = 4; cout << "Summation of " << N << " = " << result[N] << endl;; N = 12; cout << "Summation of " << N << " = " << result[N] << endl; N = 5000; cout << "Summation of " << N << " = " << result[N] ; return 0;}Java// Java approach of finding // sum of GCD of all pairs.import java.lang.*; class GFG { static final int MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value jstatic long phi[] = new long[MAX];static long result[] = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void main(String[] args) { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; System.out.println("Summation of " + N + " = " + result[N]); N = 12; System.out.println("Summation of " + N + " = " + result[N]); N = 5000; System.out.print("Summation of " + N + " = " + +result[N]);}} // This code is contributed by Anant Agarwal.Python3# Python approach of finding# sum of GCD of all pairsMAX = 100001 # phi[i] stores euler # totient function for # i result[j] stores # result for value jphi = [0] * MAXresult = [0] * MAX # Precomputation of phi[]# numbers. Refer below link# for details : https://goo.gl/LUqdtYdef computeTotient(): # Refer https://goo.gl/LUqdtY phi[1] = 1 for i in range(2, MAX): if not phi[i]: phi[i] = i - 1 for j in range(i << 1, MAX, i): if not phi[j]: phi[j] = j phi[j] = ((phi[j] // i) * (i - 1)) # Precomputes result # for all numbers # till MAXdef sumOfGcdPairs(): # Precompute all phi value computeTotient() for i in range(MAX): # Iterate throght all # the divisors of i. for j in range(2, MAX): if i * j >= MAX: break result[i * j] += i * phi[j] # Add summation of # previous calculated sum for i in range(2, MAX): result[i] += result[i - 1] # Driver code# Function to calculate # sum of all the GCD pairssumOfGcdPairs() N = 4print("Summation of",N,"=",result[N])N = 12print("Summation of",N,"=",result[N])N = 5000print("Summation of",N,"=",result[N]) # This code is contributed # by Sanjit_Prasad.C#// C# approach of finding // sum of GCD of all pairs.using System; class GFG { static int MAX = 100001; // phi[i] stores euler totient// function for i result[j]// stores result for value jstatic long []phi = new long[MAX];static long []result = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous // calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void Main() { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; Console.WriteLine("Summation of " + N + " = " + result[N]); N = 12; Console.WriteLine("Summation of " + N + " = " + result[N]); N = 5000; Console.Write("Summation of " + N + " = " + +result[N]);}} // This code is contributed by Nitin Mittal.PHP<?php// PHP approach of finding sum of // GCD of all pairs $MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value j$phi = array_fill(0, $MAX, 0);$result = array_fill(0, $MAX, 0); // Precomputation of phi[] numbers. Refer // link for details : https://goo.gl/LUqdtYfunction computeTotient(){ global $MAX, $phi; // Refer https://goo.gl/LUqdtY $phi[1] = 1; for ($i = 2; $i < $MAX; $i++) { if (!$phi[$i]) { $phi[$i] = $i - 1; for ($j = ($i << 1); $j < $MAX; $j += $i) { if (!$phi[$j]) $phi[$j] = $j; $phi[$j] = ($phi[$j] / $i) * ($i - 1); } } }} // Precomputes result for all // numbers till MAXfunction sumOfGcdPairs(){ global $MAX, $phi, $result; // Precompute all phi value computeTotient(); for ($i = 1; $i < $MAX; ++$i) { // Iterate throght all the divisors // of i. for ($j = 2; $i * $j < $MAX; ++$j) $result[$i * $j] += $i * $phi[$j]; } // Add summation of previous calculated sum for ($i = 2; $i < $MAX; $i++) $result[$i] += $result[$i - 1];} // Driver code // Function to calculate sum of // all the GCD pairssumOfGcdPairs(); $N = 4;echo "Summation of " . $N . " = " . $result[$N] . "\n";$N = 12;echo "Summation of " . $N . " = " . $result[$N] . "\n";$N = 5000;echo "Summation of " . $N . " = " . $result[$N] . "\n"; // This code is contributed by mits?>Output:Summation of 4 = 7 Summation of 12 = 105 Summation of 5000 = 61567426 Time complexity: O(MAX*log(log MAX))Auxiliary space: O(MAX)Reference:https://www.quora.com/How-can-I-solve-the-problem-GCD-Extreme-on-SPOJ-SPOJ-com-Problem-GCDEXThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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.My Personal Notes arrow_drop_upSave The idea is to convert given problem into sum of Euler Totient Functions. Sum of all GCDs where j is a part of pair is and j is greater element in pair: Sumj = ?(i=1 to j-1) gcd(i, j) Our final result is Result = ?(j=1 to N) Sumj The above equation can be written as : Sumj = ? g * count(g) For every possible GCD 'g' of j. Here count(g) represents count of pairs having GCD equals to g. For every such pair(i, j), we can write : gcd(i/g, j/g) = 1 We can re-write our previous equation as Sumj = ? d * phi(j/d) For every divisor d of j and phi[] is Euler Totient number Example : j = 12 and d = 3 is one of divisor of j so in order to calculate the sum of count of all pairs having 3 as gcd we can simple write it as => 3*phi[12/3] => 3*phi[4] => 3*2 => 6 Therefore sum of GCDs of all pairs where 12 is greater part of pair and 3 is GCD. GCD(3, 12) + GCD(9, 12) = 6. Complete Example : N = 4 Sum1 = 0 Sum2 = 1 [GCD(1, 2)] Sum3 = 2 [GCD(1, 3) + GCD(2, 3)] Sum4 = 4 [GCD(1, 4) + GCD(3, 4) + GCD(2, 4)] Result = Sum1 + Sum2 + Sum3 + Sum4 = 0 + 1 + 2 + 4 = 7 Below is the implementation of above idea. We pre-compute Euler Totient Functions and result for all numbers till a maximum value. The idea used in implementation is based this post. C++ Java Python3 C# PHP // C++ approach of finding sum of GCD of all pairs#include<bits/stdc++.h>using namespace std; #define MAX 100001 // phi[i] stores euler totient function for i// result[j] stores result for value jlong long phi[MAX], result[MAX]; // Precomputation of phi[] numbers. Refer below link// for details : https://goo.gl/LUqdtYvoid computeTotient(){ // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i=2; i<MAX; i++) { if (!phi[i]) { phi[i] = i-1; for (int j = (i<<1); j<MAX; j+=i) { if (!phi[j]) phi[j] = j; phi[j] = (phi[j]/i)*(i-1); } } }} // Precomputes result for all numbers till MAXvoid sumOfGcdPairs(){ // Precompute all phi value computeTotient(); for (int i=1; i<MAX; ++i) { // Iterate throght all the divisors // of i. for (int j=2; i*j<MAX; ++j) result[i*j] += i*phi[j]; } // Add summation of previous calculated sum for (int i=2; i<MAX; i++) result[i] += result[i-1];} // Driver codeint main(){ // Function to calculate sum of all the GCD // pairs sumOfGcdPairs(); int N = 4; cout << "Summation of " << N << " = " << result[N] << endl;; N = 12; cout << "Summation of " << N << " = " << result[N] << endl; N = 5000; cout << "Summation of " << N << " = " << result[N] ; return 0;} // Java approach of finding // sum of GCD of all pairs.import java.lang.*; class GFG { static final int MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value jstatic long phi[] = new long[MAX];static long result[] = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void main(String[] args) { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; System.out.println("Summation of " + N + " = " + result[N]); N = 12; System.out.println("Summation of " + N + " = " + result[N]); N = 5000; System.out.print("Summation of " + N + " = " + +result[N]);}} // This code is contributed by Anant Agarwal. # Python approach of finding# sum of GCD of all pairsMAX = 100001 # phi[i] stores euler # totient function for # i result[j] stores # result for value jphi = [0] * MAXresult = [0] * MAX # Precomputation of phi[]# numbers. Refer below link# for details : https://goo.gl/LUqdtYdef computeTotient(): # Refer https://goo.gl/LUqdtY phi[1] = 1 for i in range(2, MAX): if not phi[i]: phi[i] = i - 1 for j in range(i << 1, MAX, i): if not phi[j]: phi[j] = j phi[j] = ((phi[j] // i) * (i - 1)) # Precomputes result # for all numbers # till MAXdef sumOfGcdPairs(): # Precompute all phi value computeTotient() for i in range(MAX): # Iterate throght all # the divisors of i. for j in range(2, MAX): if i * j >= MAX: break result[i * j] += i * phi[j] # Add summation of # previous calculated sum for i in range(2, MAX): result[i] += result[i - 1] # Driver code# Function to calculate # sum of all the GCD pairssumOfGcdPairs() N = 4print("Summation of",N,"=",result[N])N = 12print("Summation of",N,"=",result[N])N = 5000print("Summation of",N,"=",result[N]) # This code is contributed # by Sanjit_Prasad. // C# approach of finding // sum of GCD of all pairs.using System; class GFG { static int MAX = 100001; // phi[i] stores euler totient// function for i result[j]// stores result for value jstatic long []phi = new long[MAX];static long []result = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous // calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void Main() { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; Console.WriteLine("Summation of " + N + " = " + result[N]); N = 12; Console.WriteLine("Summation of " + N + " = " + result[N]); N = 5000; Console.Write("Summation of " + N + " = " + +result[N]);}} // This code is contributed by Nitin Mittal. <?php// PHP approach of finding sum of // GCD of all pairs $MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value j$phi = array_fill(0, $MAX, 0);$result = array_fill(0, $MAX, 0); // Precomputation of phi[] numbers. Refer // link for details : https://goo.gl/LUqdtYfunction computeTotient(){ global $MAX, $phi; // Refer https://goo.gl/LUqdtY $phi[1] = 1; for ($i = 2; $i < $MAX; $i++) { if (!$phi[$i]) { $phi[$i] = $i - 1; for ($j = ($i << 1); $j < $MAX; $j += $i) { if (!$phi[$j]) $phi[$j] = $j; $phi[$j] = ($phi[$j] / $i) * ($i - 1); } } }} // Precomputes result for all // numbers till MAXfunction sumOfGcdPairs(){ global $MAX, $phi, $result; // Precompute all phi value computeTotient(); for ($i = 1; $i < $MAX; ++$i) { // Iterate throght all the divisors // of i. for ($j = 2; $i * $j < $MAX; ++$j) $result[$i * $j] += $i * $phi[$j]; } // Add summation of previous calculated sum for ($i = 2; $i < $MAX; $i++) $result[$i] += $result[$i - 1];} // Driver code // Function to calculate sum of // all the GCD pairssumOfGcdPairs(); $N = 4;echo "Summation of " . $N . " = " . $result[$N] . "\n";$N = 12;echo "Summation of " . $N . " = " . $result[$N] . "\n";$N = 5000;echo "Summation of " . $N . " = " . $result[$N] . "\n"; // This code is contributed by mits?> Output: Summation of 4 = 7 Summation of 12 = 105 Summation of 5000 = 61567426 Time complexity: O(MAX*log(log MAX))Auxiliary space: O(MAX) Reference:https://www.quora.com/How-can-I-solve-the-problem-GCD-Extreme-on-SPOJ-SPOJ-com-Problem-GCDEX This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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 Sanjit_Prasad Mithun Kumar GCD-LCM Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 25907, "s": 25879, "text": "\n27 Dec, 2018" }, { "code": null, "e": 26014, "s": 25907, "text": "Given a number N, find sum of all GCDs that can be formed by selecting all the pairs from 1 to N.Examples:" }, { "code": null, "e": 26284, "s": 26014, "text": "Input : 4\nOutput : 7\nExplanation: \nNumbers from 1 to 4 are: 1, 2, 3, 4\nResult = gcd(1,2) + gcd(1,3) + gcd(1,4) + \n gcd(2,3) + gcd(2,4) + gcd(3,4)\n = 1 + 1 + 1 + 1 + 2 + 1\n = 7\n\nInput : 12\nOutput : 105\n\nInput : 1\nOutput : 0\n\nInput : 2\nOutput : 1\n" }, { "code": null, "e": 26479, "s": 26284, "text": "A Naive approach is to run two loops one inside the other. Select all pairs one by one, find GCD of every pair and then find sum of these GCDs. Time complexity of this approach is O(N2 * log(N))" }, { "code": null, "e": 26530, "s": 26479, "text": "Efficient Approach is based on following concepts:" }, { "code": null, "e": 36470, "s": 26530, "text": "Euler’s Totient function ?(n) for an input n is count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively prime to 4, 2 numbers smaller or equal to 3 that are relatively prime to 3. And 4 numbers smaller than or equal to 5 that are relatively prime to 5.The idea is to convert given problem into sum of Euler Totient Functions.Sum of all GCDs where j is a part of\npair is and j is greater element in pair:\nSumj = ?(i=1 to j-1) gcd(i, j)\nOur final result is \nResult = ?(j=1 to N) Sumj\n\nThe above equation can be written as :\nSumj = ? g * count(g) \nFor every possible GCD 'g' of j. Here count(g)\nrepresents count of pairs having GCD equals to\ng. For every such pair(i, j), we can write :\n gcd(i/g, j/g) = 1\n\nWe can re-write our previous equation as\nSumj = ? d * phi(j/d) \nFor every divisor d of j and phi[] is Euler\nTotient number \n\nExample : j = 12 and d = 3 is one of divisor \nof j so in order to calculate the sum of count\nof all pairs having 3 as gcd we can simple write\nit as \n=> 3*phi[12/3] \n=> 3*phi[4]\n=> 3*2\n=> 6\n\nTherefore sum of GCDs of all pairs where 12 is \ngreater part of pair and 3 is GCD.\nGCD(3, 12) + GCD(9, 12) = 6.\n\nComplete Example : \nN = 4\nSum1 = 0\nSum2 = 1 [GCD(1, 2)]\nSum3 = 2 [GCD(1, 3) + GCD(2, 3)]\nSum4 = 4 [GCD(1, 4) + GCD(3, 4) + GCD(2, 4)]\n\nResult = Sum1 + Sum2 + Sum3 + Sum4\n = 0 + 1 + 2 + 4\n = 7\n Below is the implementation of above idea. We pre-compute Euler Totient Functions and result for all numbers till a maximum value. The idea used in implementation is based this post.C++JavaPython3C#PHPC++// C++ approach of finding sum of GCD of all pairs#include<bits/stdc++.h>using namespace std; #define MAX 100001 // phi[i] stores euler totient function for i// result[j] stores result for value jlong long phi[MAX], result[MAX]; // Precomputation of phi[] numbers. Refer below link// for details : https://goo.gl/LUqdtYvoid computeTotient(){ // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i=2; i<MAX; i++) { if (!phi[i]) { phi[i] = i-1; for (int j = (i<<1); j<MAX; j+=i) { if (!phi[j]) phi[j] = j; phi[j] = (phi[j]/i)*(i-1); } } }} // Precomputes result for all numbers till MAXvoid sumOfGcdPairs(){ // Precompute all phi value computeTotient(); for (int i=1; i<MAX; ++i) { // Iterate throght all the divisors // of i. for (int j=2; i*j<MAX; ++j) result[i*j] += i*phi[j]; } // Add summation of previous calculated sum for (int i=2; i<MAX; i++) result[i] += result[i-1];} // Driver codeint main(){ // Function to calculate sum of all the GCD // pairs sumOfGcdPairs(); int N = 4; cout << \"Summation of \" << N << \" = \" << result[N] << endl;; N = 12; cout << \"Summation of \" << N << \" = \" << result[N] << endl; N = 5000; cout << \"Summation of \" << N << \" = \" << result[N] ; return 0;}Java// Java approach of finding // sum of GCD of all pairs.import java.lang.*; class GFG { static final int MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value jstatic long phi[] = new long[MAX];static long result[] = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void main(String[] args) { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; System.out.println(\"Summation of \" + N + \" = \" + result[N]); N = 12; System.out.println(\"Summation of \" + N + \" = \" + result[N]); N = 5000; System.out.print(\"Summation of \" + N + \" = \" + +result[N]);}} // This code is contributed by Anant Agarwal.Python3# Python approach of finding# sum of GCD of all pairsMAX = 100001 # phi[i] stores euler # totient function for # i result[j] stores # result for value jphi = [0] * MAXresult = [0] * MAX # Precomputation of phi[]# numbers. Refer below link# for details : https://goo.gl/LUqdtYdef computeTotient(): # Refer https://goo.gl/LUqdtY phi[1] = 1 for i in range(2, MAX): if not phi[i]: phi[i] = i - 1 for j in range(i << 1, MAX, i): if not phi[j]: phi[j] = j phi[j] = ((phi[j] // i) * (i - 1)) # Precomputes result # for all numbers # till MAXdef sumOfGcdPairs(): # Precompute all phi value computeTotient() for i in range(MAX): # Iterate throght all # the divisors of i. for j in range(2, MAX): if i * j >= MAX: break result[i * j] += i * phi[j] # Add summation of # previous calculated sum for i in range(2, MAX): result[i] += result[i - 1] # Driver code# Function to calculate # sum of all the GCD pairssumOfGcdPairs() N = 4print(\"Summation of\",N,\"=\",result[N])N = 12print(\"Summation of\",N,\"=\",result[N])N = 5000print(\"Summation of\",N,\"=\",result[N]) # This code is contributed # by Sanjit_Prasad.C#// C# approach of finding // sum of GCD of all pairs.using System; class GFG { static int MAX = 100001; // phi[i] stores euler totient// function for i result[j]// stores result for value jstatic long []phi = new long[MAX];static long []result = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous // calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void Main() { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; Console.WriteLine(\"Summation of \" + N + \" = \" + result[N]); N = 12; Console.WriteLine(\"Summation of \" + N + \" = \" + result[N]); N = 5000; Console.Write(\"Summation of \" + N + \" = \" + +result[N]);}} // This code is contributed by Nitin Mittal.PHP<?php// PHP approach of finding sum of // GCD of all pairs $MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value j$phi = array_fill(0, $MAX, 0);$result = array_fill(0, $MAX, 0); // Precomputation of phi[] numbers. Refer // link for details : https://goo.gl/LUqdtYfunction computeTotient(){ global $MAX, $phi; // Refer https://goo.gl/LUqdtY $phi[1] = 1; for ($i = 2; $i < $MAX; $i++) { if (!$phi[$i]) { $phi[$i] = $i - 1; for ($j = ($i << 1); $j < $MAX; $j += $i) { if (!$phi[$j]) $phi[$j] = $j; $phi[$j] = ($phi[$j] / $i) * ($i - 1); } } }} // Precomputes result for all // numbers till MAXfunction sumOfGcdPairs(){ global $MAX, $phi, $result; // Precompute all phi value computeTotient(); for ($i = 1; $i < $MAX; ++$i) { // Iterate throght all the divisors // of i. for ($j = 2; $i * $j < $MAX; ++$j) $result[$i * $j] += $i * $phi[$j]; } // Add summation of previous calculated sum for ($i = 2; $i < $MAX; $i++) $result[$i] += $result[$i - 1];} // Driver code // Function to calculate sum of // all the GCD pairssumOfGcdPairs(); $N = 4;echo \"Summation of \" . $N . \" = \" . $result[$N] . \"\\n\";$N = 12;echo \"Summation of \" . $N . \" = \" . $result[$N] . \"\\n\";$N = 5000;echo \"Summation of \" . $N . \" = \" . $result[$N] . \"\\n\"; // This code is contributed by mits?>Output:Summation of 4 = 7\nSummation of 12 = 105\nSummation of 5000 = 61567426\nTime complexity: O(MAX*log(log MAX))Auxiliary space: O(MAX)Reference:https://www.quora.com/How-can-I-solve-the-problem-GCD-Extreme-on-SPOJ-SPOJ-com-Problem-GCDEXThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 36544, "s": 36470, "text": "The idea is to convert given problem into sum of Euler Totient Functions." }, { "code": null, "e": 37558, "s": 36544, "text": "Sum of all GCDs where j is a part of\npair is and j is greater element in pair:\nSumj = ?(i=1 to j-1) gcd(i, j)\nOur final result is \nResult = ?(j=1 to N) Sumj\n\nThe above equation can be written as :\nSumj = ? g * count(g) \nFor every possible GCD 'g' of j. Here count(g)\nrepresents count of pairs having GCD equals to\ng. For every such pair(i, j), we can write :\n gcd(i/g, j/g) = 1\n\nWe can re-write our previous equation as\nSumj = ? d * phi(j/d) \nFor every divisor d of j and phi[] is Euler\nTotient number \n\nExample : j = 12 and d = 3 is one of divisor \nof j so in order to calculate the sum of count\nof all pairs having 3 as gcd we can simple write\nit as \n=> 3*phi[12/3] \n=> 3*phi[4]\n=> 3*2\n=> 6\n\nTherefore sum of GCDs of all pairs where 12 is \ngreater part of pair and 3 is GCD.\nGCD(3, 12) + GCD(9, 12) = 6.\n\nComplete Example : \nN = 4\nSum1 = 0\nSum2 = 1 [GCD(1, 2)]\nSum3 = 2 [GCD(1, 3) + GCD(2, 3)]\nSum4 = 4 [GCD(1, 4) + GCD(3, 4) + GCD(2, 4)]\n\nResult = Sum1 + Sum2 + Sum3 + Sum4\n = 0 + 1 + 2 + 4\n = 7\n " }, { "code": null, "e": 37741, "s": 37558, "text": "Below is the implementation of above idea. We pre-compute Euler Totient Functions and result for all numbers till a maximum value. The idea used in implementation is based this post." }, { "code": null, "e": 37745, "s": 37741, "text": "C++" }, { "code": null, "e": 37750, "s": 37745, "text": "Java" }, { "code": null, "e": 37758, "s": 37750, "text": "Python3" }, { "code": null, "e": 37761, "s": 37758, "text": "C#" }, { "code": null, "e": 37765, "s": 37761, "text": "PHP" }, { "code": "// C++ approach of finding sum of GCD of all pairs#include<bits/stdc++.h>using namespace std; #define MAX 100001 // phi[i] stores euler totient function for i// result[j] stores result for value jlong long phi[MAX], result[MAX]; // Precomputation of phi[] numbers. Refer below link// for details : https://goo.gl/LUqdtYvoid computeTotient(){ // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i=2; i<MAX; i++) { if (!phi[i]) { phi[i] = i-1; for (int j = (i<<1); j<MAX; j+=i) { if (!phi[j]) phi[j] = j; phi[j] = (phi[j]/i)*(i-1); } } }} // Precomputes result for all numbers till MAXvoid sumOfGcdPairs(){ // Precompute all phi value computeTotient(); for (int i=1; i<MAX; ++i) { // Iterate throght all the divisors // of i. for (int j=2; i*j<MAX; ++j) result[i*j] += i*phi[j]; } // Add summation of previous calculated sum for (int i=2; i<MAX; i++) result[i] += result[i-1];} // Driver codeint main(){ // Function to calculate sum of all the GCD // pairs sumOfGcdPairs(); int N = 4; cout << \"Summation of \" << N << \" = \" << result[N] << endl;; N = 12; cout << \"Summation of \" << N << \" = \" << result[N] << endl; N = 5000; cout << \"Summation of \" << N << \" = \" << result[N] ; return 0;}", "e": 39207, "s": 37765, "text": null }, { "code": "// Java approach of finding // sum of GCD of all pairs.import java.lang.*; class GFG { static final int MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value jstatic long phi[] = new long[MAX];static long result[] = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void main(String[] args) { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; System.out.println(\"Summation of \" + N + \" = \" + result[N]); N = 12; System.out.println(\"Summation of \" + N + \" = \" + result[N]); N = 5000; System.out.print(\"Summation of \" + N + \" = \" + +result[N]);}} // This code is contributed by Anant Agarwal.", "e": 40825, "s": 39207, "text": null }, { "code": "# Python approach of finding# sum of GCD of all pairsMAX = 100001 # phi[i] stores euler # totient function for # i result[j] stores # result for value jphi = [0] * MAXresult = [0] * MAX # Precomputation of phi[]# numbers. Refer below link# for details : https://goo.gl/LUqdtYdef computeTotient(): # Refer https://goo.gl/LUqdtY phi[1] = 1 for i in range(2, MAX): if not phi[i]: phi[i] = i - 1 for j in range(i << 1, MAX, i): if not phi[j]: phi[j] = j phi[j] = ((phi[j] // i) * (i - 1)) # Precomputes result # for all numbers # till MAXdef sumOfGcdPairs(): # Precompute all phi value computeTotient() for i in range(MAX): # Iterate throght all # the divisors of i. for j in range(2, MAX): if i * j >= MAX: break result[i * j] += i * phi[j] # Add summation of # previous calculated sum for i in range(2, MAX): result[i] += result[i - 1] # Driver code# Function to calculate # sum of all the GCD pairssumOfGcdPairs() N = 4print(\"Summation of\",N,\"=\",result[N])N = 12print(\"Summation of\",N,\"=\",result[N])N = 5000print(\"Summation of\",N,\"=\",result[N]) # This code is contributed # by Sanjit_Prasad.", "e": 42142, "s": 40825, "text": null }, { "code": "// C# approach of finding // sum of GCD of all pairs.using System; class GFG { static int MAX = 100001; // phi[i] stores euler totient// function for i result[j]// stores result for value jstatic long []phi = new long[MAX];static long []result = new long[MAX]; // Precomputation of phi[] numbers.// Refer below link for details :// https://goo.gl/LUqdtYstatic void computeTotient() { // Refer https://goo.gl/LUqdtY phi[1] = 1; for (int i = 2; i < MAX; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = (i << 1); j < MAX; j += i) { if (phi[j] == 0) phi[j] = j; phi[j] = (phi[j] / i) * (i - 1); } } }} // Precomputes result for all// numbers till MAXstatic void sumOfGcdPairs() { // Precompute all phi value computeTotient(); for (int i = 1; i < MAX; ++i) { // Iterate throght all the // divisors of i. for (int j = 2; i * j < MAX; ++j) result[i * j] += i * phi[j]; } // Add summation of previous // calculated sum for (int i = 2; i < MAX; i++) result[i] += result[i - 1];} // Driver codepublic static void Main() { // Function to calculate sum of // all the GCD pairs sumOfGcdPairs(); int N = 4; Console.WriteLine(\"Summation of \" + N + \" = \" + result[N]); N = 12; Console.WriteLine(\"Summation of \" + N + \" = \" + result[N]); N = 5000; Console.Write(\"Summation of \" + N + \" = \" + +result[N]);}} // This code is contributed by Nitin Mittal.", "e": 43726, "s": 42142, "text": null }, { "code": "<?php// PHP approach of finding sum of // GCD of all pairs $MAX = 100001; // phi[i] stores euler totient function for i// result[j] stores result for value j$phi = array_fill(0, $MAX, 0);$result = array_fill(0, $MAX, 0); // Precomputation of phi[] numbers. Refer // link for details : https://goo.gl/LUqdtYfunction computeTotient(){ global $MAX, $phi; // Refer https://goo.gl/LUqdtY $phi[1] = 1; for ($i = 2; $i < $MAX; $i++) { if (!$phi[$i]) { $phi[$i] = $i - 1; for ($j = ($i << 1); $j < $MAX; $j += $i) { if (!$phi[$j]) $phi[$j] = $j; $phi[$j] = ($phi[$j] / $i) * ($i - 1); } } }} // Precomputes result for all // numbers till MAXfunction sumOfGcdPairs(){ global $MAX, $phi, $result; // Precompute all phi value computeTotient(); for ($i = 1; $i < $MAX; ++$i) { // Iterate throght all the divisors // of i. for ($j = 2; $i * $j < $MAX; ++$j) $result[$i * $j] += $i * $phi[$j]; } // Add summation of previous calculated sum for ($i = 2; $i < $MAX; $i++) $result[$i] += $result[$i - 1];} // Driver code // Function to calculate sum of // all the GCD pairssumOfGcdPairs(); $N = 4;echo \"Summation of \" . $N . \" = \" . $result[$N] . \"\\n\";$N = 12;echo \"Summation of \" . $N . \" = \" . $result[$N] . \"\\n\";$N = 5000;echo \"Summation of \" . $N . \" = \" . $result[$N] . \"\\n\"; // This code is contributed by mits?>", "e": 45264, "s": 43726, "text": null }, { "code": null, "e": 45272, "s": 45264, "text": "Output:" }, { "code": null, "e": 45343, "s": 45272, "text": "Summation of 4 = 7\nSummation of 12 = 105\nSummation of 5000 = 61567426\n" }, { "code": null, "e": 45403, "s": 45343, "text": "Time complexity: O(MAX*log(log MAX))Auxiliary space: O(MAX)" }, { "code": null, "e": 45506, "s": 45403, "text": "Reference:https://www.quora.com/How-can-I-solve-the-problem-GCD-Extreme-on-SPOJ-SPOJ-com-Problem-GCDEX" }, { "code": null, "e": 45808, "s": 45506, "text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 45933, "s": 45808, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 45946, "s": 45933, "text": "nitin mittal" }, { "code": null, "e": 45960, "s": 45946, "text": "Sanjit_Prasad" }, { "code": null, "e": 45973, "s": 45960, "text": "Mithun Kumar" }, { "code": null, "e": 45981, "s": 45973, "text": "GCD-LCM" }, { "code": null, "e": 45994, "s": 45981, "text": "Mathematical" }, { "code": null, "e": 46007, "s": 45994, "text": "Mathematical" }, { "code": null, "e": 46105, "s": 46007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46129, "s": 46105, "text": "Merge two sorted arrays" }, { "code": null, "e": 46172, "s": 46129, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 46186, "s": 46172, "text": "Prime Numbers" }, { "code": null, "e": 46259, "s": 46186, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 46300, "s": 46259, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 46343, "s": 46300, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 46364, "s": 46343, "text": "Operators in C / C++" }, { "code": null, "e": 46398, "s": 46364, "text": "Program for factorial of a number" }, { "code": null, "e": 46451, "s": 46398, "text": "Find minimum number of coins that make a given value" } ]
How to write multi-line strings in template literals ? - GeeksforGeeks
03 Dec, 2021 Template literals are introduced in ES6 and by this, we use strings in a modern way. Normally for defining string, we use double/single quotes ( ” ” or ‘ ‘ ) in JavaScript. But in template literals, we use backtick ( ` ` ). Let us see how to write multiline strings in template literals. Example 1: We write multiline string by template literals. HTML <script> const multilineString = `How are you doing I am fine`; console.log(multilineString);</script> Output: How are you doing I am fine Example 2: If you use double/single quote to write multiline string then we use the newline character (\n). Use an extra backslash ( \ ) after every newline character (\n), this backslash tells the JavaScript engine that the string is not over yet. HTML <script> var multilineString = "How \n\ are you \n\ doing \n\ I am fine"; console.log(multilineString);</script> Output: How are you doing I am fine JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26569, "s": 26541, "text": "\n03 Dec, 2021" }, { "code": null, "e": 26793, "s": 26569, "text": "Template literals are introduced in ES6 and by this, we use strings in a modern way. Normally for defining string, we use double/single quotes ( ” ” or ‘ ‘ ) in JavaScript. But in template literals, we use backtick ( ` ` )." }, { "code": null, "e": 26857, "s": 26793, "text": "Let us see how to write multiline strings in template literals." }, { "code": null, "e": 26916, "s": 26857, "text": "Example 1: We write multiline string by template literals." }, { "code": null, "e": 26921, "s": 26916, "text": "HTML" }, { "code": "<script> const multilineString = `How are you doing I am fine`; console.log(multilineString);</script>", "e": 27046, "s": 26921, "text": null }, { "code": null, "e": 27054, "s": 27046, "text": "Output:" }, { "code": null, "e": 27094, "s": 27054, "text": "How \nare you \ndoing \nI am fine" }, { "code": null, "e": 27344, "s": 27094, "text": "Example 2: If you use double/single quote to write multiline string then we use the newline character (\\n). Use an extra backslash ( \\ ) after every newline character (\\n), this backslash tells the JavaScript engine that the string is not over yet." }, { "code": null, "e": 27349, "s": 27344, "text": "HTML" }, { "code": "<script> var multilineString = \"How \\n\\ are you \\n\\ doing \\n\\ I am fine\"; console.log(multilineString);</script>", "e": 27487, "s": 27349, "text": null }, { "code": null, "e": 27495, "s": 27487, "text": "Output:" }, { "code": null, "e": 27524, "s": 27495, "text": "How \nare you\ndoing\nI am fine" }, { "code": null, "e": 27545, "s": 27524, "text": "JavaScript-Questions" }, { "code": null, "e": 27552, "s": 27545, "text": "Picked" }, { "code": null, "e": 27563, "s": 27552, "text": "JavaScript" }, { "code": null, "e": 27580, "s": 27563, "text": "Web Technologies" }, { "code": null, "e": 27678, "s": 27580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27718, "s": 27678, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27779, "s": 27718, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27820, "s": 27779, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27842, "s": 27820, "text": "JavaScript | Promises" }, { "code": null, "e": 27896, "s": 27842, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27936, "s": 27896, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27969, "s": 27936, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28012, "s": 27969, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28062, "s": 28012, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python - tensorflow.math.sqrt() - GeeksforGeeks
16 Jun, 2020 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. sqrt() is used to compute element wise square root. Syntax: tensorflow.math.sqrt(x, name) Parameters: x: It’s a tensor. Allowed dtypes are bfloat16, half, float32, float64, complex64, complex128. name(optional): It defines the name for the operation. Returns: It returns a tensor. Example 1: Python3 # importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ 5, 7, 9, 15], dtype = tf.float64) # Printing the input tensorprint('a: ', a) # Calculating resultres = tf.math.sqrt(a) # Printing the resultprint('Result: ', res) Output: a: tf.Tensor([ 5. 7. 9. 15.], shape=(4, ), dtype=float64) Result: tf.Tensor([2.23606798 2.64575131 3. 3.87298335], shape=(4, ), dtype=float64) Example 2: Visualization Python3 # import tensorflow as tfimport matplotlib.pyplot as plt # Initializing the input tensora = tf.constant([ 5, 7, 9, 15], dtype = tf.float64) # Calculating tangentres = tf.math.sqrt(a) # Plotting the graphplt.plot(a, res, color ='green')plt.title('tensorflow.math.sqrt')plt.xlabel('Input')plt.ylabel('Result')plt.show() Output: Python Tensorflow-math-functions Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Jun, 2020" }, { "code": null, "e": 25668, "s": 25537, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks." }, { "code": null, "e": 25720, "s": 25668, "text": "sqrt() is used to compute element wise square root." }, { "code": null, "e": 25758, "s": 25720, "text": "Syntax: tensorflow.math.sqrt(x, name)" }, { "code": null, "e": 25770, "s": 25758, "text": "Parameters:" }, { "code": null, "e": 25864, "s": 25770, "text": "x: It’s a tensor. Allowed dtypes are bfloat16, half, float32, float64, complex64, complex128." }, { "code": null, "e": 25919, "s": 25864, "text": "name(optional): It defines the name for the operation." }, { "code": null, "e": 25949, "s": 25919, "text": "Returns: It returns a tensor." }, { "code": null, "e": 25960, "s": 25949, "text": "Example 1:" }, { "code": null, "e": 25968, "s": 25960, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ 5, 7, 9, 15], dtype = tf.float64) # Printing the input tensorprint('a: ', a) # Calculating resultres = tf.math.sqrt(a) # Printing the resultprint('Result: ', res)", "e": 26231, "s": 25968, "text": null }, { "code": null, "e": 26239, "s": 26231, "text": "Output:" }, { "code": null, "e": 26398, "s": 26239, "text": "a: tf.Tensor([ 5. 7. 9. 15.], shape=(4, ), dtype=float64)\nResult: tf.Tensor([2.23606798 2.64575131 3. 3.87298335], shape=(4, ), dtype=float64)\n\n\n\n" }, { "code": null, "e": 26423, "s": 26398, "text": "Example 2: Visualization" }, { "code": null, "e": 26431, "s": 26423, "text": "Python3" }, { "code": "# import tensorflow as tfimport matplotlib.pyplot as plt # Initializing the input tensora = tf.constant([ 5, 7, 9, 15], dtype = tf.float64) # Calculating tangentres = tf.math.sqrt(a) # Plotting the graphplt.plot(a, res, color ='green')plt.title('tensorflow.math.sqrt')plt.xlabel('Input')plt.ylabel('Result')plt.show()", "e": 26752, "s": 26431, "text": null }, { "code": null, "e": 26760, "s": 26752, "text": "Output:" }, { "code": null, "e": 26793, "s": 26760, "text": "Python Tensorflow-math-functions" }, { "code": null, "e": 26811, "s": 26793, "text": "Python-Tensorflow" }, { "code": null, "e": 26818, "s": 26811, "text": "Python" }, { "code": null, "e": 26916, "s": 26818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26948, "s": 26916, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26990, "s": 26948, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27032, "s": 26990, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27088, "s": 27032, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27115, "s": 27088, "text": "Python Classes and Objects" }, { "code": null, "e": 27154, "s": 27115, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27185, "s": 27154, "text": "Python | os.path.join() method" }, { "code": null, "e": 27207, "s": 27185, "text": "Defaultdict in Python" }, { "code": null, "e": 27236, "s": 27207, "text": "Create a directory in Python" } ]
How to Extract time from timestamp in R ? - GeeksforGeeks
21 Apr, 2021 In this article, we are going to see how to extract time from timestamp in the R Programming language. Method 1: Using POSIXct class in R We can store a date variable in the form of a string variable, and then convert it to a general format timestamp. POSIXct method can be used which converts a date-time string variable into a POSIXct class. as.POSIXct method is used which stores both the date and time along with an associated time zone in R. The POSIXlt class maintains the record of the hour, minute, second, day, month, and year separately. POSIXct class saves the date and time in seconds where in the number of seconds begin at 1 January 1970. This method is used for storage and computation. The format() method can be used to then extract the timestamp from the datetime object. The format() method has the following syntax : format(date, format =) , where the first parameter illustrates the date and second the specific format specifier Code: R # declaring string variabledate <- "01/08/2020 12:48:00" # conversion of date variable into # POSIXct format date <- as.POSIXct(date, format = "%m/%d/%Y %H:%M:%S") # print original complete dateprint ("Original TimeStamp: ")print (date) # extract time from datetime <- format(date, format = "%H:%M:%S")print("Extraction of time: ")print(time) Output [1] "Original TimeStamp: " [1] "2020-01-08 12:48:00 UTC" [1] "Extraction of time: " [1] "12:48:00" Method 2: Using Lubridate package in R Lubridate package in R is used to store and modify the date formats. It has a large variety of parse functions available, which allow the access of dates and various formats with great simplicity. dmy_hms() method in this package is the most common method, used to store the dates in the standard format (data-month-year-hour-minute-second). In case the time zone(tz) is not specified, the standard UTC zone is used for computations. Specific information can be extracted from this object, without affecting the original datetime object. The format() method is used to extract time from this lubridate datetime object. The dmy_hms() method has the following syntax : dmy_hms(date), which returns the date in complete time stamp format. Code: R # invoking specific library library(lubridate) # declaring string variabledate <- dmy_hms("01/08/2020 11:18:56") # print original complete dateprint ("Original TimeStamp: ")print (date) # extract time from datetime <- format(date, format = "%H:%M:%S")print("Extraction of time: ")print(time) Output [1] "Original TimeStamp: " [1] "2020-01-08 11:18:56 UTC" [1] "Extraction of time: " [1] "11:18:56" Method 3: Using hms package in R hms package in R can also be used to perform access, storage, and perform arithmetic operations on date-time objects. The package can first be installed into the environment using the command : install.packages("hms") The package can then be included to provide methods to work with date-time object manipulations. The library provides a function as_hms(date) which is used to directly access the time stamp from the date-time object. hms stands for hour minutes and seconds. The string type date needs to be converted to a standard POSIXct format first, in order to apply this method. The as_hms(date) method takes as input the complete datetime object and extracts the timestamp from it. Code: R require("hms") # declaring string variabledate <- "01/08/2020 12:15:38" # conversion of date variable into# POSIXct format date <- as.POSIXct(date, format = "%m/%d/%Y %H:%M:%S") # print original complete dateprint ("Original TimeStamp: ")print (date) # extract time from datetime <- as_hms(date)print("Extraction of time: ")print(time) Output [1] "Original TimeStamp: " [1] "2020-01-08 12:15:38 IST" [1] "Extraction of time: " [1] 12:15:38 Picked R-DateTime R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n21 Apr, 2021" }, { "code": null, "e": 26591, "s": 26487, "text": "In this article, we are going to see how to extract time from timestamp in the R Programming language. " }, { "code": null, "e": 26626, "s": 26591, "text": "Method 1: Using POSIXct class in R" }, { "code": null, "e": 27279, "s": 26626, "text": "We can store a date variable in the form of a string variable, and then convert it to a general format timestamp. POSIXct method can be used which converts a date-time string variable into a POSIXct class. as.POSIXct method is used which stores both the date and time along with an associated time zone in R. The POSIXlt class maintains the record of the hour, minute, second, day, month, and year separately. POSIXct class saves the date and time in seconds where in the number of seconds begin at 1 January 1970. This method is used for storage and computation. The format() method can be used to then extract the timestamp from the datetime object. " }, { "code": null, "e": 27327, "s": 27279, "text": "The format() method has the following syntax : " }, { "code": null, "e": 27353, "s": 27327, "text": "format(date, format =) , " }, { "code": null, "e": 27441, "s": 27353, "text": "where the first parameter illustrates the date and second the specific format specifier" }, { "code": null, "e": 27447, "s": 27441, "text": "Code:" }, { "code": null, "e": 27449, "s": 27447, "text": "R" }, { "code": "# declaring string variabledate <- \"01/08/2020 12:48:00\" # conversion of date variable into # POSIXct format date <- as.POSIXct(date, format = \"%m/%d/%Y %H:%M:%S\") # print original complete dateprint (\"Original TimeStamp: \")print (date) # extract time from datetime <- format(date, format = \"%H:%M:%S\")print(\"Extraction of time: \")print(time)", "e": 27795, "s": 27449, "text": null }, { "code": null, "e": 27802, "s": 27795, "text": "Output" }, { "code": null, "e": 27901, "s": 27802, "text": "[1] \"Original TimeStamp: \"\n[1] \"2020-01-08 12:48:00 UTC\"\n[1] \"Extraction of time: \"\n[1] \"12:48:00\"" }, { "code": null, "e": 27940, "s": 27901, "text": "Method 2: Using Lubridate package in R" }, { "code": null, "e": 28560, "s": 27940, "text": "Lubridate package in R is used to store and modify the date formats. It has a large variety of parse functions available, which allow the access of dates and various formats with great simplicity. dmy_hms() method in this package is the most common method, used to store the dates in the standard format (data-month-year-hour-minute-second). In case the time zone(tz) is not specified, the standard UTC zone is used for computations. Specific information can be extracted from this object, without affecting the original datetime object. The format() method is used to extract time from this lubridate datetime object." }, { "code": null, "e": 28609, "s": 28560, "text": "The dmy_hms() method has the following syntax : " }, { "code": null, "e": 28625, "s": 28609, "text": "dmy_hms(date), " }, { "code": null, "e": 28679, "s": 28625, "text": "which returns the date in complete time stamp format." }, { "code": null, "e": 28685, "s": 28679, "text": "Code:" }, { "code": null, "e": 28687, "s": 28685, "text": "R" }, { "code": "# invoking specific library library(lubridate) # declaring string variabledate <- dmy_hms(\"01/08/2020 11:18:56\") # print original complete dateprint (\"Original TimeStamp: \")print (date) # extract time from datetime <- format(date, format = \"%H:%M:%S\")print(\"Extraction of time: \")print(time)", "e": 28982, "s": 28687, "text": null }, { "code": null, "e": 28989, "s": 28982, "text": "Output" }, { "code": null, "e": 29088, "s": 28989, "text": "[1] \"Original TimeStamp: \"\n[1] \"2020-01-08 11:18:56 UTC\"\n[1] \"Extraction of time: \"\n[1] \"11:18:56\"" }, { "code": null, "e": 29121, "s": 29088, "text": "Method 3: Using hms package in R" }, { "code": null, "e": 29315, "s": 29121, "text": "hms package in R can also be used to perform access, storage, and perform arithmetic operations on date-time objects. The package can first be installed into the environment using the command :" }, { "code": null, "e": 29339, "s": 29315, "text": "install.packages(\"hms\")" }, { "code": null, "e": 29708, "s": 29339, "text": "The package can then be included to provide methods to work with date-time object manipulations. The library provides a function as_hms(date) which is used to directly access the time stamp from the date-time object. hms stands for hour minutes and seconds. The string type date needs to be converted to a standard POSIXct format first, in order to apply this method. " }, { "code": null, "e": 29812, "s": 29708, "text": "The as_hms(date) method takes as input the complete datetime object and extracts the timestamp from it." }, { "code": null, "e": 29818, "s": 29812, "text": "Code:" }, { "code": null, "e": 29820, "s": 29818, "text": "R" }, { "code": "require(\"hms\") # declaring string variabledate <- \"01/08/2020 12:15:38\" # conversion of date variable into# POSIXct format date <- as.POSIXct(date, format = \"%m/%d/%Y %H:%M:%S\") # print original complete dateprint (\"Original TimeStamp: \")print (date) # extract time from datetime <- as_hms(date)print(\"Extraction of time: \")print(time)", "e": 30160, "s": 29820, "text": null }, { "code": null, "e": 30167, "s": 30160, "text": "Output" }, { "code": null, "e": 30266, "s": 30167, "text": "[1] \"Original TimeStamp: \"\n[1] \"2020-01-08 12:15:38 IST\" \n[1] \"Extraction of time: \" \n[1] 12:15:38" }, { "code": null, "e": 30273, "s": 30266, "text": "Picked" }, { "code": null, "e": 30284, "s": 30273, "text": "R-DateTime" }, { "code": null, "e": 30295, "s": 30284, "text": "R Language" }, { "code": null, "e": 30393, "s": 30295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30445, "s": 30393, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30480, "s": 30445, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30518, "s": 30480, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30576, "s": 30518, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30619, "s": 30576, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30668, "s": 30619, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30705, "s": 30668, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30722, "s": 30705, "text": "R - if statement" }, { "code": null, "e": 30748, "s": 30722, "text": "Time Series Analysis in R" } ]
Find Corners of Rectangle using mid points - GeeksforGeeks
11 Mar, 2022 Consider a rectangle ABCD, we’re given the co-ordinates of the mid points of side AD and BC (p and q respectively) along with their length L (AD = BC = L). Now given the parameters, we need to print the co-ordinates of the 4 points A, B, C and D. Examples: Input : p = (1, 0) q = (1, 2) L = 2 Output : (0, 0), (0, 2), (2, 2), (2, 0) Explanation: The printed points form a rectangle which satisfy the input constraints. Input : p = (1, 1) q = (-1, -1) L = 2*sqrt(2) Output : (0, 2), (-2, 0), (0, -2), (2, 0) From the problem statement 3 cases can arise : The Rectangle is horizontal i.e., AD and BC are parallel to X-axisThe Rectangle is vertical i.e., AD and BC are parallel to Y-axisThe Rectangle is inclined at a certain angle with the axes The Rectangle is horizontal i.e., AD and BC are parallel to X-axis The Rectangle is vertical i.e., AD and BC are parallel to Y-axis The Rectangle is inclined at a certain angle with the axes The first two cases are trivial and can easily be solved using basic geometry. For the third case we need to apply some mathematical concepts to find the points. Consider the above diagram for clarity. We have the co-ordinates of p and q. Thus we can find the slope of AD and BC (As pq is perpendicular to AD). Once we have the slope of AD, we can find the equation of straight line passing through AD. Now we can apply distance formula to obtain the displacements along X and Y axes. If slope of AD = m, then m = (p.x- q.x)/(q.y - p.y) and displacement along X axis, dx = L/(2*sqrt(1+m*m)) Similarly, dy = m*L/(2*sqrt(1+m*m)) Now we can simply find the co-ordinates of 4 corners by simply adding and subtracting the displacements obtained accordingly. Below is the implementation . C++ Java Python3 C# Javascript // C++ program to find corner points of// a rectangle using given length and middle// points.#include <bits/stdc++.h>using namespace std; // Structure to represent a co-ordinate pointstruct Point{ float x, y; Point() { x = y = 0; } Point(float a, float b) { x = a, y = b; }}; // This function receives two points and length// of the side of rectangle and prints the 4// corner points of the rectanglevoid printCorners(Point p, Point q, float l){ Point a, b, c, d; // horizontal rectangle if (p.x == q.x) { a.x = p.x - (l/2.0); a.y = p.y; d.x = p.x + (l/2.0); d.y = p.y; b.x = q.x - (l/2.0); b.y = q.y; c.x = q.x + (l/2.0); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = p.y - (l/2.0); a.x = p.x; d.y = p.y + (l/2.0); d.x = p.x; b.y = q.y - (l/2.0); b.x = q.x; c.y = q.y + (l/2.0); c.x = q.x; } // slanted rectangle else { // calculate slope of the side float m = (p.x-q.x)/float(q.y-p.y); // calculate displacements along axes float dx = (l /sqrt(1+(m*m))) *0.5 ; float dy = m*dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } cout << a.x << ", " << a.y << " n" << b.x << ", " << b.y << "n"; << c.x << ", " << c.y << " n" << d.x << ", " << d.y << "nn";} // Driver codeint main(){ Point p1(1, 0), q1(1, 2); printCorners(p1, q1, 2); Point p(1, 1), q(-1, -1); printCorners(p, q, 2*sqrt(2)); return 0;} // Java program to find corner points of// a rectangle using given length and middle// points. class GFG{ // Structure to represent a co-ordinate point static class Point { float x, y; Point() { x = y = 0; } Point(float a, float b) { x = a; y = b; } }; // This function receives two points and length // of the side of rectangle and prints the 4 // corner points of the rectangle static void printCorners(Point p, Point q, float l) { Point a = new Point(), b = new Point(), c = new Point(), d = new Point(); // horizontal rectangle if (p.x == q.x) { a.x = (float) (p.x - (l / 2.0)); a.y = p.y; d.x = (float) (p.x + (l / 2.0)); d.y = p.y; b.x = (float) (q.x - (l / 2.0)); b.y = q.y; c.x = (float) (q.x + (l / 2.0)); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = (float) (p.y - (l / 2.0)); a.x = p.x; d.y = (float) (p.y + (l / 2.0)); d.x = p.x; b.y = (float) (q.y - (l / 2.0)); b.x = q.x; c.y = (float) (q.y + (l / 2.0)); c.x = q.x; } // slanted rectangle else { // calculate slope of the side float m = (p.x - q.x) / (q.y - p.y); // calculate displacements along axes float dx = (float) ((l / Math.sqrt(1 + (m * m))) * 0.5); float dy = m * dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } System.out.print((int)a.x + ", " + (int)a.y + " \n" + (int)b.x + ", " + (int)b.y + "\n" + (int)c.x + ", " + (int)c.y + " \n" + (int)d.x + ", " + (int)d.y + "\n"); } // Driver code public static void main(String[] args) { Point p1 = new Point(1, 0), q1 = new Point(1, 2); printCorners(p1, q1, 2); Point p = new Point(1, 1), q = new Point(-1, -1); printCorners(p, q, (float) (2 * Math.sqrt(2))); }} // This code contributed by Rajput-Ji # Python3 program to find corner points of# a rectangle using given length and middle# points.import math # Structure to represent a co-ordinate pointclass Point: def __init__(self, a = 0, b = 0): self.x = a self.y = b # This function receives two points and length# of the side of rectangle and prints the 4# corner points of the rectangledef printCorners(p, q, l): a, b, c, d = Point(), Point(), Point(), Point() # Horizontal rectangle if (p.x == q.x): a.x = p.x - (l / 2.0) a.y = p.y d.x = p.x + (l / 2.0) d.y = p.y b.x = q.x - (l / 2.0) b.y = q.y c.x = q.x + (l / 2.0) c.y = q.y # Vertical rectangle else if (p.y == q.y): a.y = p.y - (l / 2.0) a.x = p.x d.y = p.y + (l / 2.0) d.x = p.x b.y = q.y - (l / 2.0) b.x = q.x c.y = q.y + (l / 2.0) c.x = q.x # Slanted rectangle else: # Calculate slope of the side m = (p.x - q.x) / (q.y - p.y) # Calculate displacements along axes dx = (l / math.sqrt(1 + (m * m))) * 0.5 dy = m * dx a.x = p.x - dx a.y = p.y - dy d.x = p.x + dx d.y = p.y + dy b.x = q.x - dx b.y = q.y - dy c.x = q.x + dx c.y = q.y + dy print(int(a.x), ", ", int(a.y), sep = "") print(int(b.x), ", ", int(b.y), sep = "") print(int(c.x), ", ", int(c.y), sep = "") print(int(d.x), ", ", int(d.y), sep = "") print() # Driver codep1 = Point(1, 0)q1 = Point(1, 2)printCorners(p1, q1, 2) p = Point(1, 1)q = Point(-1, -1)printCorners(p, q, 2 * math.sqrt(2)) # This code is contributed by shubhamsingh10 // C# program to find corner points of// a rectangle using given length and middle// points.using System; class GFG{ // Structure to represent a co-ordinate point public class Point { public float x, y; public Point() { x = y = 0; } public Point(float a, float b) { x = a; y = b; } }; // This function receives two points and length // of the side of rectangle and prints the 4 // corner points of the rectangle static void printCorners(Point p, Point q, float l) { Point a = new Point(), b = new Point(), c = new Point(), d = new Point(); // horizontal rectangle if (p.x == q.x) { a.x = (float) (p.x - (l / 2.0)); a.y = p.y; d.x = (float) (p.x + (l / 2.0)); d.y = p.y; b.x = (float) (q.x - (l / 2.0)); b.y = q.y; c.x = (float) (q.x + (l / 2.0)); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = (float) (p.y - (l / 2.0)); a.x = p.x; d.y = (float) (p.y + (l / 2.0)); d.x = p.x; b.y = (float) (q.y - (l / 2.0)); b.x = q.x; c.y = (float) (q.y + (l / 2.0)); c.x = q.x; } // slanted rectangle else { // calculate slope of the side float m = (p.x - q.x) / (q.y - p.y); // calculate displacements along axes float dx = (float) ((l / Math.Sqrt(1 + (m * m))) * 0.5); float dy = m * dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } Console.Write((int)a.x + ", " + (int)a.y + " \n" + (int)b.x + ", " + (int)b.y + "\n" + (int)c.x + ", " + (int)c.y + " \n" + (int)d.x + ", " + (int)d.y + "\n"); } // Driver code public static void Main(String[] args) { Point p1 = new Point(1, 0), q1 = new Point(1, 2); printCorners(p1, q1, 2); Point p = new Point(1, 1), q = new Point(-1, -1); printCorners(p, q, (float) (2 * Math.Sqrt(2))); }} // This code has been contributed by 29AjayKumar <script>// Javascript program to find corner points of// a rectangle using given length and middle// points. // Structure to represent a co-ordinate pointclass Point{ constructor(a,b) { this.x=a; this.y=b; }} // This function receives two points and length // of the side of rectangle and prints the 4 // corner points of the rectanglefunction printCorners(p,q,l){ let a = new Point(), b = new Point(), c = new Point(), d = new Point(); // horizontal rectangle if (p.x == q.x) { a.x = (p.x - (l / 2.0)); a.y = p.y; d.x = (p.x + (l / 2.0)); d.y = p.y; b.x = (q.x - (l / 2.0)); b.y = q.y; c.x = (q.x + (l / 2.0)); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = (p.y - (l / 2.0)); a.x = p.x; d.y = (p.y + (l / 2.0)); d.x = p.x; b.y = (q.y - (l / 2.0)); b.x = q.x; c.y = (q.y + (l / 2.0)); c.x = q.x; } // slanted rectangle else { // calculate slope of the side let m = (p.x - q.x) / (q.y - p.y); // calculate displacements along axes let dx = ((l / Math.sqrt(1 + (m * m))) * 0.5); let dy = m * dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } document.write(a.x + ", " + a.y + " <br>" + b.x + ", " + b.y + "<br>" + c.x + ", " + c.y + " <br>" + d.x + ", " + d.y + "<br>");} // Driver codelet p1 = new Point(1, 0), q1 = new Point(1, 2);printCorners(p1, q1, 2); let p = new Point(1, 1), q = new Point(-1, -1);printCorners(p, q, (2 * Math.sqrt(2))); // This code is contributed by rag2127</script> Output: 0, 0 0, 2 2, 2 2, 0 0, 2 -2, 0 0, -2 2, 0 Reference: StackOverflowThis article is contributed by Ashutosh Kumar 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. Rajput-Ji 29AjayKumar rag2127 SHUBHAMSINGH10 simmytarika5 square-rectangle Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Equation of circle when three points on the circle are given Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Orientation of 3 ordered points Minimum Cost Polygon Triangulation Check if a line touches or intersects a circle Quickhull Algorithm for Convex Hull Program to find area of a circle
[ { "code": null, "e": 26507, "s": 26479, "text": "\n11 Mar, 2022" }, { "code": null, "e": 26755, "s": 26507, "text": "Consider a rectangle ABCD, we’re given the co-ordinates of the mid points of side AD and BC (p and q respectively) along with their length L (AD = BC = L). Now given the parameters, we need to print the co-ordinates of the 4 points A, B, C and D. " }, { "code": null, "e": 26766, "s": 26755, "text": "Examples: " }, { "code": null, "e": 27049, "s": 26766, "text": "Input : p = (1, 0)\n q = (1, 2)\n L = 2\nOutput : (0, 0), (0, 2), (2, 2), (2, 0)\nExplanation:\nThe printed points form a rectangle which\nsatisfy the input constraints.\n\nInput : p = (1, 1)\n q = (-1, -1)\n L = 2*sqrt(2)\nOutput : (0, 2), (-2, 0), (0, -2), (2, 0)" }, { "code": null, "e": 27098, "s": 27049, "text": "From the problem statement 3 cases can arise : " }, { "code": null, "e": 27287, "s": 27098, "text": "The Rectangle is horizontal i.e., AD and BC are parallel to X-axisThe Rectangle is vertical i.e., AD and BC are parallel to Y-axisThe Rectangle is inclined at a certain angle with the axes" }, { "code": null, "e": 27354, "s": 27287, "text": "The Rectangle is horizontal i.e., AD and BC are parallel to X-axis" }, { "code": null, "e": 27419, "s": 27354, "text": "The Rectangle is vertical i.e., AD and BC are parallel to Y-axis" }, { "code": null, "e": 27478, "s": 27419, "text": "The Rectangle is inclined at a certain angle with the axes" }, { "code": null, "e": 27640, "s": 27478, "text": "The first two cases are trivial and can easily be solved using basic geometry. For the third case we need to apply some mathematical concepts to find the points." }, { "code": null, "e": 27965, "s": 27640, "text": "Consider the above diagram for clarity. We have the co-ordinates of p and q. Thus we can find the slope of AD and BC (As pq is perpendicular to AD). Once we have the slope of AD, we can find the equation of straight line passing through AD. Now we can apply distance formula to obtain the displacements along X and Y axes. " }, { "code": null, "e": 28114, "s": 27965, "text": "If slope of AD = m, then\nm = (p.x- q.x)/(q.y - p.y)\n\nand displacement along X axis, dx = \n L/(2*sqrt(1+m*m))\n\nSimilarly, dy = m*L/(2*sqrt(1+m*m))" }, { "code": null, "e": 28241, "s": 28114, "text": "Now we can simply find the co-ordinates of 4 corners by simply adding and subtracting the displacements obtained accordingly. " }, { "code": null, "e": 28273, "s": 28241, "text": "Below is the implementation . " }, { "code": null, "e": 28277, "s": 28273, "text": "C++" }, { "code": null, "e": 28282, "s": 28277, "text": "Java" }, { "code": null, "e": 28290, "s": 28282, "text": "Python3" }, { "code": null, "e": 28293, "s": 28290, "text": "C#" }, { "code": null, "e": 28304, "s": 28293, "text": "Javascript" }, { "code": "// C++ program to find corner points of// a rectangle using given length and middle// points.#include <bits/stdc++.h>using namespace std; // Structure to represent a co-ordinate pointstruct Point{ float x, y; Point() { x = y = 0; } Point(float a, float b) { x = a, y = b; }}; // This function receives two points and length// of the side of rectangle and prints the 4// corner points of the rectanglevoid printCorners(Point p, Point q, float l){ Point a, b, c, d; // horizontal rectangle if (p.x == q.x) { a.x = p.x - (l/2.0); a.y = p.y; d.x = p.x + (l/2.0); d.y = p.y; b.x = q.x - (l/2.0); b.y = q.y; c.x = q.x + (l/2.0); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = p.y - (l/2.0); a.x = p.x; d.y = p.y + (l/2.0); d.x = p.x; b.y = q.y - (l/2.0); b.x = q.x; c.y = q.y + (l/2.0); c.x = q.x; } // slanted rectangle else { // calculate slope of the side float m = (p.x-q.x)/float(q.y-p.y); // calculate displacements along axes float dx = (l /sqrt(1+(m*m))) *0.5 ; float dy = m*dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } cout << a.x << \", \" << a.y << \" n\" << b.x << \", \" << b.y << \"n\"; << c.x << \", \" << c.y << \" n\" << d.x << \", \" << d.y << \"nn\";} // Driver codeint main(){ Point p1(1, 0), q1(1, 2); printCorners(p1, q1, 2); Point p(1, 1), q(-1, -1); printCorners(p, q, 2*sqrt(2)); return 0;}", "e": 30040, "s": 28304, "text": null }, { "code": "// Java program to find corner points of// a rectangle using given length and middle// points. class GFG{ // Structure to represent a co-ordinate point static class Point { float x, y; Point() { x = y = 0; } Point(float a, float b) { x = a; y = b; } }; // This function receives two points and length // of the side of rectangle and prints the 4 // corner points of the rectangle static void printCorners(Point p, Point q, float l) { Point a = new Point(), b = new Point(), c = new Point(), d = new Point(); // horizontal rectangle if (p.x == q.x) { a.x = (float) (p.x - (l / 2.0)); a.y = p.y; d.x = (float) (p.x + (l / 2.0)); d.y = p.y; b.x = (float) (q.x - (l / 2.0)); b.y = q.y; c.x = (float) (q.x + (l / 2.0)); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = (float) (p.y - (l / 2.0)); a.x = p.x; d.y = (float) (p.y + (l / 2.0)); d.x = p.x; b.y = (float) (q.y - (l / 2.0)); b.x = q.x; c.y = (float) (q.y + (l / 2.0)); c.x = q.x; } // slanted rectangle else { // calculate slope of the side float m = (p.x - q.x) / (q.y - p.y); // calculate displacements along axes float dx = (float) ((l / Math.sqrt(1 + (m * m))) * 0.5); float dy = m * dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } System.out.print((int)a.x + \", \" + (int)a.y + \" \\n\" + (int)b.x + \", \" + (int)b.y + \"\\n\" + (int)c.x + \", \" + (int)c.y + \" \\n\" + (int)d.x + \", \" + (int)d.y + \"\\n\"); } // Driver code public static void main(String[] args) { Point p1 = new Point(1, 0), q1 = new Point(1, 2); printCorners(p1, q1, 2); Point p = new Point(1, 1), q = new Point(-1, -1); printCorners(p, q, (float) (2 * Math.sqrt(2))); }} // This code contributed by Rajput-Ji", "e": 32415, "s": 30040, "text": null }, { "code": "# Python3 program to find corner points of# a rectangle using given length and middle# points.import math # Structure to represent a co-ordinate pointclass Point: def __init__(self, a = 0, b = 0): self.x = a self.y = b # This function receives two points and length# of the side of rectangle and prints the 4# corner points of the rectangledef printCorners(p, q, l): a, b, c, d = Point(), Point(), Point(), Point() # Horizontal rectangle if (p.x == q.x): a.x = p.x - (l / 2.0) a.y = p.y d.x = p.x + (l / 2.0) d.y = p.y b.x = q.x - (l / 2.0) b.y = q.y c.x = q.x + (l / 2.0) c.y = q.y # Vertical rectangle else if (p.y == q.y): a.y = p.y - (l / 2.0) a.x = p.x d.y = p.y + (l / 2.0) d.x = p.x b.y = q.y - (l / 2.0) b.x = q.x c.y = q.y + (l / 2.0) c.x = q.x # Slanted rectangle else: # Calculate slope of the side m = (p.x - q.x) / (q.y - p.y) # Calculate displacements along axes dx = (l / math.sqrt(1 + (m * m))) * 0.5 dy = m * dx a.x = p.x - dx a.y = p.y - dy d.x = p.x + dx d.y = p.y + dy b.x = q.x - dx b.y = q.y - dy c.x = q.x + dx c.y = q.y + dy print(int(a.x), \", \", int(a.y), sep = \"\") print(int(b.x), \", \", int(b.y), sep = \"\") print(int(c.x), \", \", int(c.y), sep = \"\") print(int(d.x), \", \", int(d.y), sep = \"\") print() # Driver codep1 = Point(1, 0)q1 = Point(1, 2)printCorners(p1, q1, 2) p = Point(1, 1)q = Point(-1, -1)printCorners(p, q, 2 * math.sqrt(2)) # This code is contributed by shubhamsingh10", "e": 34240, "s": 32415, "text": null }, { "code": "// C# program to find corner points of// a rectangle using given length and middle// points.using System; class GFG{ // Structure to represent a co-ordinate point public class Point { public float x, y; public Point() { x = y = 0; } public Point(float a, float b) { x = a; y = b; } }; // This function receives two points and length // of the side of rectangle and prints the 4 // corner points of the rectangle static void printCorners(Point p, Point q, float l) { Point a = new Point(), b = new Point(), c = new Point(), d = new Point(); // horizontal rectangle if (p.x == q.x) { a.x = (float) (p.x - (l / 2.0)); a.y = p.y; d.x = (float) (p.x + (l / 2.0)); d.y = p.y; b.x = (float) (q.x - (l / 2.0)); b.y = q.y; c.x = (float) (q.x + (l / 2.0)); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = (float) (p.y - (l / 2.0)); a.x = p.x; d.y = (float) (p.y + (l / 2.0)); d.x = p.x; b.y = (float) (q.y - (l / 2.0)); b.x = q.x; c.y = (float) (q.y + (l / 2.0)); c.x = q.x; } // slanted rectangle else { // calculate slope of the side float m = (p.x - q.x) / (q.y - p.y); // calculate displacements along axes float dx = (float) ((l / Math.Sqrt(1 + (m * m))) * 0.5); float dy = m * dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } Console.Write((int)a.x + \", \" + (int)a.y + \" \\n\" + (int)b.x + \", \" + (int)b.y + \"\\n\" + (int)c.x + \", \" + (int)c.y + \" \\n\" + (int)d.x + \", \" + (int)d.y + \"\\n\"); } // Driver code public static void Main(String[] args) { Point p1 = new Point(1, 0), q1 = new Point(1, 2); printCorners(p1, q1, 2); Point p = new Point(1, 1), q = new Point(-1, -1); printCorners(p, q, (float) (2 * Math.Sqrt(2))); }} // This code has been contributed by 29AjayKumar", "e": 36673, "s": 34240, "text": null }, { "code": "<script>// Javascript program to find corner points of// a rectangle using given length and middle// points. // Structure to represent a co-ordinate pointclass Point{ constructor(a,b) { this.x=a; this.y=b; }} // This function receives two points and length // of the side of rectangle and prints the 4 // corner points of the rectanglefunction printCorners(p,q,l){ let a = new Point(), b = new Point(), c = new Point(), d = new Point(); // horizontal rectangle if (p.x == q.x) { a.x = (p.x - (l / 2.0)); a.y = p.y; d.x = (p.x + (l / 2.0)); d.y = p.y; b.x = (q.x - (l / 2.0)); b.y = q.y; c.x = (q.x + (l / 2.0)); c.y = q.y; } // vertical rectangle else if (p.y == q.y) { a.y = (p.y - (l / 2.0)); a.x = p.x; d.y = (p.y + (l / 2.0)); d.x = p.x; b.y = (q.y - (l / 2.0)); b.x = q.x; c.y = (q.y + (l / 2.0)); c.x = q.x; } // slanted rectangle else { // calculate slope of the side let m = (p.x - q.x) / (q.y - p.y); // calculate displacements along axes let dx = ((l / Math.sqrt(1 + (m * m))) * 0.5); let dy = m * dx; a.x = p.x - dx; a.y = p.y - dy; d.x = p.x + dx; d.y = p.y + dy; b.x = q.x - dx; b.y = q.y - dy; c.x = q.x + dx; c.y = q.y + dy; } document.write(a.x + \", \" + a.y + \" <br>\" + b.x + \", \" + b.y + \"<br>\" + c.x + \", \" + c.y + \" <br>\" + d.x + \", \" + d.y + \"<br>\");} // Driver codelet p1 = new Point(1, 0), q1 = new Point(1, 2);printCorners(p1, q1, 2); let p = new Point(1, 1), q = new Point(-1, -1);printCorners(p, q, (2 * Math.sqrt(2))); // This code is contributed by rag2127</script>", "e": 38713, "s": 36673, "text": null }, { "code": null, "e": 38722, "s": 38713, "text": "Output: " }, { "code": null, "e": 38769, "s": 38722, "text": "0, 0 \n0, 2\n2, 2 \n2, 0\n\n0, 2 \n-2, 0\n0, -2 \n2, 0" }, { "code": null, "e": 39216, "s": 38769, "text": "Reference: StackOverflowThis article is contributed by Ashutosh Kumar 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": 39226, "s": 39216, "text": "Rajput-Ji" }, { "code": null, "e": 39238, "s": 39226, "text": "29AjayKumar" }, { "code": null, "e": 39246, "s": 39238, "text": "rag2127" }, { "code": null, "e": 39261, "s": 39246, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 39274, "s": 39261, "text": "simmytarika5" }, { "code": null, "e": 39291, "s": 39274, "text": "square-rectangle" }, { "code": null, "e": 39301, "s": 39291, "text": "Geometric" }, { "code": null, "e": 39311, "s": 39301, "text": "Geometric" }, { "code": null, "e": 39409, "s": 39311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39475, "s": 39409, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 39507, "s": 39475, "text": "Program to find slope of a line" }, { "code": null, "e": 39568, "s": 39507, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 39614, "s": 39568, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 39684, "s": 39614, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 39716, "s": 39684, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 39751, "s": 39716, "text": "Minimum Cost Polygon Triangulation" }, { "code": null, "e": 39798, "s": 39751, "text": "Check if a line touches or intersects a circle" }, { "code": null, "e": 39834, "s": 39798, "text": "Quickhull Algorithm for Convex Hull" } ]
Java Program to Find the Largest of three Numbers - GeeksforGeeks
23 Aug, 2021 Problem Statement: Given three numbers x, y, and z of which aim is to get the largest among these three numbers. Example: Input: x = 7, y = 20, z = 56 Output: 56 // value stored in variable z Flowchart For Largest of 3 numbers: Algorithm to find the largest of three numbers: 1. Start 2. Read the three numbers to be compared, as A, B and C 3. Check if A is greater than B. 3.1 If true, then check if A is greater than C If true, print 'A' as the greatest number If false, print 'C' as the greatest number 3.2 If false, then check if B is greater than C If true, print 'B' as the greatest number If false, print 'C' as the greatest number 4. End Approaches: Using Ternary operator Using if-else Approach 1: Using Ternary operator The syntax for the conditional operator: ans = (conditional expression) ? execute if true : execute if false If the condition is true then execute the statement before the colon If the condition is false then execute a statement after colon so largest = z > (x>y ? x:y) ? z:((x>y) ? x:y); Illustration: x = 5, y= 10, z = 3 largest = 3>(5>10 ? 5:10) ? 3: ((5>10) ? 5:10); largest = 3>10 ? 3 : 10 largest = 10 Java // Java Program to Find the Biggest of 3 Numbers // Importing generic Classes/Filesimport java.io.*; class GFG { // Function to find the biggest of three numbers static int biggestOfThree(int x, int y, int z) { return z > (x > y ? x : y) ? z : ((x > y) ? x : y); } // Main driver function public static void main(String[] args) { // Declaring variables for 3 numbers int a, b, c; // Variable holding the largest number int largest; a = 5; b = 10; c = 3; // Calling the above function in main largest = biggestOfThree(a, b, c); // Printing the largest number System.out.println(largest + " is the largest number."); }} 10 is the largest number. Approach 2: Using the if-else statements In this method, if-else statements will compare and check for the largest number by comparing numbers. ‘If’ will check whether ‘x’ is greater than ‘y’ and ‘z’ or not. ‘else if’ will check whether ‘y’ is greater than ‘x’ and ‘z’ or not. And if both the conditions are false then ‘z’ will be the largest number. Java // Java Program to Find the Biggest of 3 Numbers // Importing generic Classes/Filesimport java.io.*; class GFG { // Function to find the biggest of three numbers static int biggestOfThree(int x, int y, int z) { // Comparing all 3 numbers if (x >= y && x >= z) // Returning 1st number if largest return x; // Comparing 2nd no with 1st and 3rd no else if (y >= x && y >= z) // Return z if the above conditions are false return y; else // Returning 3rd no, Its sure it is greatest return z; } // Main driver function public static void main(String[] args) { int a, b, c, largest; // Considering random integers three numbers a = 5; b = 10; c = 3; // Calling the function in main() body largest = biggestOfThree(a, b, c); // Printing the largest number System.out.println(largest + " is the largest number."); }} 10 is the largest number. simmytarika5 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n23 Aug, 2021" }, { "code": null, "e": 25362, "s": 25249, "text": "Problem Statement: Given three numbers x, y, and z of which aim is to get the largest among these three numbers." }, { "code": null, "e": 25372, "s": 25362, "text": "Example: " }, { "code": null, "e": 25461, "s": 25372, "text": "Input: x = 7, y = 20, z = 56\nOutput: 56 // value stored in variable z" }, { "code": null, "e": 25497, "s": 25461, "text": "Flowchart For Largest of 3 numbers:" }, { "code": null, "e": 25545, "s": 25497, "text": "Algorithm to find the largest of three numbers:" }, { "code": null, "e": 25956, "s": 25545, "text": "1. Start\n2. Read the three numbers to be compared, as A, B and C\n3. Check if A is greater than B.\n\n 3.1 If true, then check if A is greater than C\n If true, print 'A' as the greatest number\n If false, print 'C' as the greatest number\n\n 3.2 If false, then check if B is greater than C\n If true, print 'B' as the greatest number\n If false, print 'C' as the greatest number\n4. End" }, { "code": null, "e": 25968, "s": 25956, "text": "Approaches:" }, { "code": null, "e": 25991, "s": 25968, "text": "Using Ternary operator" }, { "code": null, "e": 26005, "s": 25991, "text": "Using if-else" }, { "code": null, "e": 26040, "s": 26005, "text": "Approach 1: Using Ternary operator" }, { "code": null, "e": 26082, "s": 26040, "text": " The syntax for the conditional operator:" }, { "code": null, "e": 26150, "s": 26082, "text": "ans = (conditional expression) ? execute if true : execute if false" }, { "code": null, "e": 26219, "s": 26150, "text": "If the condition is true then execute the statement before the colon" }, { "code": null, "e": 26285, "s": 26219, "text": "If the condition is false then execute a statement after colon so" }, { "code": null, "e": 26331, "s": 26285, "text": "largest = z > (x>y ? x:y) ? z:((x>y) ? x:y); " }, { "code": null, "e": 26345, "s": 26331, "text": "Illustration:" }, { "code": null, "e": 26454, "s": 26345, "text": "x = 5, y= 10, z = 3\n\nlargest = 3>(5>10 ? 5:10) ? 3: ((5>10) ? 5:10);\nlargest = 3>10 ? 3 : 10\nlargest = 10" }, { "code": null, "e": 26459, "s": 26454, "text": "Java" }, { "code": "// Java Program to Find the Biggest of 3 Numbers // Importing generic Classes/Filesimport java.io.*; class GFG { // Function to find the biggest of three numbers static int biggestOfThree(int x, int y, int z) { return z > (x > y ? x : y) ? z : ((x > y) ? x : y); } // Main driver function public static void main(String[] args) { // Declaring variables for 3 numbers int a, b, c; // Variable holding the largest number int largest; a = 5; b = 10; c = 3; // Calling the above function in main largest = biggestOfThree(a, b, c); // Printing the largest number System.out.println(largest + \" is the largest number.\"); }}", "e": 27219, "s": 26459, "text": null }, { "code": null, "e": 27248, "s": 27222, "text": "10 is the largest number." }, { "code": null, "e": 27291, "s": 27250, "text": "Approach 2: Using the if-else statements" }, { "code": null, "e": 27603, "s": 27293, "text": "In this method, if-else statements will compare and check for the largest number by comparing numbers. ‘If’ will check whether ‘x’ is greater than ‘y’ and ‘z’ or not. ‘else if’ will check whether ‘y’ is greater than ‘x’ and ‘z’ or not. And if both the conditions are false then ‘z’ will be the largest number." }, { "code": null, "e": 27610, "s": 27605, "text": "Java" }, { "code": "// Java Program to Find the Biggest of 3 Numbers // Importing generic Classes/Filesimport java.io.*; class GFG { // Function to find the biggest of three numbers static int biggestOfThree(int x, int y, int z) { // Comparing all 3 numbers if (x >= y && x >= z) // Returning 1st number if largest return x; // Comparing 2nd no with 1st and 3rd no else if (y >= x && y >= z) // Return z if the above conditions are false return y; else // Returning 3rd no, Its sure it is greatest return z; } // Main driver function public static void main(String[] args) { int a, b, c, largest; // Considering random integers three numbers a = 5; b = 10; c = 3; // Calling the function in main() body largest = biggestOfThree(a, b, c); // Printing the largest number System.out.println(largest + \" is the largest number.\"); }}", "e": 28643, "s": 27610, "text": null }, { "code": null, "e": 28672, "s": 28646, "text": "10 is the largest number." }, { "code": null, "e": 28687, "s": 28674, "text": "simmytarika5" }, { "code": null, "e": 28692, "s": 28687, "text": "Java" }, { "code": null, "e": 28706, "s": 28692, "text": "Java Programs" }, { "code": null, "e": 28711, "s": 28706, "text": "Java" }, { "code": null, "e": 28809, "s": 28711, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28824, "s": 28809, "text": "Stream In Java" }, { "code": null, "e": 28845, "s": 28824, "text": "Constructors in Java" }, { "code": null, "e": 28864, "s": 28845, "text": "Exceptions in Java" }, { "code": null, "e": 28894, "s": 28864, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28940, "s": 28894, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28966, "s": 28940, "text": "Java Programming Examples" }, { "code": null, "e": 29000, "s": 28966, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29047, "s": 29000, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29079, "s": 29047, "text": "How to Iterate HashMap in Java?" } ]
Median of sliding window in an array | Set 2 - GeeksforGeeks
07 Jul, 2021 Prerequisites: Policy based data structure, Sliding window technique.Given an array of integer arr[] and an integer K, the task is to find the median of each window of size K starting from the left and moving towards the right by one position each time.Examples: Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, K = 3 Output: 5 8 8 3 3 3 Explanation: 1st Window: {-1, 5, 13} Median = 5 2nd Window: {5, 13, 8} Median = 8 3rd Window: {13, 8, 2} Median = 8 4th Window: {8, 2, 3} Median = 3 5th Window: {2, 3, 3} Median = 3 6th Window: {3, 3, 1} Median = 3Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, K = 4 Output: 6.5 6.5 5.5 3.0 2.5 Naive Approach: The simplest approach to solve the problem is to traverse over every window of size K and sort the elements of the window and find the middle element. Print the middle element of every window as the median. Time Complexity: O(N*KlogK) Auxiliary Space: O(K)Sorted Set Approach: Refer to Median of sliding window in an array to solve the problem using SortedSet.Ordered Set Approach: In this article, an approach to solving the problem using a Policy-based Ordered set data structure. Follow the steps below to solve the problem: Insert the first window of size K in the Ordered_set( maintains a sorted order). Hence, the middle element of this Ordered set is the required median of the corresponding window. The middle element can be obtained by the find_by_order() method in O(logN) computational complexity.Proceed to the following windows by remove the first element of the previous window and insert the new element. To remove any element from the set, find the order of the element in the Ordered_Set using order_by_key(), which fetches the result in O(logN) computational complexity, and erase() that element by searching its obtained order in the Ordered_Set using find_by_order() method. Now add the new element for the new window. Repeat the above steps for each window and print the respective medians. Insert the first window of size K in the Ordered_set( maintains a sorted order). Hence, the middle element of this Ordered set is the required median of the corresponding window. The middle element can be obtained by the find_by_order() method in O(logN) computational complexity. Proceed to the following windows by remove the first element of the previous window and insert the new element. To remove any element from the set, find the order of the element in the Ordered_Set using order_by_key(), which fetches the result in O(logN) computational complexity, and erase() that element by searching its obtained order in the Ordered_Set using find_by_order() method. Now add the new element for the new window. Repeat the above steps for each window and print the respective medians. Below is the implementation of the above approach. CPP // C++ Program to implement the// above approach#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp> using namespace std;using namespace __gnu_pbds; // Policy based data structuretypedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> Ordered_set; // Function to find and return the// median of every window of size kvoid findMedian(int arr[], int n, int k){ Ordered_set s; for (int i = 0; i < k; i++) s.insert(arr[i]); if (k & 1) { // Value at index k/2 // in sorted list. int ans = *s.find_by_order(k / 2); cout << ans << " "; for (int i = 0; i < n - k; i++) { // Erasing Element out of window. s.erase(s.find_by_order( s.order_of_key( arr[i]))); // Inserting newer element // to the window s.insert(arr[i + k]); // Value at index k/2 in // sorted list. ans = *s.find_by_order(k / 2); cout << ans << " "; } cout << endl; } else { // Getting the two middle // median of sorted list. float ans = ((float)*s.find_by_order( (k + 1) / 2 - 1) + (float)*s.find_by_order(k / 2)) / 2; printf("%.2f ", ans); for (int i = 0; i < n - k; i++) { s.erase(s.find_by_order( s.order_of_key(arr[i]))); s.insert(arr[i + k]); ans = ((float)*s.find_by_order( (k + 1) / 2 - 1) + (float)*s.find_by_order(k / 2)) / 2; printf("%.2f ", ans); } cout << endl; }} // Driver Codeint main(){ int arr[] = { -1, 5, 13, 8, 2, 3, 3, 1 }; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); findMedian(arr, n, k); return 0;} 5 8 8 3 3 3 Time Complexity: O(NlogK) Auxiliary Space: O(K) surindertarika1234 cpp-unordered_set-functions median-finding sliding-window Advanced Data Structure Competitive Programming Data Structures Mathematical Searching Sorting Tree Data Structures sliding-window Searching Mathematical Sorting Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) AVL Tree | Set 2 (Deletion) Ordered Set and GNU C++ PBDS Competitive Programming - A Complete Guide Arrow operator -> in C/C++ with Examples Breadth First Traversal ( BFS ) on a 2D array Practice for cracking any coding interview Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 26167, "s": 26139, "text": "\n07 Jul, 2021" }, { "code": null, "e": 26432, "s": 26167, "text": "Prerequisites: Policy based data structure, Sliding window technique.Given an array of integer arr[] and an integer K, the task is to find the median of each window of size K starting from the left and moving towards the right by one position each time.Examples: " }, { "code": null, "e": 26794, "s": 26432, "text": "Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, K = 3 Output: 5 8 8 3 3 3 Explanation: 1st Window: {-1, 5, 13} Median = 5 2nd Window: {5, 13, 8} Median = 8 3rd Window: {13, 8, 2} Median = 8 4th Window: {8, 2, 3} Median = 3 5th Window: {2, 3, 3} Median = 3 6th Window: {3, 3, 1} Median = 3Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, K = 4 Output: 6.5 6.5 5.5 3.0 2.5 " }, { "code": null, "e": 27342, "s": 26796, "text": "Naive Approach: The simplest approach to solve the problem is to traverse over every window of size K and sort the elements of the window and find the middle element. Print the middle element of every window as the median. Time Complexity: O(N*KlogK) Auxiliary Space: O(K)Sorted Set Approach: Refer to Median of sliding window in an array to solve the problem using SortedSet.Ordered Set Approach: In this article, an approach to solving the problem using a Policy-based Ordered set data structure. Follow the steps below to solve the problem: " }, { "code": null, "e": 28130, "s": 27342, "text": "Insert the first window of size K in the Ordered_set( maintains a sorted order). Hence, the middle element of this Ordered set is the required median of the corresponding window. The middle element can be obtained by the find_by_order() method in O(logN) computational complexity.Proceed to the following windows by remove the first element of the previous window and insert the new element. To remove any element from the set, find the order of the element in the Ordered_Set using order_by_key(), which fetches the result in O(logN) computational complexity, and erase() that element by searching its obtained order in the Ordered_Set using find_by_order() method. Now add the new element for the new window. Repeat the above steps for each window and print the respective medians. " }, { "code": null, "e": 28311, "s": 28130, "text": "Insert the first window of size K in the Ordered_set( maintains a sorted order). Hence, the middle element of this Ordered set is the required median of the corresponding window. " }, { "code": null, "e": 28413, "s": 28311, "text": "The middle element can be obtained by the find_by_order() method in O(logN) computational complexity." }, { "code": null, "e": 28846, "s": 28413, "text": "Proceed to the following windows by remove the first element of the previous window and insert the new element. To remove any element from the set, find the order of the element in the Ordered_Set using order_by_key(), which fetches the result in O(logN) computational complexity, and erase() that element by searching its obtained order in the Ordered_Set using find_by_order() method. Now add the new element for the new window. " }, { "code": null, "e": 28921, "s": 28846, "text": "Repeat the above steps for each window and print the respective medians. " }, { "code": null, "e": 28973, "s": 28921, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 28977, "s": 28973, "text": "CPP" }, { "code": "// C++ Program to implement the// above approach#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp> using namespace std;using namespace __gnu_pbds; // Policy based data structuretypedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> Ordered_set; // Function to find and return the// median of every window of size kvoid findMedian(int arr[], int n, int k){ Ordered_set s; for (int i = 0; i < k; i++) s.insert(arr[i]); if (k & 1) { // Value at index k/2 // in sorted list. int ans = *s.find_by_order(k / 2); cout << ans << \" \"; for (int i = 0; i < n - k; i++) { // Erasing Element out of window. s.erase(s.find_by_order( s.order_of_key( arr[i]))); // Inserting newer element // to the window s.insert(arr[i + k]); // Value at index k/2 in // sorted list. ans = *s.find_by_order(k / 2); cout << ans << \" \"; } cout << endl; } else { // Getting the two middle // median of sorted list. float ans = ((float)*s.find_by_order( (k + 1) / 2 - 1) + (float)*s.find_by_order(k / 2)) / 2; printf(\"%.2f \", ans); for (int i = 0; i < n - k; i++) { s.erase(s.find_by_order( s.order_of_key(arr[i]))); s.insert(arr[i + k]); ans = ((float)*s.find_by_order( (k + 1) / 2 - 1) + (float)*s.find_by_order(k / 2)) / 2; printf(\"%.2f \", ans); } cout << endl; }} // Driver Codeint main(){ int arr[] = { -1, 5, 13, 8, 2, 3, 3, 1 }; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); findMedian(arr, n, k); return 0;}", "e": 31042, "s": 28977, "text": null }, { "code": null, "e": 31054, "s": 31042, "text": "5 8 8 3 3 3" }, { "code": null, "e": 31105, "s": 31056, "text": "Time Complexity: O(NlogK) Auxiliary Space: O(K) " }, { "code": null, "e": 31124, "s": 31105, "text": "surindertarika1234" }, { "code": null, "e": 31152, "s": 31124, "text": "cpp-unordered_set-functions" }, { "code": null, "e": 31167, "s": 31152, "text": "median-finding" }, { "code": null, "e": 31182, "s": 31167, "text": "sliding-window" }, { "code": null, "e": 31206, "s": 31182, "text": "Advanced Data Structure" }, { "code": null, "e": 31230, "s": 31206, "text": "Competitive Programming" }, { "code": null, "e": 31246, "s": 31230, "text": "Data Structures" }, { "code": null, "e": 31259, "s": 31246, "text": "Mathematical" }, { "code": null, "e": 31269, "s": 31259, "text": "Searching" }, { "code": null, "e": 31277, "s": 31269, "text": "Sorting" }, { "code": null, "e": 31282, "s": 31277, "text": "Tree" }, { "code": null, "e": 31298, "s": 31282, "text": "Data Structures" }, { "code": null, "e": 31313, "s": 31298, "text": "sliding-window" }, { "code": null, "e": 31323, "s": 31313, "text": "Searching" }, { "code": null, "e": 31336, "s": 31323, "text": "Mathematical" }, { "code": null, "e": 31344, "s": 31336, "text": "Sorting" }, { "code": null, "e": 31349, "s": 31344, "text": "Tree" }, { "code": null, "e": 31447, "s": 31349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31481, "s": 31447, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 31521, "s": 31481, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31563, "s": 31521, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 31591, "s": 31563, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 31620, "s": 31591, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 31663, "s": 31620, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31704, "s": 31663, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31750, "s": 31704, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 31793, "s": 31750, "text": "Practice for cracking any coding interview" } ]
Output of Java Program | Set 6 - GeeksforGeeks
27 Dec, 2016 Difficulty level : Intermediate Predict the output of following Java Programs. Program 1: class First{ public First() { System.out.println("a"); }} class Second extends First{ public Second() { System.out.println("b"); }} class Third extends Second{ public Third() { System.out.println("c"); }} public class MainClass{ public static void main(String[] args) { Third c = new Third(); }} Output: a b c Explanation:While creating a new object of ‘Third’ type, before calling the default constructor of Third class, the default constructor of super class is called i.e, Second class and then again before the default constructor of super class, default constructor of First class is called. And hence gives such output. Program 2: class First{ int i = 10; public First(int j) { System.out.println(i); this.i = j * 10; }} class Second extends First{ public Second(int j) { super(j); System.out.println(i); this.i = j * 20; }} public class MainClass{ public static void main(String[] args) { Second n = new Second(20); System.out.println(n.i); }} Output: 10 200 400 Explanation:Since in ‘Second’ class it doesn’t have its own ‘i’, the variable is inherited from the super class. Also, the constructor of parent is called when we create an object of Second. Program 3: import java.util.*; class I { public static void main (String[] args) { Object i = new ArrayList().iterator(); System.out.print((i instanceof List) + ", "); System.out.print((i instanceof Iterator) + ", "); System.out.print(i instanceof ListIterator); } } Output: false, true, false Explanation:The iterator() method returns an iterator over the elements in the list in proper sequence, it doesn’t return a List or a ListIterator object. A ListIterator can be obtained by invoking the listIterator method. Program 4: class ThreadEx extends Thread{ public void run() { System.out.print("Hello..."); } public static void main(String args[]) { ThreadEx T1 = new ThreadEx(); T1.start(); T1.stop(); T1.start(); }} Output: Run Time Exception Explanation:Exception in thread “main” java.lang.IllegalThreadStateException at java.lang.Thread.startThread cannot be started twice. This article is contributed by Pratik Agrawal. 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. Java-Output Java Program Output 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 Stack Class in Java Singleton Class in Java Arrow operator -> in C/C++ with Examples Output of Java Program | Set 1 delete keyword in C++ Output of C Programs | Set 1 Output of C++ programs | Set 34 (File Handling)
[ { "code": null, "e": 25695, "s": 25667, "text": "\n27 Dec, 2016" }, { "code": null, "e": 25727, "s": 25695, "text": "Difficulty level : Intermediate" }, { "code": null, "e": 25774, "s": 25727, "text": "Predict the output of following Java Programs." }, { "code": null, "e": 25785, "s": 25774, "text": "Program 1:" }, { "code": "class First{ public First() { System.out.println(\"a\"); }} class Second extends First{ public Second() { System.out.println(\"b\"); }} class Third extends Second{ public Third() { System.out.println(\"c\"); }} public class MainClass{ public static void main(String[] args) { Third c = new Third(); }}", "e": 26118, "s": 25785, "text": null }, { "code": null, "e": 26126, "s": 26118, "text": "Output:" }, { "code": null, "e": 26133, "s": 26126, "text": "a\nb\nc\n" }, { "code": null, "e": 26449, "s": 26133, "text": "Explanation:While creating a new object of ‘Third’ type, before calling the default constructor of Third class, the default constructor of super class is called i.e, Second class and then again before the default constructor of super class, default constructor of First class is called. And hence gives such output." }, { "code": null, "e": 26460, "s": 26449, "text": "Program 2:" }, { "code": "class First{ int i = 10; public First(int j) { System.out.println(i); this.i = j * 10; }} class Second extends First{ public Second(int j) { super(j); System.out.println(i); this.i = j * 20; }} public class MainClass{ public static void main(String[] args) { Second n = new Second(20); System.out.println(n.i); }}", "e": 26864, "s": 26460, "text": null }, { "code": null, "e": 26872, "s": 26864, "text": "Output:" }, { "code": null, "e": 26884, "s": 26872, "text": "10\n200\n400\n" }, { "code": null, "e": 27075, "s": 26884, "text": "Explanation:Since in ‘Second’ class it doesn’t have its own ‘i’, the variable is inherited from the super class. Also, the constructor of parent is called when we create an object of Second." }, { "code": null, "e": 27086, "s": 27075, "text": "Program 3:" }, { "code": "import java.util.*; class I { public static void main (String[] args) { Object i = new ArrayList().iterator(); System.out.print((i instanceof List) + \", \"); System.out.print((i instanceof Iterator) + \", \"); System.out.print(i instanceof ListIterator); } }", "e": 27384, "s": 27086, "text": null }, { "code": null, "e": 27392, "s": 27384, "text": "Output:" }, { "code": null, "e": 27412, "s": 27392, "text": "false, true, false\n" }, { "code": null, "e": 27635, "s": 27412, "text": "Explanation:The iterator() method returns an iterator over the elements in the list in proper sequence, it doesn’t return a List or a ListIterator object. A ListIterator can be obtained by invoking the listIterator method." }, { "code": null, "e": 27646, "s": 27635, "text": "Program 4:" }, { "code": "class ThreadEx extends Thread{ public void run() { System.out.print(\"Hello...\"); } public static void main(String args[]) { ThreadEx T1 = new ThreadEx(); T1.start(); T1.stop(); T1.start(); }}", "e": 27891, "s": 27646, "text": null }, { "code": null, "e": 27899, "s": 27891, "text": "Output:" }, { "code": null, "e": 27919, "s": 27899, "text": "Run Time Exception\n" }, { "code": null, "e": 28053, "s": 27919, "text": "Explanation:Exception in thread “main” java.lang.IllegalThreadStateException at java.lang.Thread.startThread cannot be started twice." }, { "code": null, "e": 28355, "s": 28053, "text": "This article is contributed by Pratik Agrawal. 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": 28480, "s": 28355, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28492, "s": 28480, "text": "Java-Output" }, { "code": null, "e": 28497, "s": 28492, "text": "Java" }, { "code": null, "e": 28512, "s": 28497, "text": "Program Output" }, { "code": null, "e": 28517, "s": 28512, "text": "Java" }, { "code": null, "e": 28615, "s": 28517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28634, "s": 28615, "text": "Interfaces in Java" }, { "code": null, "e": 28649, "s": 28634, "text": "Stream In Java" }, { "code": null, "e": 28667, "s": 28649, "text": "ArrayList in Java" }, { "code": null, "e": 28687, "s": 28667, "text": "Stack Class in Java" }, { "code": null, "e": 28711, "s": 28687, "text": "Singleton Class in Java" }, { "code": null, "e": 28752, "s": 28711, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28783, "s": 28752, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 28805, "s": 28783, "text": "delete keyword in C++" }, { "code": null, "e": 28834, "s": 28805, "text": "Output of C Programs | Set 1" } ]
list splice() function in C++ STL
14 Jun, 2022 The list::splice() is a built-in function in C++ STL which is used to transfer elements from one list to another. The splice() function can be used in three ways: Transfer all the elements of list x into another list at some position.Transfer only the element pointed by i from list x into the list at some position.Transfers the range [first, last) from list x into another list at some position. Transfer all the elements of list x into another list at some position. Transfer only the element pointed by i from list x into the list at some position. Transfers the range [first, last) from list x into another list at some position. Syntax: list1_name.splice (iterator position, list2) or list1_name.splice (iterator position, list2, iterator i) or list1_name.splice (iterator position, list2, iterator first, iterator last) Parameters: The function accepts four parameters which are specified as below: position – Specifies the position where the elements are to be transferred. list2 – It specifies a list object of the same type which is to be transferred. i – It specifies an iterator to the position of an element in list2 which is to be transferred. first, last – Iterators specifying a range of elements in list2 which is to be transferred in list1. The range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. Return value: This function doesnot returns anything. Below programs illustrate the above function: Program 1: Transfer all the elements of the list. CPP // CPP program to illustrate the// list::splice() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing lists list<int> l1 = { 1, 2, 3 }; list<int> l2 = { 4, 5 }; list<int> l3 = { 6, 7, 8 }; // transfer all the elements of l2 l1.splice(l1.begin(), l2); // at the beginning of l1 cout << "list l1 after splice operation" << endl; for (auto x : l1) cout << x << " "; // transfer all the elements of l1 l3.splice(l3.end(), l1); // at the end of l3 cout << "\nlist l3 after splice operation" << endl; for (auto x : l3) cout << x << " "; return 0;} list l1 after splice operation 4 5 1 2 3 list l3 after splice operation 6 7 8 4 5 1 2 3 Time Complexity: O(n) Auxiliary Space: O(1) Program 2: Transfer a single element. CPP // CPP program to illustrate the// list::splice() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing lists and iterator list<int> l1 = { 1, 2, 3 }; list<int> l2 = { 4, 5 }; list<int>::iterator it; // Iterator pointing to 4 it = l2.begin(); // transfer 4 at the end of l1 l1.splice(l1.end(), l2, it); cout << "list l1 after splice operation" << endl; for (auto x : l1) cout << x << " "; return 0;} list l1 after splice operation 1 2 3 4 Time Complexity: O(n) Auxiliary Space: O(1) Program 3: Transfer a range of elements. CPP // CPP program to illustrate the// list::splice() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing lists and iterator list<int> l1 = { 1, 2, 3, 4, 5 }; list<int> l2 = { 6, 7, 8 }; list<int>::iterator it; // iterator pointing to 1 it = l1.begin(); // advance the iterator by 2 positions advance(it, 2); // transfer 3, 4 and 5 at the // beginning of l2 l2.splice(l2.begin(), l1, it, l1.end()); cout << "list l2 after splice operation" << endl; for (auto x : l2) cout << x << " "; return 0;} list l2 after splice operation 3 4 5 6 7 8 Time Complexity: O(n) Auxiliary Space: O(1) mohataraghav12 Amreda aniketald2018 sooda367 adnanirshad158 utkarshgupta110092 CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 217, "s": 52, "text": "The list::splice() is a built-in function in C++ STL which is used to transfer elements from one list to another. The splice() function can be used in three ways: " }, { "code": null, "e": 452, "s": 217, "text": "Transfer all the elements of list x into another list at some position.Transfer only the element pointed by i from list x into the list at some position.Transfers the range [first, last) from list x into another list at some position." }, { "code": null, "e": 524, "s": 452, "text": "Transfer all the elements of list x into another list at some position." }, { "code": null, "e": 607, "s": 524, "text": "Transfer only the element pointed by i from list x into the list at some position." }, { "code": null, "e": 689, "s": 607, "text": "Transfers the range [first, last) from list x into another list at some position." }, { "code": null, "e": 698, "s": 689, "text": "Syntax: " }, { "code": null, "e": 916, "s": 698, "text": "list1_name.splice (iterator position, list2)\n or \nlist1_name.splice (iterator position, list2, iterator i)\n or \nlist1_name.splice (iterator position, list2, iterator first, iterator last)" }, { "code": null, "e": 996, "s": 916, "text": "Parameters: The function accepts four parameters which are specified as below: " }, { "code": null, "e": 1072, "s": 996, "text": "position – Specifies the position where the elements are to be transferred." }, { "code": null, "e": 1152, "s": 1072, "text": "list2 – It specifies a list object of the same type which is to be transferred." }, { "code": null, "e": 1248, "s": 1152, "text": "i – It specifies an iterator to the position of an element in list2 which is to be transferred." }, { "code": null, "e": 1481, "s": 1248, "text": "first, last – Iterators specifying a range of elements in list2 which is to be transferred in list1. The range includes all the elements between first and last, including the element pointed by first but not the one pointed by last." }, { "code": null, "e": 1632, "s": 1481, "text": "Return value: This function doesnot returns anything. Below programs illustrate the above function: Program 1: Transfer all the elements of the list. " }, { "code": null, "e": 1636, "s": 1632, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::splice() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing lists list<int> l1 = { 1, 2, 3 }; list<int> l2 = { 4, 5 }; list<int> l3 = { 6, 7, 8 }; // transfer all the elements of l2 l1.splice(l1.begin(), l2); // at the beginning of l1 cout << \"list l1 after splice operation\" << endl; for (auto x : l1) cout << x << \" \"; // transfer all the elements of l1 l3.splice(l3.end(), l1); // at the end of l3 cout << \"\\nlist l3 after splice operation\" << endl; for (auto x : l3) cout << x << \" \"; return 0;}", "e": 2270, "s": 1636, "text": null }, { "code": null, "e": 2359, "s": 2270, "text": "list l1 after splice operation\n4 5 1 2 3 \nlist l3 after splice operation\n6 7 8 4 5 1 2 3" }, { "code": null, "e": 2383, "s": 2361, "text": "Time Complexity: O(n)" }, { "code": null, "e": 2405, "s": 2383, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2445, "s": 2405, "text": "Program 2: Transfer a single element. " }, { "code": null, "e": 2449, "s": 2445, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::splice() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing lists and iterator list<int> l1 = { 1, 2, 3 }; list<int> l2 = { 4, 5 }; list<int>::iterator it; // Iterator pointing to 4 it = l2.begin(); // transfer 4 at the end of l1 l1.splice(l1.end(), l2, it); cout << \"list l1 after splice operation\" << endl; for (auto x : l1) cout << x << \" \"; return 0;}", "e": 2919, "s": 2449, "text": null }, { "code": null, "e": 2958, "s": 2919, "text": "list l1 after splice operation\n1 2 3 4" }, { "code": null, "e": 2982, "s": 2960, "text": "Time Complexity: O(n)" }, { "code": null, "e": 3004, "s": 2982, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3046, "s": 3004, "text": "Program 3: Transfer a range of elements. " }, { "code": null, "e": 3050, "s": 3046, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::splice() function#include <bits/stdc++.h>using namespace std; int main(){ // initializing lists and iterator list<int> l1 = { 1, 2, 3, 4, 5 }; list<int> l2 = { 6, 7, 8 }; list<int>::iterator it; // iterator pointing to 1 it = l1.begin(); // advance the iterator by 2 positions advance(it, 2); // transfer 3, 4 and 5 at the // beginning of l2 l2.splice(l2.begin(), l1, it, l1.end()); cout << \"list l2 after splice operation\" << endl; for (auto x : l2) cout << x << \" \"; return 0;}", "e": 3624, "s": 3050, "text": null }, { "code": null, "e": 3667, "s": 3624, "text": "list l2 after splice operation\n3 4 5 6 7 8" }, { "code": null, "e": 3691, "s": 3669, "text": "Time Complexity: O(n)" }, { "code": null, "e": 3713, "s": 3691, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3728, "s": 3713, "text": "mohataraghav12" }, { "code": null, "e": 3735, "s": 3728, "text": "Amreda" }, { "code": null, "e": 3749, "s": 3735, "text": "aniketald2018" }, { "code": null, "e": 3758, "s": 3749, "text": "sooda367" }, { "code": null, "e": 3773, "s": 3758, "text": "adnanirshad158" }, { "code": null, "e": 3792, "s": 3773, "text": "utkarshgupta110092" }, { "code": null, "e": 3806, "s": 3792, "text": "CPP-Functions" }, { "code": null, "e": 3815, "s": 3806, "text": "cpp-list" }, { "code": null, "e": 3819, "s": 3815, "text": "STL" }, { "code": null, "e": 3823, "s": 3819, "text": "C++" }, { "code": null, "e": 3827, "s": 3823, "text": "STL" }, { "code": null, "e": 3831, "s": 3827, "text": "CPP" } ]
numpy.angle() in Python
28 Nov, 2018 numpy.angle() function is used when we want to compute the angle of the complex argument. A complex number is represented by “ x + yi ” where x and y are real number and i= (-1)^1/2. The angle is calculated by the formula tan-1(x/y). Syntax : numpy.angle(z, deg=0) Parameters :z : [array_like] A complex number or sequence of complex numbers.deg : [bool, optional] Return angle in degrees if True, radians if False (default). Return :angle : The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. Code #1 : Working # Python program explaining# numpy.angle() function# when we want answer in radian import numpy as geekin_list =[2.0, 1.0j, 1 + 1j] print ("Input list : ", in_list) out_angle = geek.angle(in_list) print ("output angle in radians : ", out_angle) Output : Input list : [2.0, 1j, (1+1j)] output angle in radians : [ 0. 1.57079633 0.78539816] Code #2 : Working # Python program explaining# numpy.angle() function# when we want answer in degrees import numpy as geekin_list =[2.0, 1.0j, 1 + 1j] print ("Input list : ", in_list) out_angle = geek.angle(in_list, deg = True) print ("output angle in degrees : ", out_angle) Output : Input list : [2.0, 1j, (1+1j)] output angle in degrees : [ 0. 90. 45.] Python numpy-Mathematical Function 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 Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 262, "s": 28, "text": "numpy.angle() function is used when we want to compute the angle of the complex argument. A complex number is represented by “ x + yi ” where x and y are real number and i= (-1)^1/2. The angle is calculated by the formula tan-1(x/y)." }, { "code": null, "e": 293, "s": 262, "text": "Syntax : numpy.angle(z, deg=0)" }, { "code": null, "e": 454, "s": 293, "text": "Parameters :z : [array_like] A complex number or sequence of complex numbers.deg : [bool, optional] Return angle in degrees if True, radians if False (default)." }, { "code": null, "e": 576, "s": 454, "text": "Return :angle : The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64." }, { "code": null, "e": 594, "s": 576, "text": "Code #1 : Working" }, { "code": "# Python program explaining# numpy.angle() function# when we want answer in radian import numpy as geekin_list =[2.0, 1.0j, 1 + 1j] print (\"Input list : \", in_list) out_angle = geek.angle(in_list) print (\"output angle in radians : \", out_angle) ", "e": 846, "s": 594, "text": null }, { "code": null, "e": 855, "s": 846, "text": "Output :" }, { "code": null, "e": 954, "s": 855, "text": "Input list : [2.0, 1j, (1+1j)]\noutput angle in radians : [ 0. 1.57079633 0.78539816]\n" }, { "code": null, "e": 973, "s": 954, "text": " Code #2 : Working" }, { "code": "# Python program explaining# numpy.angle() function# when we want answer in degrees import numpy as geekin_list =[2.0, 1.0j, 1 + 1j] print (\"Input list : \", in_list) out_angle = geek.angle(in_list, deg = True) print (\"output angle in degrees : \", out_angle) ", "e": 1238, "s": 973, "text": null }, { "code": null, "e": 1247, "s": 1238, "text": "Output :" }, { "code": null, "e": 1325, "s": 1247, "text": "Input list : [2.0, 1j, (1+1j)]\noutput angle in degrees : [ 0. 90. 45.]\n" }, { "code": null, "e": 1360, "s": 1325, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1373, "s": 1360, "text": "Python-numpy" }, { "code": null, "e": 1380, "s": 1373, "text": "Python" }, { "code": null, "e": 1478, "s": 1380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1496, "s": 1478, "text": "Python Dictionary" }, { "code": null, "e": 1538, "s": 1496, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1560, "s": 1538, "text": "Enumerate() in Python" }, { "code": null, "e": 1595, "s": 1560, "text": "Read a file line by line in Python" }, { "code": null, "e": 1621, "s": 1595, "text": "Python String | replace()" }, { "code": null, "e": 1653, "s": 1621, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1682, "s": 1653, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1709, "s": 1682, "text": "Python Classes and Objects" }, { "code": null, "e": 1739, "s": 1709, "text": "Iterate over a list in Python" } ]
Difference between COMP and COMP3
27 Sep, 2021 Internally the computer stores the data in more than one form. The Cobol language facilitates the programmer to specify the internal representation of the data according to the need. There are two internal forms available in the Cobol: DISPLAY –It is the default internal representation of the data. Any type of data can be specified with the DISPLAY internal representation.COMPUTATIONAL –Only the numeric data’s can be specified with COMPUTATIONAL internal representation. There are many types of COMPUTATIONAL representation, like COMP, COMP-1 , COMP-2, COMP-3 etc. DISPLAY –It is the default internal representation of the data. Any type of data can be specified with the DISPLAY internal representation. COMPUTATIONAL –Only the numeric data’s can be specified with COMPUTATIONAL internal representation. There are many types of COMPUTATIONAL representation, like COMP, COMP-1 , COMP-2, COMP-3 etc. USAGE clause is used to specify the type of internal representation. You can use any level-number for USAGE clause except 66 or 88. Syntax: USAGE IS {COMPUTATIONAL/COMP/DISPLAY}. 1. COMP :Usage clause is applicable only on numerical data items. It represents the data purely in binary form. and can store the data either in half word or in full word depending on the size of the data. We can use only 9 and S during the data declaration: 9 is used to store declare integer variables. S is used to store the sign. 2. COMP3 :Usage clause is applicable only on numerical data items. It stores the data in packed decimal form. It uses one rightmost bit to store the sign irrespective of weather we have used S in PIC clause or not. The hexadecimal number C and F stores the positive sign at rightmost bit and D stores the negative sign at rightmost bit. We can use 9, S and V in PIC clause during data declaration. V is used to store decimal point at a particular location in data item. Difference between COMP and COMP3 : COMP COMP3 The memory to be occupied by the data according to the length is predefined i.e. : 9(01) – 9(04) : 16 bits (2 bytes) 9(05) – 9(09) : 32 bits (4 bytes) S9(10) – S9(18) : 64 bits (8 bytes) The memory to be occupied by the data is defined by the following formula: (length of variable + 1)/2 bytes. Example : The memory occupied by S9(3) is: (3+1)/2 i.e. 2 bytes. Example: 02 CompVariable PIC 9 USAGE IS COMP. 02 CompVariable1 PIC S9(5) USAGE IS COMP. Example: 02 Variable PIC 9 USAGE IS COMP3. 02 Variable1 PIC S9(10) USAGE IS COMP3. 02 Variable2 PIC S9V99 USAGE IS COMP3. Picked COBOL Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies 50 Common Ports You Should Know Naming Convention in C++ Floyd’s Cycle Finding Algorithm Layers of OSI Model TCP/IP Model Basics of Computer Networking Differences between TCP and UDP Types of Network Topology
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 265, "s": 28, "text": "Internally the computer stores the data in more than one form. The Cobol language facilitates the programmer to specify the internal representation of the data according to the need. There are two internal forms available in the Cobol:" }, { "code": null, "e": 598, "s": 265, "text": "DISPLAY –It is the default internal representation of the data. Any type of data can be specified with the DISPLAY internal representation.COMPUTATIONAL –Only the numeric data’s can be specified with COMPUTATIONAL internal representation. There are many types of COMPUTATIONAL representation, like COMP, COMP-1 , COMP-2, COMP-3 etc." }, { "code": null, "e": 738, "s": 598, "text": "DISPLAY –It is the default internal representation of the data. Any type of data can be specified with the DISPLAY internal representation." }, { "code": null, "e": 932, "s": 738, "text": "COMPUTATIONAL –Only the numeric data’s can be specified with COMPUTATIONAL internal representation. There are many types of COMPUTATIONAL representation, like COMP, COMP-1 , COMP-2, COMP-3 etc." }, { "code": null, "e": 1064, "s": 932, "text": "USAGE clause is used to specify the type of internal representation. You can use any level-number for USAGE clause except 66 or 88." }, { "code": null, "e": 1119, "s": 1064, "text": "Syntax:\n USAGE IS {COMPUTATIONAL/COMP/DISPLAY}." }, { "code": null, "e": 1378, "s": 1119, "text": "1. COMP :Usage clause is applicable only on numerical data items. It represents the data purely in binary form. and can store the data either in half word or in full word depending on the size of the data. We can use only 9 and S during the data declaration:" }, { "code": null, "e": 1424, "s": 1378, "text": "9 is used to store declare integer variables." }, { "code": null, "e": 1453, "s": 1424, "text": "S is used to store the sign." }, { "code": null, "e": 1851, "s": 1453, "text": "2. COMP3 :Usage clause is applicable only on numerical data items. It stores the data in packed decimal form. It uses one rightmost bit to store the sign irrespective of weather we have used S in PIC clause or not. The hexadecimal number C and F stores the positive sign at rightmost bit and D stores the negative sign at rightmost bit. We can use 9, S and V in PIC clause during data declaration." }, { "code": null, "e": 1923, "s": 1851, "text": "V is used to store decimal point at a particular location in data item." }, { "code": null, "e": 1959, "s": 1923, "text": "Difference between COMP and COMP3 :" }, { "code": null, "e": 1964, "s": 1959, "text": "COMP" }, { "code": null, "e": 1970, "s": 1964, "text": "COMP3" }, { "code": null, "e": 2053, "s": 1970, "text": "The memory to be occupied by the data according to the length is predefined i.e. :" }, { "code": null, "e": 2087, "s": 2053, "text": "9(01) – 9(04) : 16 bits (2 bytes)" }, { "code": null, "e": 2122, "s": 2087, "text": "9(05) – 9(09) : 32 bits (4 bytes)" }, { "code": null, "e": 2159, "s": 2122, "text": "S9(10) – S9(18) : 64 bits (8 bytes)" }, { "code": null, "e": 2234, "s": 2159, "text": "The memory to be occupied by the data is defined by the following formula:" }, { "code": null, "e": 2268, "s": 2234, "text": "(length of variable + 1)/2 bytes." }, { "code": null, "e": 2311, "s": 2268, "text": "Example : The memory occupied by S9(3) is:" }, { "code": null, "e": 2333, "s": 2311, "text": "(3+1)/2 i.e. 2 bytes." }, { "code": null, "e": 2437, "s": 2333, "text": "Example:\n 02 CompVariable PIC 9 USAGE IS COMP.\n 02 CompVariable1 PIC S9(5) USAGE IS COMP." }, { "code": null, "e": 2583, "s": 2437, "text": "Example:\n 02 Variable PIC 9 USAGE IS COMP3.\n 02 Variable1 PIC S9(10) USAGE IS COMP3.\n 02 Variable2 PIC S9V99 USAGE IS COMP3." }, { "code": null, "e": 2590, "s": 2583, "text": "Picked" }, { "code": null, "e": 2596, "s": 2590, "text": "COBOL" }, { "code": null, "e": 2614, "s": 2596, "text": "Computer Networks" }, { "code": null, "e": 2632, "s": 2614, "text": "Computer Networks" }, { "code": null, "e": 2730, "s": 2632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2804, "s": 2730, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 2857, "s": 2804, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 2889, "s": 2857, "text": "50 Common Ports You Should Know" }, { "code": null, "e": 2914, "s": 2889, "text": "Naming Convention in C++" }, { "code": null, "e": 2946, "s": 2914, "text": "Floyd’s Cycle Finding Algorithm" }, { "code": null, "e": 2966, "s": 2946, "text": "Layers of OSI Model" }, { "code": null, "e": 2979, "s": 2966, "text": "TCP/IP Model" }, { "code": null, "e": 3009, "s": 2979, "text": "Basics of Computer Networking" }, { "code": null, "e": 3041, "s": 3009, "text": "Differences between TCP and UDP" } ]
Java Program to Write into a File
12 Apr, 2022 In this article, we will see different ways of writing into a File using Java Programming language. Java FileWriter class in java is used to write character-oriented data to a file as this class is character-oriented class because of what it is used in file handling in java. There are many ways to write into a file in Java as there are many classes and methods which can fulfill the goal as follows: Using writeString() methodUsing FileWriter ClassUsing BufferedWriter ClassUsing FileOutputStream Class Using writeString() method Using FileWriter Class Using BufferedWriter Class Using FileOutputStream Class This method is supported by Java version 11. This method can take four parameters. These are file path, character sequence, charset, and options. The first two parameters are mandatory for this method to write into a file. It writes the characters as the content of the file. It returns the file path and can throw four types of exceptions. It is better to use when the content of the file is short. Example: It shows the use of the writeString() method that is under the Files class to write data into a file. Another class, Path, is used to assign the filename with a path where the content will be written. Files class has another method named readString() to read the content of any existing file that is used in the code to check the content is properly written in the file. Java // Java Program to Write Into a File// using writeString() Method // Importing required classesimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Assigning the content of the file String text = "Welcome to geekforgeeks\nHappy Learning!"; // Defining the file name of the file Path fileName = Path.of( "/Users/mayanksolanki/Desktop/demo.docx"); // Writing into the file Files.writeString(fileName, text); // Reading the content of the file String file_content = Files.readString(fileName); // Printing the content inside the file System.out.println(file_content); }} Welcome to geekforgeeks Happy Learning! If the content of the file is short, then using the FileWriter class to write in the file is another better option. It also writes the stream of characters as the content of the file like writeString() method. The constructor of this class defines the default character encoding and the default buffer size in bytes. The following below example illustrates the use of the FileWriter class to write content into a file. It requires creating the object of the FileWriter class with the filename to write into a file. Next, the write() method is used to write the value of the text variable in the file. If any error occurs at the time of writing the file, then an IOException will be thrown, and the error message will be printed from the catch block. Example: Java // Java Program to Write into a File// using FileWriterClass // Importing required classesimport java.io.FileWriter;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Content to be assigned to a file // Custom input just for illustratinon purposes String text = "Computer Science Portal GeeksforGeeks"; // Try block to check if exception occurs try { // Create a FileWriter object // to write in the file FileWriter fWriter = new FileWriter( "/Users/mayanksolanki/Desktop/demo.docx"); // Writing into file // Note: The content taken above inside the // string fWriter.write(text); // Printing the contents of a file System.out.println(text); // Closing the file writing connection fWriter.close(); // Display message for successful execution of // program on the console System.out.println( "File is created successfully with the content."); } // Catch block to handle if exception occurs catch (IOException e) { // Print the exception System.out.print(e.getMessage()); } }} File is created successfully with the content. It is used to write text to a character-output stream. It has a default buffer size, but a large buffer size can be assigned. It is useful for writing characters, strings, and arrays. It is better to wrap this class with any writer class for writing data to a file if no prompt output is required. Example: Java // Java Program to write into a File// Using BufferedWriter Class // Importing java input output librariesimport java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Assigning the file content // Note: Custom contents taken as input to // illustrate String text = "Computer Science Portal GeeksforGeks"; // Try block to check for exceptions try { // Step 1: Create an object of BufferedWriter BufferedWriter f_writer = new BufferedWriter(new FileWriter( "/Users/mayanksolanki/Desktop/demo.docx")); // Step 2: Write text(content) to file f_writer.write(text); // Step 3: Printing the content inside the file // on the terminal/CMD System.out.print(text); // Step 4: Display message showcasing // successful execution of the program System.out.print( "File is created successfully with the content."); // Step 5: Close the BufferedWriter object f_writer.close(); } // Catch block to handle if exceptions occurs catch (IOException e) { // Print the exception on console // using getMessage() method System.out.print(e.getMessage()); } }} File is created successfully with the content. The following example shows the use of BufferedWriter class to write into a file. It also requires creating the object of BufferedWriter class like FileWriter to write content into the file. But this class supports large content to write into the file by using a large buffer size. It is used to write raw stream data to a file. FileWriter and BufferedWriter classes are used to write only the text to a file, but the binary data can be written by using the FileOutputStream class. To write data into a file using FileOutputStream class is shown in the following example. It also requires creating the object of the class with the filename to write data into a file. Here, the string content is converted into the byte array that is written into the file by using the write() method. Example: Java // Java Program to Write into a File// using FileOutputStream Class // Importing java input output classesimport java.io.FileOutputStream;import java.io.IOException; public class GFG { // Main driver method public static void main(String[] args) { // Assign the file content String fileContent = "Welcome to geeksforgeeks"; FileOutputStream outputStream = null; // Try block to check if exception occurs try { // Step 1: Create an object of FileOutputStream outputStream = new FileOutputStream("file.txt"); // Step 2: Store byte content from string byte[] strToBytes = fileContent.getBytes(); // Step 3: Write into the file outputStream.write(strToBytes); // Print the success message (Optional) System.out.print( "File is created successfully with the content."); } // Catch block to handle the exception catch (IOException e) { // Display the exception/s System.out.print(e.getMessage()); } // finally keyword is used with in try catch block // and this code will always execute whether // exception occurred or not finally { // Step 4: Close the object if (outputStream != null) { // Note: Second try catch block ensures that // the file is closed even if an error // occurs try { // Closing the file connections // if no exception has occurred outputStream.close(); } catch (IOException e) { // Display exceptions if occurred System.out.print(e.getMessage()); } } } }} File is created successfully with the content. surinderdawra388 anikakapoor sagartomar9927 surindertarika1234 devmrfitz solankimayank nishkarshgandhi simmytarika5 Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Apr, 2022" }, { "code": null, "e": 329, "s": 52, "text": "In this article, we will see different ways of writing into a File using Java Programming language. Java FileWriter class in java is used to write character-oriented data to a file as this class is character-oriented class because of what it is used in file handling in java. " }, { "code": null, "e": 455, "s": 329, "text": "There are many ways to write into a file in Java as there are many classes and methods which can fulfill the goal as follows:" }, { "code": null, "e": 558, "s": 455, "text": "Using writeString() methodUsing FileWriter ClassUsing BufferedWriter ClassUsing FileOutputStream Class" }, { "code": null, "e": 585, "s": 558, "text": "Using writeString() method" }, { "code": null, "e": 608, "s": 585, "text": "Using FileWriter Class" }, { "code": null, "e": 635, "s": 608, "text": "Using BufferedWriter Class" }, { "code": null, "e": 664, "s": 635, "text": "Using FileOutputStream Class" }, { "code": null, "e": 1064, "s": 664, "text": "This method is supported by Java version 11. This method can take four parameters. These are file path, character sequence, charset, and options. The first two parameters are mandatory for this method to write into a file. It writes the characters as the content of the file. It returns the file path and can throw four types of exceptions. It is better to use when the content of the file is short." }, { "code": null, "e": 1444, "s": 1064, "text": "Example: It shows the use of the writeString() method that is under the Files class to write data into a file. Another class, Path, is used to assign the filename with a path where the content will be written. Files class has another method named readString() to read the content of any existing file that is used in the code to check the content is properly written in the file." }, { "code": null, "e": 1449, "s": 1444, "text": "Java" }, { "code": "// Java Program to Write Into a File// using writeString() Method // Importing required classesimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Assigning the content of the file String text = \"Welcome to geekforgeeks\\nHappy Learning!\"; // Defining the file name of the file Path fileName = Path.of( \"/Users/mayanksolanki/Desktop/demo.docx\"); // Writing into the file Files.writeString(fileName, text); // Reading the content of the file String file_content = Files.readString(fileName); // Printing the content inside the file System.out.println(file_content); }}", "e": 2278, "s": 1449, "text": null }, { "code": null, "e": 2318, "s": 2278, "text": "Welcome to geekforgeeks\nHappy Learning!" }, { "code": null, "e": 2635, "s": 2318, "text": "If the content of the file is short, then using the FileWriter class to write in the file is another better option. It also writes the stream of characters as the content of the file like writeString() method. The constructor of this class defines the default character encoding and the default buffer size in bytes." }, { "code": null, "e": 3068, "s": 2635, "text": "The following below example illustrates the use of the FileWriter class to write content into a file. It requires creating the object of the FileWriter class with the filename to write into a file. Next, the write() method is used to write the value of the text variable in the file. If any error occurs at the time of writing the file, then an IOException will be thrown, and the error message will be printed from the catch block." }, { "code": null, "e": 3077, "s": 3068, "text": "Example:" }, { "code": null, "e": 3082, "s": 3077, "text": "Java" }, { "code": "// Java Program to Write into a File// using FileWriterClass // Importing required classesimport java.io.FileWriter;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Content to be assigned to a file // Custom input just for illustratinon purposes String text = \"Computer Science Portal GeeksforGeeks\"; // Try block to check if exception occurs try { // Create a FileWriter object // to write in the file FileWriter fWriter = new FileWriter( \"/Users/mayanksolanki/Desktop/demo.docx\"); // Writing into file // Note: The content taken above inside the // string fWriter.write(text); // Printing the contents of a file System.out.println(text); // Closing the file writing connection fWriter.close(); // Display message for successful execution of // program on the console System.out.println( \"File is created successfully with the content.\"); } // Catch block to handle if exception occurs catch (IOException e) { // Print the exception System.out.print(e.getMessage()); } }}", "e": 4434, "s": 3082, "text": null }, { "code": null, "e": 4481, "s": 4434, "text": "File is created successfully with the content." }, { "code": null, "e": 4779, "s": 4481, "text": "It is used to write text to a character-output stream. It has a default buffer size, but a large buffer size can be assigned. It is useful for writing characters, strings, and arrays. It is better to wrap this class with any writer class for writing data to a file if no prompt output is required." }, { "code": null, "e": 4788, "s": 4779, "text": "Example:" }, { "code": null, "e": 4793, "s": 4788, "text": "Java" }, { "code": "// Java Program to write into a File// Using BufferedWriter Class // Importing java input output librariesimport java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Assigning the file content // Note: Custom contents taken as input to // illustrate String text = \"Computer Science Portal GeeksforGeks\"; // Try block to check for exceptions try { // Step 1: Create an object of BufferedWriter BufferedWriter f_writer = new BufferedWriter(new FileWriter( \"/Users/mayanksolanki/Desktop/demo.docx\")); // Step 2: Write text(content) to file f_writer.write(text); // Step 3: Printing the content inside the file // on the terminal/CMD System.out.print(text); // Step 4: Display message showcasing // successful execution of the program System.out.print( \"File is created successfully with the content.\"); // Step 5: Close the BufferedWriter object f_writer.close(); } // Catch block to handle if exceptions occurs catch (IOException e) { // Print the exception on console // using getMessage() method System.out.print(e.getMessage()); } }}", "e": 6267, "s": 4793, "text": null }, { "code": null, "e": 6314, "s": 6267, "text": "File is created successfully with the content." }, { "code": null, "e": 6596, "s": 6314, "text": "The following example shows the use of BufferedWriter class to write into a file. It also requires creating the object of BufferedWriter class like FileWriter to write content into the file. But this class supports large content to write into the file by using a large buffer size." }, { "code": null, "e": 6796, "s": 6596, "text": "It is used to write raw stream data to a file. FileWriter and BufferedWriter classes are used to write only the text to a file, but the binary data can be written by using the FileOutputStream class." }, { "code": null, "e": 7098, "s": 6796, "text": "To write data into a file using FileOutputStream class is shown in the following example. It also requires creating the object of the class with the filename to write data into a file. Here, the string content is converted into the byte array that is written into the file by using the write() method." }, { "code": null, "e": 7107, "s": 7098, "text": "Example:" }, { "code": null, "e": 7112, "s": 7107, "text": "Java" }, { "code": "// Java Program to Write into a File// using FileOutputStream Class // Importing java input output classesimport java.io.FileOutputStream;import java.io.IOException; public class GFG { // Main driver method public static void main(String[] args) { // Assign the file content String fileContent = \"Welcome to geeksforgeeks\"; FileOutputStream outputStream = null; // Try block to check if exception occurs try { // Step 1: Create an object of FileOutputStream outputStream = new FileOutputStream(\"file.txt\"); // Step 2: Store byte content from string byte[] strToBytes = fileContent.getBytes(); // Step 3: Write into the file outputStream.write(strToBytes); // Print the success message (Optional) System.out.print( \"File is created successfully with the content.\"); } // Catch block to handle the exception catch (IOException e) { // Display the exception/s System.out.print(e.getMessage()); } // finally keyword is used with in try catch block // and this code will always execute whether // exception occurred or not finally { // Step 4: Close the object if (outputStream != null) { // Note: Second try catch block ensures that // the file is closed even if an error // occurs try { // Closing the file connections // if no exception has occurred outputStream.close(); } catch (IOException e) { // Display exceptions if occurred System.out.print(e.getMessage()); } } } }}", "e": 8969, "s": 7112, "text": null }, { "code": null, "e": 9016, "s": 8969, "text": "File is created successfully with the content." }, { "code": null, "e": 9033, "s": 9016, "text": "surinderdawra388" }, { "code": null, "e": 9045, "s": 9033, "text": "anikakapoor" }, { "code": null, "e": 9060, "s": 9045, "text": "sagartomar9927" }, { "code": null, "e": 9079, "s": 9060, "text": "surindertarika1234" }, { "code": null, "e": 9089, "s": 9079, "text": "devmrfitz" }, { "code": null, "e": 9103, "s": 9089, "text": "solankimayank" }, { "code": null, "e": 9119, "s": 9103, "text": "nishkarshgandhi" }, { "code": null, "e": 9132, "s": 9119, "text": "simmytarika5" }, { "code": null, "e": 9143, "s": 9132, "text": "Java-Files" }, { "code": null, "e": 9150, "s": 9143, "text": "Picked" }, { "code": null, "e": 9155, "s": 9150, "text": "Java" }, { "code": null, "e": 9169, "s": 9155, "text": "Java Programs" }, { "code": null, "e": 9174, "s": 9169, "text": "Java" }, { "code": null, "e": 9272, "s": 9174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9323, "s": 9272, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 9354, "s": 9323, "text": "How to iterate any Map in Java" }, { "code": null, "e": 9373, "s": 9354, "text": "Interfaces in Java" }, { "code": null, "e": 9403, "s": 9373, "text": "HashMap in Java with Examples" }, { "code": null, "e": 9418, "s": 9403, "text": "Stream In Java" }, { "code": null, "e": 9446, "s": 9418, "text": "Initializing a List in Java" }, { "code": null, "e": 9472, "s": 9446, "text": "Java Programming Examples" }, { "code": null, "e": 9516, "s": 9472, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 9550, "s": 9516, "text": "Convert Double to Integer in Java" } ]
How to use AutoCheck property of CheckBox in C#?
30 Sep, 2021 The CheckBox control is the part of the windows form that is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. You are allowed to set a value that determines the Checked or CheckedStates values and also the appearance of the CheckBox is set automatically when you click a CheckBox using the AutoCheck property. The value of this property is of System.Boolean type. If the value of AutoCheck property is true, then the value of Checked or CheckState and the appearance of the CheckBox is changed automatically when you click a CheckBox. Otherwise, false. The default value of this property is true. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the AutoCheck property of a CheckBox using the following steps: Step 1: Create a windows form as shown in the below image Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the CheckBox control to set the value of the AutoCheck property. Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the AutoCheck property of a CheckBox programmatically using the following syntax: public bool AutoCheck { get; set; } Following steps are used to set the AutoCheck property of the CheckBox: Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class. // Creating checkbox CheckBox Mycheckbox = new CheckBox(); Step 2: After creating CheckBox, set the AutoCheck property of the CheckBox provided by the CheckBox class. // Set the AutoCheck property of the CheckBox Mycheckbox.AutoCheck = false; Step 3: And last add this checkbox control to form using Add() method. // Add this checkbox to form this.Controls.Add(Mycheckbox); Example: C# using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = "Select language:"; l.AutoSize = true; l.Location = new Point(233, 111); l.Font = new Font("Bradley Hand ITC", 12); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = "C#"; Mycheckbox.AutoCheck = false; Mycheckbox.Font = new Font("Bradley Hand ITC", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 198); Mycheckbox1.Text = "Ruby"; Mycheckbox1.AutoCheck = true; Mycheckbox1.Font = new Font("Bradley Hand ITC", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}} Output: varshagumber28 sagartomar9927 CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2021" }, { "code": null, "e": 781, "s": 28, "text": "The CheckBox control is the part of the windows form that is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. You are allowed to set a value that determines the Checked or CheckedStates values and also the appearance of the CheckBox is set automatically when you click a CheckBox using the AutoCheck property. The value of this property is of System.Boolean type. If the value of AutoCheck property is true, then the value of Checked or CheckState and the appearance of the CheckBox is changed automatically when you click a CheckBox. Otherwise, false. The default value of this property is true. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 892, "s": 781, "text": "1. Design-Time: It is the simplest way to set the AutoCheck property of a CheckBox using the following steps: " }, { "code": null, "e": 1009, "s": 892, "text": "Step 1: Create a windows form as shown in the below image Visual Studio -> File -> New -> Project -> WindowsFormApp " }, { "code": null, "e": 1170, "s": 1009, "text": "Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. " }, { "code": null, "e": 1297, "s": 1170, "text": "Step 3: After drag and drop you will go to the properties of the CheckBox control to set the value of the AutoCheck property. " }, { "code": null, "e": 1306, "s": 1297, "text": "Output: " }, { "code": null, "e": 1481, "s": 1306, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the AutoCheck property of a CheckBox programmatically using the following syntax: " }, { "code": null, "e": 1517, "s": 1481, "text": "public bool AutoCheck { get; set; }" }, { "code": null, "e": 1591, "s": 1517, "text": "Following steps are used to set the AutoCheck property of the CheckBox: " }, { "code": null, "e": 1682, "s": 1591, "text": "Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class." }, { "code": null, "e": 1741, "s": 1682, "text": "// Creating checkbox\nCheckBox Mycheckbox = new CheckBox();" }, { "code": null, "e": 1849, "s": 1741, "text": "Step 2: After creating CheckBox, set the AutoCheck property of the CheckBox provided by the CheckBox class." }, { "code": null, "e": 1925, "s": 1849, "text": "// Set the AutoCheck property of the CheckBox\nMycheckbox.AutoCheck = false;" }, { "code": null, "e": 1997, "s": 1925, "text": "Step 3: And last add this checkbox control to form using Add() method. " }, { "code": null, "e": 2057, "s": 1997, "text": "// Add this checkbox to form\nthis.Controls.Add(Mycheckbox);" }, { "code": null, "e": 2066, "s": 2057, "text": "Example:" }, { "code": null, "e": 2069, "s": 2066, "text": "C#" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = \"Select language:\"; l.AutoSize = true; l.Location = new Point(233, 111); l.Font = new Font(\"Bradley Hand ITC\", 12); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = \"C#\"; Mycheckbox.AutoCheck = false; Mycheckbox.Font = new Font(\"Bradley Hand ITC\", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 198); Mycheckbox1.Text = \"Ruby\"; Mycheckbox1.AutoCheck = true; Mycheckbox1.Font = new Font(\"Bradley Hand ITC\", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}", "e": 3606, "s": 2069, "text": null }, { "code": null, "e": 3615, "s": 3606, "text": "Output: " }, { "code": null, "e": 3632, "s": 3617, "text": "varshagumber28" }, { "code": null, "e": 3647, "s": 3632, "text": "sagartomar9927" }, { "code": null, "e": 3678, "s": 3647, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 3681, "s": 3678, "text": "C#" }, { "code": null, "e": 3779, "s": 3681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3807, "s": 3779, "text": "C# Dictionary with examples" }, { "code": null, "e": 3850, "s": 3807, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3881, "s": 3850, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3896, "s": 3881, "text": "C# | Delegates" }, { "code": null, "e": 3945, "s": 3896, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3961, "s": 3945, "text": "C# | Data Types" }, { "code": null, "e": 3984, "s": 3961, "text": "C# | Method Overriding" }, { "code": null, "e": 4024, "s": 3984, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 4042, "s": 4024, "text": "C# | Constructors" } ]
numpy.mask_indices() function | Python
22 Apr, 2020 numpy.mask_indices() function return the indices to access (n, n) arrays, given a masking function. Syntax : numpy.mask_indices(n, mask_func, k = 0)Parameters :n : [int] The returned indices will be valid to access arrays of shape (n, n).mask_func : [callable] A function whose call signature is similar to that of triu, tril.k : [scalar] An optional argument which is passed through to mask_func.Return : [tuple of arrays] The n arrays of indices corresponding to the locations where mask_func(np.ones((n, n)), k) is True. Code #1 : # Python program explaining# numpy.mask_indices() function # importing numpy as geek import numpy as geek gfg = geek.mask_indices(3, geek.triu) print (gfg) Output : (array([0, 0, 0, 1, 1, 2]), array([0, 1, 2, 1, 2, 2])) Code #2 : # Python program explaining# numpy.mask_indices() function # importing numpy as geek import numpy as geek gfg = geek.mask_indices(3, geek.triu, 1) print (gfg) Output : (array([0, 0, 1]), array([1, 2, 2])) Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 128, "s": 28, "text": "numpy.mask_indices() function return the indices to access (n, n) arrays, given a masking function." }, { "code": null, "e": 552, "s": 128, "text": "Syntax : numpy.mask_indices(n, mask_func, k = 0)Parameters :n : [int] The returned indices will be valid to access arrays of shape (n, n).mask_func : [callable] A function whose call signature is similar to that of triu, tril.k : [scalar] An optional argument which is passed through to mask_func.Return : [tuple of arrays] The n arrays of indices corresponding to the locations where mask_func(np.ones((n, n)), k) is True." }, { "code": null, "e": 562, "s": 552, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.mask_indices() function # importing numpy as geek import numpy as geek gfg = geek.mask_indices(3, geek.triu) print (gfg)", "e": 721, "s": 562, "text": null }, { "code": null, "e": 730, "s": 721, "text": "Output :" }, { "code": null, "e": 786, "s": 730, "text": "(array([0, 0, 0, 1, 1, 2]), array([0, 1, 2, 1, 2, 2]))\n" }, { "code": null, "e": 797, "s": 786, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.mask_indices() function # importing numpy as geek import numpy as geek gfg = geek.mask_indices(3, geek.triu, 1) print (gfg)", "e": 959, "s": 797, "text": null }, { "code": null, "e": 968, "s": 959, "text": "Output :" }, { "code": null, "e": 1006, "s": 968, "text": "(array([0, 0, 1]), array([1, 2, 2]))\n" }, { "code": null, "e": 1037, "s": 1006, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 1050, "s": 1037, "text": "Python-numpy" }, { "code": null, "e": 1057, "s": 1050, "text": "Python" } ]
Python – Consecutive Pairs comma removal
28 Jun, 2022 Sometimes, while working amongst lists, we can have a problem in which we need to pair up elements from two lists. In this, we can have pairs in which we find that there is comma that is printed in tuple and we wish to avoid it usually. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + list comprehension + replace() The combination of above functionalities can be used to perform this task. In this, we join lists using zip() and task of removal of comma and joining is performed using replace(). Python3 # Python3 code to demonstrate# Consecutive Pairs Duplication Removal# using list comprehension + zip() + replace() # Initializing liststest_list1 = [1, 2, 3, 4, 5]test_list2 = [2, 3, 4, 5, 6] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Consecutive Pairs Duplication Removal# using list comprehension + zip() + replace()res = str(list(zip(test_list1, test_list2))).replace('), (', ') (') # printing resultprint ("The combined list after consecutive comma removal : " + str(res)) The original list 1 is : [1, 2, 3, 4, 5] The original list 2 is : [2, 3, 4, 5, 6] The combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)] Method #2 : Using map() + list comprehension + zip() This is yet another way in which this task can be performed. In this we perform the task performed using replace() with map(). Python3 # Python3 code to demonstrate# Consecutive Pairs Duplication Removal# using list comprehension + zip() + map() # Initializing liststest_list1 = [1, 2, 3, 4, 5]test_list2 = [2, 3, 4, 5, 6] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Consecutive Pairs Duplication Removal# using list comprehension + zip() + map()res = "[" + " ".join(map(str, zip(test_list1, test_list2))) + "]" # printing resultprint ("The combined list after consecutive comma removal : " + str(res)) The original list 1 is : [1, 2, 3, 4, 5] The original list 2 is : [2, 3, 4, 5, 6] The combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)] vinayedula Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2022" }, { "code": null, "e": 567, "s": 28, "text": "Sometimes, while working amongst lists, we can have a problem in which we need to pair up elements from two lists. In this, we can have pairs in which we find that there is comma that is printed in tuple and we wish to avoid it usually. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + list comprehension + replace() The combination of above functionalities can be used to perform this task. In this, we join lists using zip() and task of removal of comma and joining is performed using replace(). " }, { "code": null, "e": 575, "s": 567, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Consecutive Pairs Duplication Removal# using list comprehension + zip() + replace() # Initializing liststest_list1 = [1, 2, 3, 4, 5]test_list2 = [2, 3, 4, 5, 6] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Consecutive Pairs Duplication Removal# using list comprehension + zip() + replace()res = str(list(zip(test_list1, test_list2))).replace('), (', ') (') # printing resultprint (\"The combined list after consecutive comma removal : \" + str(res))", "e": 1149, "s": 575, "text": null }, { "code": null, "e": 1320, "s": 1149, "text": "The original list 1 is : [1, 2, 3, 4, 5]\nThe original list 2 is : [2, 3, 4, 5, 6]\nThe combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]" }, { "code": null, "e": 1503, "s": 1320, "text": " Method #2 : Using map() + list comprehension + zip() This is yet another way in which this task can be performed. In this we perform the task performed using replace() with map(). " }, { "code": null, "e": 1511, "s": 1503, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Consecutive Pairs Duplication Removal# using list comprehension + zip() + map() # Initializing liststest_list1 = [1, 2, 3, 4, 5]test_list2 = [2, 3, 4, 5, 6] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Consecutive Pairs Duplication Removal# using list comprehension + zip() + map()res = \"[\" + \" \".join(map(str, zip(test_list1, test_list2))) + \"]\" # printing resultprint (\"The combined list after consecutive comma removal : \" + str(res))", "e": 2075, "s": 1511, "text": null }, { "code": null, "e": 2246, "s": 2075, "text": "The original list 1 is : [1, 2, 3, 4, 5]\nThe original list 2 is : [2, 3, 4, 5, 6]\nThe combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]" }, { "code": null, "e": 2257, "s": 2246, "text": "vinayedula" }, { "code": null, "e": 2278, "s": 2257, "text": "Python list-programs" }, { "code": null, "e": 2285, "s": 2278, "text": "Python" }, { "code": null, "e": 2301, "s": 2285, "text": "Python Programs" } ]
Python | Split list of strings into sublists based on length
09 Mar, 2022 Given a list of strings, write a Python program to split the list into sublists based on string length.Examples: Input : ['The', 'art', 'of', 'programming'] Output : [['of'], ['The', 'art'], ['programming']] Input : ['Welcome', 'to', 'geeksforgeeks'] Output : [['to'], ['Welcome'], ['geeksforgeeks']] Approach #1 : Pythonic naiveA naive approach for the above method uses a dictionary and a for loop to traverse the list. In each iteration, it checks whether the element length is already in the list or not. If not, it adds the element length and element as key:value pair, otherwise, the element is just added to the value sublist. Finally, we make a list of all the values of the dict and return it. Python3 # Python3 program to Divide list of strings# into sublists based on string length def divideList(lst): dct = {} for element in lst: if len(element) not in dct: dct[len(element)] = [element] elif len(element) in dct: dct[len(element)] += [element] res = [] for key in sorted(dct): res.append(dct[key]) return res # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst)) [['of'], ['The', 'art'], ['programming']] Approach #2 : defaultdict() from collections moduleThis method uses defaultdict and saves it in a variable ‘group_by_len’. Using a for loop, we save the length of string as key and the string with the key length as its value. Finally, we make a list of all the values of ‘group_by_len’ and return it. Python3 # Python3 program to Divide list of strings# into sublists based on string lengthfrom collections import defaultdict def divideList(lst): group_by_len = defaultdict(list) for ele in lst: group_by_len[len(ele)].append(ele) res = [] for key in sorted(group_by_len): res.append(group_by_len[key]) return res # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst)) [['of'], ['The', 'art'], ['programming']] Approach #3 : groupby() from itertools moduleThe most efficient and simplest method to solve the given problem is using groupby() from itertools module. This is a one-liner where we use two variables ‘l'(for length) and ‘g'(group of strings) to traverse through ‘lst’, grouped by length and finally return all groups packed within a list. Python3 # Python3 program to Divide list of strings# into sub lists based on string lengthfrom itertools import groupby def divideList(lst): res = dict((l, list(g)) for l, g in groupby(lst, key = len)) # Sorting dict by key res = sorted(res.items(), key = lambda kv:(kv[0], kv[1])) # Removing key from list of tuple return [el[1:] for el in (tuple(x) for x in res)] # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst)) [(['of'],), (['The', 'art'],), (['programming'],)] varshagumber28 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2022" }, { "code": null, "e": 143, "s": 28, "text": "Given a list of strings, write a Python program to split the list into sublists based on string length.Examples: " }, { "code": null, "e": 332, "s": 143, "text": "Input : ['The', 'art', 'of', 'programming']\nOutput : [['of'], ['The', 'art'], ['programming']]\n\nInput : ['Welcome', 'to', 'geeksforgeeks']\nOutput : [['to'], ['Welcome'], ['geeksforgeeks']]" }, { "code": null, "e": 735, "s": 332, "text": "Approach #1 : Pythonic naiveA naive approach for the above method uses a dictionary and a for loop to traverse the list. In each iteration, it checks whether the element length is already in the list or not. If not, it adds the element length and element as key:value pair, otherwise, the element is just added to the value sublist. Finally, we make a list of all the values of the dict and return it. " }, { "code": null, "e": 743, "s": 735, "text": "Python3" }, { "code": "# Python3 program to Divide list of strings# into sublists based on string length def divideList(lst): dct = {} for element in lst: if len(element) not in dct: dct[len(element)] = [element] elif len(element) in dct: dct[len(element)] += [element] res = [] for key in sorted(dct): res.append(dct[key]) return res # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst))", "e": 1205, "s": 743, "text": null }, { "code": null, "e": 1247, "s": 1205, "text": "[['of'], ['The', 'art'], ['programming']]" }, { "code": null, "e": 1554, "s": 1249, "text": " Approach #2 : defaultdict() from collections moduleThis method uses defaultdict and saves it in a variable ‘group_by_len’. Using a for loop, we save the length of string as key and the string with the key length as its value. Finally, we make a list of all the values of ‘group_by_len’ and return it. " }, { "code": null, "e": 1562, "s": 1554, "text": "Python3" }, { "code": "# Python3 program to Divide list of strings# into sublists based on string lengthfrom collections import defaultdict def divideList(lst): group_by_len = defaultdict(list) for ele in lst: group_by_len[len(ele)].append(ele) res = [] for key in sorted(group_by_len): res.append(group_by_len[key]) return res # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst))", "e": 1995, "s": 1562, "text": null }, { "code": null, "e": 2037, "s": 1995, "text": "[['of'], ['The', 'art'], ['programming']]" }, { "code": null, "e": 2382, "s": 2039, "text": " Approach #3 : groupby() from itertools moduleThe most efficient and simplest method to solve the given problem is using groupby() from itertools module. This is a one-liner where we use two variables ‘l'(for length) and ‘g'(group of strings) to traverse through ‘lst’, grouped by length and finally return all groups packed within a list. " }, { "code": null, "e": 2390, "s": 2382, "text": "Python3" }, { "code": "# Python3 program to Divide list of strings# into sub lists based on string lengthfrom itertools import groupby def divideList(lst): res = dict((l, list(g)) for l, g in groupby(lst, key = len)) # Sorting dict by key res = sorted(res.items(), key = lambda kv:(kv[0], kv[1])) # Removing key from list of tuple return [el[1:] for el in (tuple(x) for x in res)] # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst))", "e": 2846, "s": 2390, "text": null }, { "code": null, "e": 2897, "s": 2846, "text": "[(['of'],), (['The', 'art'],), (['programming'],)]" }, { "code": null, "e": 2914, "s": 2899, "text": "varshagumber28" }, { "code": null, "e": 2935, "s": 2914, "text": "Python list-programs" }, { "code": null, "e": 2942, "s": 2935, "text": "Python" }, { "code": null, "e": 2958, "s": 2942, "text": "Python Programs" }, { "code": null, "e": 3056, "s": 2958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3074, "s": 3056, "text": "Python Dictionary" }, { "code": null, "e": 3116, "s": 3074, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3138, "s": 3116, "text": "Enumerate() in Python" }, { "code": null, "e": 3164, "s": 3138, "text": "Python String | replace()" }, { "code": null, "e": 3196, "s": 3164, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3218, "s": 3196, "text": "Defaultdict in Python" }, { "code": null, "e": 3257, "s": 3218, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3295, "s": 3257, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3344, "s": 3295, "text": "Python | Convert string dictionary to dictionary" } ]
How .js file executed on the browser ?
29 Jul, 2021 In this article, we will learn how a .js file is executed on the browser by using following multiple approaches. Refer to Server side and Client side Programming, for in-depth knowledge about Javascript. How is .js is executed by the browser? Every Web browser comes with a JavaScript engine that provides a JavaScript runtime environment. For example, Google Chrome uses the V8 JavaScript engine, developed by Lars Bak. V8 is an open-source JavaScript engine developed for Google Chrome and Chromium web browsers by The Chromium Project. The browser’s built-in interpreter searches for <script> tag or .js file linked with HTML file while loading a web page, and then interpretation and execution starts. Approach 1: Using plain <script> tag: Syntax: <script> js code</script> Example: In this approach, we have written JavaScript code within the HTML file itself by using the <script> tag. This method is usually preferred when there is only a few lines of JS code are required in a Web project. The browser’s built-in interpreter searches for <script> tag in HTML file while loading a web page, and then interpretation and execution starts. HTML <!DOCTYPE html><html> <body> <script> document.querySelector("body").innerHTML = "<h2>Welcome to GeeksforGeeks</h2>"; document.querySelector("body") .style.color = "green"; </script></body> </html> Output: Approach 2: Using <script src=””> with “src” Parameter: Syntax: <script src="app.js"></script> Parameters: src: file path for the JavaScript file To know more about file paths refer Path Name in File Directory. Example: Below is the Javascript code from the previous example, we want to execute this code by following a different separate approach. We will create a separate file “app.js“, and put the code below in this “.js” file. app.js Now, we will use the below code to link the ‘.js‘ file with the HTML file. For this task, we will use a <script src=” “> tag where will we provide the file path of our .js file in the src parameter. In this way when our HTML file starts getting loaded in the browser then the browser’s built-in interpreter searches for <script> tag or .js file linked with HTML file, and then interpretation and execution starts. This approach is preferred when lots of lines of JavaScript code are required in a Web project, so we create a separate .js file and link that .js file to our HTML file using src parameter of <script> tag. HTML <!DOCTYPE html><html> <body> <!-- Importing app.js file--> <script src="app.js"></script></body> </html> Output: simranarora5sos JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2021" }, { "code": null, "e": 232, "s": 28, "text": "In this article, we will learn how a .js file is executed on the browser by using following multiple approaches. Refer to Server side and Client side Programming, for in-depth knowledge about Javascript." }, { "code": null, "e": 271, "s": 232, "text": "How is .js is executed by the browser?" }, { "code": null, "e": 567, "s": 271, "text": "Every Web browser comes with a JavaScript engine that provides a JavaScript runtime environment. For example, Google Chrome uses the V8 JavaScript engine, developed by Lars Bak. V8 is an open-source JavaScript engine developed for Google Chrome and Chromium web browsers by The Chromium Project." }, { "code": null, "e": 735, "s": 567, "text": "The browser’s built-in interpreter searches for <script> tag or .js file linked with HTML file while loading a web page, and then interpretation and execution starts." }, { "code": null, "e": 773, "s": 735, "text": "Approach 1: Using plain <script> tag:" }, { "code": null, "e": 782, "s": 773, "text": "Syntax: " }, { "code": null, "e": 808, "s": 782, "text": "<script> js code</script>" }, { "code": null, "e": 1174, "s": 808, "text": "Example: In this approach, we have written JavaScript code within the HTML file itself by using the <script> tag. This method is usually preferred when there is only a few lines of JS code are required in a Web project. The browser’s built-in interpreter searches for <script> tag in HTML file while loading a web page, and then interpretation and execution starts." }, { "code": null, "e": 1179, "s": 1174, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <script> document.querySelector(\"body\").innerHTML = \"<h2>Welcome to GeeksforGeeks</h2>\"; document.querySelector(\"body\") .style.color = \"green\"; </script></body> </html>", "e": 1432, "s": 1179, "text": null }, { "code": null, "e": 1440, "s": 1432, "text": "Output:" }, { "code": null, "e": 1496, "s": 1440, "text": "Approach 2: Using <script src=””> with “src” Parameter:" }, { "code": null, "e": 1505, "s": 1496, "text": "Syntax: " }, { "code": null, "e": 1536, "s": 1505, "text": "<script src=\"app.js\"></script>" }, { "code": null, "e": 1548, "s": 1536, "text": "Parameters:" }, { "code": null, "e": 1587, "s": 1548, "text": "src: file path for the JavaScript file" }, { "code": null, "e": 1652, "s": 1587, "text": "To know more about file paths refer Path Name in File Directory." }, { "code": null, "e": 1874, "s": 1652, "text": "Example: Below is the Javascript code from the previous example, we want to execute this code by following a different separate approach. We will create a separate file “app.js“, and put the code below in this “.js” file." }, { "code": null, "e": 1881, "s": 1874, "text": "app.js" }, { "code": null, "e": 2296, "s": 1881, "text": "Now, we will use the below code to link the ‘.js‘ file with the HTML file. For this task, we will use a <script src=” “> tag where will we provide the file path of our .js file in the src parameter. In this way when our HTML file starts getting loaded in the browser then the browser’s built-in interpreter searches for <script> tag or .js file linked with HTML file, and then interpretation and execution starts." }, { "code": null, "e": 2503, "s": 2296, "text": "This approach is preferred when lots of lines of JavaScript code are required in a Web project, so we create a separate .js file and link that .js file to our HTML file using src parameter of <script> tag. " }, { "code": null, "e": 2508, "s": 2503, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <!-- Importing app.js file--> <script src=\"app.js\"></script></body> </html>", "e": 2616, "s": 2508, "text": null }, { "code": null, "e": 2624, "s": 2616, "text": "Output:" }, { "code": null, "e": 2640, "s": 2624, "text": "simranarora5sos" }, { "code": null, "e": 2661, "s": 2640, "text": "JavaScript-Questions" }, { "code": null, "e": 2668, "s": 2661, "text": "Picked" }, { "code": null, "e": 2679, "s": 2668, "text": "JavaScript" }, { "code": null, "e": 2696, "s": 2679, "text": "Web Technologies" }, { "code": null, "e": 2794, "s": 2696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2855, "s": 2794, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2895, "s": 2855, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2937, "s": 2895, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2978, "s": 2937, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3000, "s": 2978, "text": "JavaScript | Promises" }, { "code": null, "e": 3033, "s": 3000, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3095, "s": 3033, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3156, "s": 3095, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3206, "s": 3156, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Set to Array in Java
Difficulty Level : Easy Given a set (HashSet or TreeSet) of strings in Java, convert it into an array of strings. Input : Set hash_Set = new HashSet(); hash_Set.add("Geeks"); hash_Set.add("For"); Output : String arr[] = {"Geeks", "for"} Method 1 (Simple)We simply create an empty array. We traverse the given set and one by one add elements to the array. // Java program to demonstrate conversion of // Set to array using simple traversalimport java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add("Geeks"); s.add("for"); int n = s.size(); String arr[] = new String[n]; int i = 0; for (String x : s) arr[i++] = x; System.out.println(Arrays.toString(arr)); }} [Geeks, for] Method 2 (Using System.arraycopy()) // Java program to demonstrate conversion of // Set to array using simple traversalimport java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add("Geeks"); s.add("for"); int n = s.size(); String arr[] = new String[n]; // Copying contents of s to arr[] System.arraycopy(s.toArray(), 0, arr, 0, n); System.out.println(Arrays.toString(arr)); }} [Geeks, for] Method 3 (Using toArray()) // Java program to demonstrate conversion of // Set to array using toArray()import java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add("Geeks"); s.add("for"); int n = s.size(); String arr[] = new String[n]; // Please refer below post for syntax // details of toArray() // https://www.geeksforgeeks.org/arraylist-array-conversion-java-toarray-methods/ arr = s.toArray(arr); System.out.println(Arrays.toString(arr)); }} [Geeks, for] Method 4 (Using Arrays.copyOf()) // Java program to demonstrate conversion of // Set to array using Arrays.copyOf()import java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add("Geeks"); s.add("for"); String[] arr = Arrays.copyOf(s.toArray(), s.size(), String[].class); System.out.println(Arrays.toString(arr)); }} [Geeks, for] Method 5 (Using stream in Java)We use stream in Java to convert given set to steam, then stream to array. This works only in Java 8 or versions after that. // Java program to demonstrate conversion of // Set to array using streamimport java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add("Geeks"); s.add("for"); int n = s.size(); String[] arr = s.stream().toArray(String[] ::new); System.out.println(Arrays.toString(arr)); }} [Geeks, for] Java-Array-Programs Java-Arrays Java-Collections java-hashset java-set Java-Set-Programs Java-Strings java-treeset Java Java-Strings Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Interfaces in Java ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Initialize an ArrayList in Java Initializing a List in Java
[ { "code": null, "e": 24, "s": 0, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 114, "s": 24, "text": "Given a set (HashSet or TreeSet) of strings in Java, convert it into an array of strings." }, { "code": null, "e": 254, "s": 114, "text": "Input : Set hash_Set = new HashSet();\n hash_Set.add(\"Geeks\");\n hash_Set.add(\"For\");\nOutput : String arr[] = {\"Geeks\", \"for\"}\n" }, { "code": null, "e": 372, "s": 254, "text": "Method 1 (Simple)We simply create an empty array. We traverse the given set and one by one add elements to the array." }, { "code": "// Java program to demonstrate conversion of // Set to array using simple traversalimport java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add(\"Geeks\"); s.add(\"for\"); int n = s.size(); String arr[] = new String[n]; int i = 0; for (String x : s) arr[i++] = x; System.out.println(Arrays.toString(arr)); }}", "e": 859, "s": 372, "text": null }, { "code": null, "e": 873, "s": 859, "text": "[Geeks, for]\n" }, { "code": null, "e": 909, "s": 873, "text": "Method 2 (Using System.arraycopy())" }, { "code": "// Java program to demonstrate conversion of // Set to array using simple traversalimport java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add(\"Geeks\"); s.add(\"for\"); int n = s.size(); String arr[] = new String[n]; // Copying contents of s to arr[] System.arraycopy(s.toArray(), 0, arr, 0, n); System.out.println(Arrays.toString(arr)); }}", "e": 1420, "s": 909, "text": null }, { "code": null, "e": 1434, "s": 1420, "text": "[Geeks, for]\n" }, { "code": null, "e": 1461, "s": 1434, "text": "Method 3 (Using toArray())" }, { "code": "// Java program to demonstrate conversion of // Set to array using toArray()import java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add(\"Geeks\"); s.add(\"for\"); int n = s.size(); String arr[] = new String[n]; // Please refer below post for syntax // details of toArray() // https://www.geeksforgeeks.org/arraylist-array-conversion-java-toarray-methods/ arr = s.toArray(arr); System.out.println(Arrays.toString(arr)); }}", "e": 2066, "s": 1461, "text": null }, { "code": null, "e": 2080, "s": 2066, "text": "[Geeks, for]\n" }, { "code": null, "e": 2113, "s": 2080, "text": "Method 4 (Using Arrays.copyOf())" }, { "code": "// Java program to demonstrate conversion of // Set to array using Arrays.copyOf()import java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add(\"Geeks\"); s.add(\"for\"); String[] arr = Arrays.copyOf(s.toArray(), s.size(), String[].class); System.out.println(Arrays.toString(arr)); }}", "e": 2552, "s": 2113, "text": null }, { "code": null, "e": 2566, "s": 2552, "text": "[Geeks, for]\n" }, { "code": null, "e": 2722, "s": 2566, "text": "Method 5 (Using stream in Java)We use stream in Java to convert given set to steam, then stream to array. This works only in Java 8 or versions after that." }, { "code": "// Java program to demonstrate conversion of // Set to array using streamimport java.util.*; class Test { public static void main(String[] args) { // Creating a hash set of strings Set<String> s = new HashSet<String>(); s.add(\"Geeks\"); s.add(\"for\"); int n = s.size(); String[] arr = s.stream().toArray(String[] ::new); System.out.println(Arrays.toString(arr)); }}", "e": 3149, "s": 2722, "text": null }, { "code": null, "e": 3163, "s": 3149, "text": "[Geeks, for]\n" }, { "code": null, "e": 3183, "s": 3163, "text": "Java-Array-Programs" }, { "code": null, "e": 3195, "s": 3183, "text": "Java-Arrays" }, { "code": null, "e": 3212, "s": 3195, "text": "Java-Collections" }, { "code": null, "e": 3225, "s": 3212, "text": "java-hashset" }, { "code": null, "e": 3234, "s": 3225, "text": "java-set" }, { "code": null, "e": 3252, "s": 3234, "text": "Java-Set-Programs" }, { "code": null, "e": 3265, "s": 3252, "text": "Java-Strings" }, { "code": null, "e": 3278, "s": 3265, "text": "java-treeset" }, { "code": null, "e": 3283, "s": 3278, "text": "Java" }, { "code": null, "e": 3296, "s": 3283, "text": "Java-Strings" }, { "code": null, "e": 3301, "s": 3296, "text": "Java" }, { "code": null, "e": 3318, "s": 3301, "text": "Java-Collections" }, { "code": null, "e": 3416, "s": 3318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3467, "s": 3416, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3486, "s": 3467, "text": "Interfaces in Java" }, { "code": null, "e": 3504, "s": 3486, "text": "ArrayList in Java" }, { "code": null, "e": 3524, "s": 3504, "text": "Collections in Java" }, { "code": null, "e": 3539, "s": 3524, "text": "Stream In Java" }, { "code": null, "e": 3571, "s": 3539, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3595, "s": 3571, "text": "Singleton Class in Java" }, { "code": null, "e": 3615, "s": 3595, "text": "Stack Class in Java" }, { "code": null, "e": 3647, "s": 3615, "text": "Initialize an ArrayList in Java" } ]
React Native Configuring Header Bar
14 Jul, 2021 To configure the header bar of a React Native application, the navigation options are used. The navigation options are a static property of the screen component which is either an object or a function. Header Bar Props headerTitle: It is used to set the title of the active screen. headerStyle: It is used to add style to the header bar. backgroundColor: It is used to change the background color of the header bar. headerTintColor: It is used to change the color to the header title. headerTitleStyle: It is used to add customized style to the header title. fontWeight: It is used to set the font style of the header title. headerRight: It is used to add items on the right side of the header bar. headerLeft: It is used to add items on the left side of the header bar. Implementation: Now let’s see how to configure the Header Bar: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init header-bar Step 2: Now create a project by the following command. expo init header-bar Step 3: Now go into your project folder i.e. header-barcd header-bar Step 3: Now go into your project folder i.e. header-bar cd header-bar Step 4: Install the required packages using the following command:npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons Step 4: Install the required packages using the following command: npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons Project Structure: The project directory should look like the following: Example:In our example, we will look at how to style the header bar, how to add header buttons/icons to it, and learn how to dynamically send data from one screen and display it as the header title on another screen. App.js import React from "react";import { createAppContainer } from "react-navigation";import { createStackNavigator } from "react-navigation-stack"; import HomeScreen from "./screens/HomeScreen";import UserScreen from "./screens/UserScreen";import SettingScreen from "./screens/SettingScreen"; const AppNavigator = createStackNavigator( { Home: HomeScreen, User: UserScreen, Setting: SettingScreen, }, { defaultNavigationOptions: { headerStyle: { backgroundColor: "#006600", }, headerTitleStyle: { fontWeight: "bold", color: "#FFF", }, headerTintColor: "#FFF", }, }, { initialRouteName: "Home", }); const Navigator = createAppContainer(AppNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );} HomeScreen.js: Notice the navigation options. Here, we configure a header button component inside our Header bar, which takes us to the Settings screen. Also, notice that we send the user input when we click on the “Go to user screen” button. HomeScreen.js import React, { useState } from "react";import { Text, View, TextInput, Button } from "react-native";import { Ionicons } from "@expo/vector-icons";import { Item, HeaderButton, HeaderButtons,} from "react-navigation-header-buttons"; const Home = (props) => { const [input, setInput] = useState(""); return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Home Screen!</Text> <Ionicons name="ios-home" size={80} color="#006600" /> <TextInput placeholder="Enter your name" value={input} onChangeText={(value) => setInput(value)} /> <Button title="Go to User Screen" color="#006600" onPress={() => props.navigation.navigate("User", { username: input })} /> </View> );}; const HeaderButtonComponent = (props) => ( <HeaderButton IconComponent={Ionicons} iconSize={23} color="#FFF" {...props} />); Home.navigationOptions = (navData) => { return { headerTitle: "Home", headerRight: () => ( <HeaderButtons HeaderButtonComponent={HeaderButtonComponent}> <Item title="Setting" iconName="ios-settings-outline" onPress={() => navData.navigation.navigate("Setting")} /> </HeaderButtons> ), };}; export default Home; UserScreen.js: Here we receive the user input which we passed through the home screen and set it as the title in out header bar. UserScreen.js import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const User = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}> User Screen! </Text> <Ionicons name="ios-person-circle-outline" size={80} color="#006600" /> </View> );}; User.navigationOptions = (navData) => { return { headerTitle: navData.navigation.getParam("username"), };}; export default User; SettingScreen.js import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Settings = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name="ios-settings-outline" size={80} color="#006600" /> </View> );}; export default Settings; Run the Application: Start the server by using the following command. expo start Output: Notice when you tap on a single tab, there is a slight animation. This is automatically provided by the Material Bottom Tab Navigator. Reference: https://reactnavigation.org/docs/headers/ Picked React-Native Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? How to set input type date in dd-mm-yyyy format using HTML ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2021" }, { "code": null, "e": 230, "s": 28, "text": "To configure the header bar of a React Native application, the navigation options are used. The navigation options are a static property of the screen component which is either an object or a function." }, { "code": null, "e": 247, "s": 230, "text": "Header Bar Props" }, { "code": null, "e": 310, "s": 247, "text": "headerTitle: It is used to set the title of the active screen." }, { "code": null, "e": 366, "s": 310, "text": "headerStyle: It is used to add style to the header bar." }, { "code": null, "e": 445, "s": 366, "text": "backgroundColor: It is used to change the background color of the header bar." }, { "code": null, "e": 514, "s": 445, "text": "headerTintColor: It is used to change the color to the header title." }, { "code": null, "e": 588, "s": 514, "text": "headerTitleStyle: It is used to add customized style to the header title." }, { "code": null, "e": 654, "s": 588, "text": "fontWeight: It is used to set the font style of the header title." }, { "code": null, "e": 728, "s": 654, "text": "headerRight: It is used to add items on the right side of the header bar." }, { "code": null, "e": 800, "s": 728, "text": "headerLeft: It is used to add items on the left side of the header bar." }, { "code": null, "e": 863, "s": 800, "text": "Implementation: Now let’s see how to configure the Header Bar:" }, { "code": null, "e": 960, "s": 863, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 1034, "s": 960, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 1058, "s": 1034, "text": "npm install -g expo-cli" }, { "code": null, "e": 1135, "s": 1060, "text": "Step 2: Now create a project by the following command.expo init header-bar" }, { "code": null, "e": 1190, "s": 1135, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 1211, "s": 1190, "text": "expo init header-bar" }, { "code": null, "e": 1280, "s": 1211, "text": "Step 3: Now go into your project folder i.e. header-barcd header-bar" }, { "code": null, "e": 1336, "s": 1280, "text": "Step 3: Now go into your project folder i.e. header-bar" }, { "code": null, "e": 1350, "s": 1336, "text": "cd header-bar" }, { "code": null, "e": 1517, "s": 1350, "text": "Step 4: Install the required packages using the following command:npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons" }, { "code": null, "e": 1584, "s": 1517, "text": "Step 4: Install the required packages using the following command:" }, { "code": null, "e": 1685, "s": 1584, "text": "npm install –save react-navigation-material-bottom-tabs react-native-paper react-native-vector-icons" }, { "code": null, "e": 1758, "s": 1685, "text": "Project Structure: The project directory should look like the following:" }, { "code": null, "e": 1977, "s": 1760, "text": "Example:In our example, we will look at how to style the header bar, how to add header buttons/icons to it, and learn how to dynamically send data from one screen and display it as the header title on another screen." }, { "code": null, "e": 1984, "s": 1977, "text": "App.js" }, { "code": "import React from \"react\";import { createAppContainer } from \"react-navigation\";import { createStackNavigator } from \"react-navigation-stack\"; import HomeScreen from \"./screens/HomeScreen\";import UserScreen from \"./screens/UserScreen\";import SettingScreen from \"./screens/SettingScreen\"; const AppNavigator = createStackNavigator( { Home: HomeScreen, User: UserScreen, Setting: SettingScreen, }, { defaultNavigationOptions: { headerStyle: { backgroundColor: \"#006600\", }, headerTitleStyle: { fontWeight: \"bold\", color: \"#FFF\", }, headerTintColor: \"#FFF\", }, }, { initialRouteName: \"Home\", }); const Navigator = createAppContainer(AppNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );}", "e": 2801, "s": 1984, "text": null }, { "code": null, "e": 3044, "s": 2801, "text": "HomeScreen.js: Notice the navigation options. Here, we configure a header button component inside our Header bar, which takes us to the Settings screen. Also, notice that we send the user input when we click on the “Go to user screen” button." }, { "code": null, "e": 3058, "s": 3044, "text": "HomeScreen.js" }, { "code": "import React, { useState } from \"react\";import { Text, View, TextInput, Button } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\";import { Item, HeaderButton, HeaderButtons,} from \"react-navigation-header-buttons\"; const Home = (props) => { const [input, setInput] = useState(\"\"); return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Home Screen!</Text> <Ionicons name=\"ios-home\" size={80} color=\"#006600\" /> <TextInput placeholder=\"Enter your name\" value={input} onChangeText={(value) => setInput(value)} /> <Button title=\"Go to User Screen\" color=\"#006600\" onPress={() => props.navigation.navigate(\"User\", { username: input })} /> </View> );}; const HeaderButtonComponent = (props) => ( <HeaderButton IconComponent={Ionicons} iconSize={23} color=\"#FFF\" {...props} />); Home.navigationOptions = (navData) => { return { headerTitle: \"Home\", headerRight: () => ( <HeaderButtons HeaderButtonComponent={HeaderButtonComponent}> <Item title=\"Setting\" iconName=\"ios-settings-outline\" onPress={() => navData.navigation.navigate(\"Setting\")} /> </HeaderButtons> ), };}; export default Home;", "e": 4401, "s": 3058, "text": null }, { "code": null, "e": 4530, "s": 4401, "text": "UserScreen.js: Here we receive the user input which we passed through the home screen and set it as the title in out header bar." }, { "code": null, "e": 4544, "s": 4530, "text": "UserScreen.js" }, { "code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const User = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}> User Screen! </Text> <Ionicons name=\"ios-person-circle-outline\" size={80} color=\"#006600\" /> </View> );}; User.navigationOptions = (navData) => { return { headerTitle: navData.navigation.getParam(\"username\"), };}; export default User;", "e": 5121, "s": 4544, "text": null }, { "code": null, "e": 5138, "s": 5121, "text": "SettingScreen.js" }, { "code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Settings = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name=\"ios-settings-outline\" size={80} color=\"#006600\" /> </View> );}; export default Settings;", "e": 5560, "s": 5138, "text": null }, { "code": null, "e": 5630, "s": 5560, "text": "Run the Application: Start the server by using the following command." }, { "code": null, "e": 5641, "s": 5630, "text": "expo start" }, { "code": null, "e": 5784, "s": 5641, "text": "Output: Notice when you tap on a single tab, there is a slight animation. This is automatically provided by the Material Bottom Tab Navigator." }, { "code": null, "e": 5837, "s": 5784, "text": "Reference: https://reactnavigation.org/docs/headers/" }, { "code": null, "e": 5844, "s": 5837, "text": "Picked" }, { "code": null, "e": 5857, "s": 5844, "text": "React-Native" }, { "code": null, "e": 5874, "s": 5857, "text": "Web Technologies" }, { "code": null, "e": 5972, "s": 5874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6033, "s": 5972, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6076, "s": 6033, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 6148, "s": 6076, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6188, "s": 6148, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6212, "s": 6188, "text": "REST API (Introduction)" }, { "code": null, "e": 6245, "s": 6212, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 6305, "s": 6245, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 6363, "s": 6305, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 6424, "s": 6363, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]