title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Convert String float to float list in Python
|
20 Jul, 2021
Sometimes, while working with data, we could be dealing with numbers, that are in decimal and not integers. This is general case in data science domain. Let’s discuss how to resolve a problem in which we may have a comma separated float numbers and we need to convert to float list.
Method #1 : Using list comprehension + split() + float() The combination of the above methods can be used to perform this task. In this, we convert the String to string list using split and then convert the string to float using float().
Python3
# Python3 code to demonstrate working of# Convert String float to float list# using list comprehension + split() + float() # initializing stringtest_str = "3.44, 7.8, 9.12, 100.2, 6.50" # printing original stringprint("The original string is : " + test_str) # Convert String float to float list# using list comprehension + split() + float()res = [float(idx) for idx in test_str.split(', ')] # printing resultprint("The float list is : " + str(res))
The original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]
Method #2 : Using map() + split() + float() The combination of above functions can also be used to solve this problem. In this, we perform the task of extending logic to the entire list using map(), rest all the functionalities are performed as above method.
Python3
# Python3 code to demonstrate working of# Convert String float to float list# using map() + split() + float() # initializing stringtest_str = "3.44, 7.8, 9.12, 100.2, 6.50" # printing original stringprint("The original string is : " + test_str) # Convert String float to float list# using map() + split() + float()res = list(map(float, test_str.split(', '))) # printing resultprint("The float list is : " + str(res))
The original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]
anikakapoor
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
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 311,
"s": 28,
"text": "Sometimes, while working with data, we could be dealing with numbers, that are in decimal and not integers. This is general case in data science domain. Let’s discuss how to resolve a problem in which we may have a comma separated float numbers and we need to convert to float list."
},
{
"code": null,
"e": 549,
"s": 311,
"text": "Method #1 : Using list comprehension + split() + float() The combination of the above methods can be used to perform this task. In this, we convert the String to string list using split and then convert the string to float using float()."
},
{
"code": null,
"e": 557,
"s": 549,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert String float to float list# using list comprehension + split() + float() # initializing stringtest_str = \"3.44, 7.8, 9.12, 100.2, 6.50\" # printing original stringprint(\"The original string is : \" + test_str) # Convert String float to float list# using list comprehension + split() + float()res = [float(idx) for idx in test_str.split(', ')] # printing resultprint(\"The float list is : \" + str(res))",
"e": 1006,
"s": 557,
"text": null
},
{
"code": null,
"e": 1110,
"s": 1006,
"text": "The original string is : 3.44, 7.8, 9.12, 100.2, 6.50\nThe float list is : [3.44, 7.8, 9.12, 100.2, 6.5]"
},
{
"code": null,
"e": 1371,
"s": 1112,
"text": "Method #2 : Using map() + split() + float() The combination of above functions can also be used to solve this problem. In this, we perform the task of extending logic to the entire list using map(), rest all the functionalities are performed as above method."
},
{
"code": null,
"e": 1379,
"s": 1371,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert String float to float list# using map() + split() + float() # initializing stringtest_str = \"3.44, 7.8, 9.12, 100.2, 6.50\" # printing original stringprint(\"The original string is : \" + test_str) # Convert String float to float list# using map() + split() + float()res = list(map(float, test_str.split(', '))) # printing resultprint(\"The float list is : \" + str(res))",
"e": 1796,
"s": 1379,
"text": null
},
{
"code": null,
"e": 1900,
"s": 1796,
"text": "The original string is : 3.44, 7.8, 9.12, 100.2, 6.50\nThe float list is : [3.44, 7.8, 9.12, 100.2, 6.5]"
},
{
"code": null,
"e": 1914,
"s": 1902,
"text": "anikakapoor"
},
{
"code": null,
"e": 1935,
"s": 1914,
"text": "Python list-programs"
},
{
"code": null,
"e": 1942,
"s": 1935,
"text": "Python"
},
{
"code": null,
"e": 1958,
"s": 1942,
"text": "Python Programs"
},
{
"code": null,
"e": 2056,
"s": 1958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2074,
"s": 2056,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2116,
"s": 2074,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2138,
"s": 2116,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2173,
"s": 2138,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2199,
"s": 2173,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2242,
"s": 2199,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2264,
"s": 2242,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2303,
"s": 2264,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2341,
"s": 2303,
"text": "Python | Convert a list to dictionary"
}
] |
Maximum and Minimum Product Subsets
|
05 Jul, 2022
Given a set, we need to find maximum and minimum possible product among all subsets of the set.
Examples:
Input : arr[] = {4, -2, 5};
Output: Maximum product = 20
Minimum product = -40
Maximum product is obtained by multiplying
4 5
Minimum product is obtained by multiplying
4, -2, 5
Input : arr[] = {-4, -2, 3, 7, 5, 0, 1};
Output: Maximum product = 840
Minimum product = -420
Maximum product is obtained by multiplying
-4, -2, 3, 7, 5
Minimum product is obtained by multiplying
-4, 3, 7, 5
As array can have negative value, zero and positive value, this problem can have lot of edge cases, if not attacked properly. Below given solution maintains maximum product and minimum product at current index and previous index and at any instant current product takes value from previous max or previous min multiplied with current element, depending on the sign of current element. For example, if we are finding maximum product then current maximum will be previous max times current value if current element is positive otherwise previous min times current value if current element is negative. Same procedure is applied for finding minimum product also.
Please see below simple code to understand.
C++
Java
Python3
C#
Javascript
// C++ program to find maximum and minimum// product from an array#include <bits/stdc++.h>using namespace std; // method returns maximum and minimum obtainable// product of array arrpair<int, int> getMaxandMinProduct(int arr[], int n){ // Initialize all products with arr[0] int curMaxProduct = arr[0]; int curMinProduct = arr[0]; int prevMaxProduct = arr[0]; int prevMinProduct = arr[0]; int maxProduct = arr[0]; int minProduct = arr[0]; // Process all elements after arr[0] for (int i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = max(prevMaxProduct * arr[i], max(prevMinProduct * arr[i], arr[i])); curMaxProduct = max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = min(prevMaxProduct * arr[i], min(prevMinProduct * arr[i], arr[i])); curMinProduct = min(curMinProduct, prevMinProduct); maxProduct = max(maxProduct, curMaxProduct); minProduct = min(minProduct, curMinProduct); // copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return make_pair(minProduct, maxProduct);} // driver code to test above methodsint main(){ int arr[] = {-4, -2, 3, 7, 5, 0, 1}; int n = sizeof(arr) / sizeof(int); pair<int, int> product = getMaxandMinProduct(arr, n); printf("Minimum product is %d and " "Maximum product is %dn", product.first, product.second); return 0;}
// Java program to find maximum and minimum// product from an arrayclass GFG{static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // method returns maximum and minimum obtainable// product of array arrstatic pair getMaxandMinProduct(int arr[], int n){ // Initialize all products with arr[0] int curMaxProduct = arr[0]; int curMinProduct = arr[0]; int prevMaxProduct = arr[0]; int prevMinProduct = arr[0]; int maxProduct = arr[0]; int minProduct = arr[0]; // Process all elements after arr[0] for (int i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = Math.max(prevMaxProduct * arr[i], Math.max(prevMinProduct * arr[i], arr[i])); curMaxProduct = Math.max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = Math.min(prevMaxProduct * arr[i], Math.min(prevMinProduct * arr[i], arr[i])); curMinProduct = Math.min(curMinProduct, prevMinProduct); maxProduct = Math.max(maxProduct, curMaxProduct); minProduct = Math.min(minProduct, curMinProduct); // copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return new pair(minProduct, maxProduct);} // Driver Codepublic static void main(String[] args){ int arr[] = {-4, -2, 3, 7, 5, 0, 1}; int n = arr.length; pair product = getMaxandMinProduct(arr, n); System.out.printf("Minimum product is %d and " + "Maximum product is %d", product.first, product.second); }} // This code is contributed by Rajput-Ji
# Python3 program to find maximum and# minimum product from an array # method returns maximum and minimum# obtainable product of array arrdef getMaxandMinProduct(arr, n): # Initialize all products with arr[0] curMaxProduct = arr[0] curMinProduct = arr[0] prevMaxProduct = arr[0] prevMinProduct = arr[0] maxProduct = arr[0] minProduct = arr[0] # Process all elements after arr[0] for i in range(1, n): # Current maximum product is maximum of following # 1) prevMax * curelement (when curelement is +ve) # 2) prevMin * curelement (when curelement is -ve) # 3) Element itself # 4) Previous max product curMaxProduct = max(prevMaxProduct * arr[i], max(prevMinProduct * arr[i], arr[i])) curMaxProduct = max(curMaxProduct, prevMaxProduct) # Current min product computation is Similar to # that of current max product curMinProduct = min(prevMaxProduct * arr[i], min(prevMinProduct * arr[i], arr[i])) curMinProduct = min(curMinProduct, prevMinProduct) maxProduct = max(maxProduct, curMaxProduct) minProduct = min(minProduct, curMinProduct) # copy current values to previous values prevMaxProduct = curMaxProduct prevMinProduct = curMinProduct return (minProduct, maxProduct) # Driver Codeif __name__ == "__main__": arr = [-4, -2, 3, 7, 5, 0, 1] n = len(arr) product = getMaxandMinProduct(arr, n) print("Minimum product is", product[0], "and", "Maximum product is", product[1]) # This code is contributed by# sanjeev2552
// C# program to find maximum and minimum// product from an arrayusing System; class GFG{public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // method returns maximum and minimum// obtainable product of array arrstatic pair getMaxandMinProduct(int []arr, int n){ // Initialize all products with arr[0] int curMaxProduct = arr[0]; int curMinProduct = arr[0]; int prevMaxProduct = arr[0]; int prevMinProduct = arr[0]; int maxProduct = arr[0]; int minProduct = arr[0]; // Process all elements after arr[0] for (int i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = Math.Max(prevMaxProduct * arr[i], Math.Max(prevMinProduct * arr[i], arr[i])); curMaxProduct = Math.Max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = Math.Min(prevMaxProduct * arr[i], Math.Min(prevMinProduct * arr[i], arr[i])); curMinProduct = Math.Min(curMinProduct, prevMinProduct); maxProduct = Math.Max(maxProduct, curMaxProduct); minProduct = Math.Min(minProduct, curMinProduct); // copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return new pair(minProduct, maxProduct);} // Driver Codepublic static void Main(String[] args){ int []arr = {-4, -2, 3, 7, 5, 0, 1}; int n = arr.Length; pair product = getMaxandMinProduct(arr, n); Console.Write("Minimum product is {0} and " + "Maximum product is {1}", product.first, product.second);}} // This code is contributed by Princi Singh
<script> // Javascript program to find maximum and minimum// product from an array // method returns maximum and minimum obtainable// product of array arrfunction getMaxandMinProduct(arr, n){ // Initialize all products with arr[0] let curMaxProduct = arr[0]; let curMinProduct = arr[0]; let prevMaxProduct = arr[0]; let prevMinProduct = arr[0]; let maxProduct = arr[0]; let minProduct = arr[0]; // Process all elements after arr[0] for(let i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = Math.max(prevMaxProduct * arr[i], Math.max(prevMinProduct * arr[i], arr[i])); curMaxProduct = Math.max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = Math.min(prevMaxProduct * arr[i], Math.min(prevMinProduct * arr[i], arr[i])); curMinProduct = Math.min(curMinProduct, prevMinProduct); maxProduct = Math.max(maxProduct, curMaxProduct); minProduct = Math.min(minProduct, curMinProduct); // Copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return [minProduct, maxProduct];} // Driver codelet arr = [ -4, -2, 3, 7, 5, 0, 1 ];let n = arr.length;let product = getMaxandMinProduct(arr, n); document.write("Minimum product is " + product[0] + " and Maximum product is " + product[1]); // This code is contributed by _saurabh_jaiswal </script>
Minimum product is -420 and Maximum product is 840n
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Rajput-Ji
princi singh
sanjeev2552
_saurabh_jaiswal
sumitgumber28
hardikkoriintern
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Next Greater Element
Move all negative numbers to beginning and positive to end with constant extra space
What is Data Structure: Types, Classifications and Applications
Count pairs with given sum
Find subarray with given sum | Set 1 (Nonnegative Numbers)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 151,
"s": 54,
"text": "Given a set, we need to find maximum and minimum possible product among all subsets of the set. "
},
{
"code": null,
"e": 162,
"s": 151,
"text": "Examples: "
},
{
"code": null,
"e": 570,
"s": 162,
"text": "Input : arr[] = {4, -2, 5};\nOutput: Maximum product = 20 \n Minimum product = -40\nMaximum product is obtained by multiplying\n4 5\nMinimum product is obtained by multiplying \n4, -2, 5\n\nInput : arr[] = {-4, -2, 3, 7, 5, 0, 1};\nOutput: Maximum product = 840 \n Minimum product = -420\nMaximum product is obtained by multiplying\n-4, -2, 3, 7, 5\nMinimum product is obtained by multiplying \n-4, 3, 7, 5 "
},
{
"code": null,
"e": 1231,
"s": 570,
"text": "As array can have negative value, zero and positive value, this problem can have lot of edge cases, if not attacked properly. Below given solution maintains maximum product and minimum product at current index and previous index and at any instant current product takes value from previous max or previous min multiplied with current element, depending on the sign of current element. For example, if we are finding maximum product then current maximum will be previous max times current value if current element is positive otherwise previous min times current value if current element is negative. Same procedure is applied for finding minimum product also. "
},
{
"code": null,
"e": 1277,
"s": 1231,
"text": "Please see below simple code to understand. "
},
{
"code": null,
"e": 1281,
"s": 1277,
"text": "C++"
},
{
"code": null,
"e": 1286,
"s": 1281,
"text": "Java"
},
{
"code": null,
"e": 1294,
"s": 1286,
"text": "Python3"
},
{
"code": null,
"e": 1297,
"s": 1294,
"text": "C#"
},
{
"code": null,
"e": 1308,
"s": 1297,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum and minimum// product from an array#include <bits/stdc++.h>using namespace std; // method returns maximum and minimum obtainable// product of array arrpair<int, int> getMaxandMinProduct(int arr[], int n){ // Initialize all products with arr[0] int curMaxProduct = arr[0]; int curMinProduct = arr[0]; int prevMaxProduct = arr[0]; int prevMinProduct = arr[0]; int maxProduct = arr[0]; int minProduct = arr[0]; // Process all elements after arr[0] for (int i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = max(prevMaxProduct * arr[i], max(prevMinProduct * arr[i], arr[i])); curMaxProduct = max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = min(prevMaxProduct * arr[i], min(prevMinProduct * arr[i], arr[i])); curMinProduct = min(curMinProduct, prevMinProduct); maxProduct = max(maxProduct, curMaxProduct); minProduct = min(minProduct, curMinProduct); // copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return make_pair(minProduct, maxProduct);} // driver code to test above methodsint main(){ int arr[] = {-4, -2, 3, 7, 5, 0, 1}; int n = sizeof(arr) / sizeof(int); pair<int, int> product = getMaxandMinProduct(arr, n); printf(\"Minimum product is %d and \" \"Maximum product is %dn\", product.first, product.second); return 0;}",
"e": 3210,
"s": 1308,
"text": null
},
{
"code": "// Java program to find maximum and minimum// product from an arrayclass GFG{static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // method returns maximum and minimum obtainable// product of array arrstatic pair getMaxandMinProduct(int arr[], int n){ // Initialize all products with arr[0] int curMaxProduct = arr[0]; int curMinProduct = arr[0]; int prevMaxProduct = arr[0]; int prevMinProduct = arr[0]; int maxProduct = arr[0]; int minProduct = arr[0]; // Process all elements after arr[0] for (int i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = Math.max(prevMaxProduct * arr[i], Math.max(prevMinProduct * arr[i], arr[i])); curMaxProduct = Math.max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = Math.min(prevMaxProduct * arr[i], Math.min(prevMinProduct * arr[i], arr[i])); curMinProduct = Math.min(curMinProduct, prevMinProduct); maxProduct = Math.max(maxProduct, curMaxProduct); minProduct = Math.min(minProduct, curMinProduct); // copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return new pair(minProduct, maxProduct);} // Driver Codepublic static void main(String[] args){ int arr[] = {-4, -2, 3, 7, 5, 0, 1}; int n = arr.length; pair product = getMaxandMinProduct(arr, n); System.out.printf(\"Minimum product is %d and \" + \"Maximum product is %d\", product.first, product.second); }} // This code is contributed by Rajput-Ji",
"e": 5357,
"s": 3210,
"text": null
},
{
"code": "# Python3 program to find maximum and# minimum product from an array # method returns maximum and minimum# obtainable product of array arrdef getMaxandMinProduct(arr, n): # Initialize all products with arr[0] curMaxProduct = arr[0] curMinProduct = arr[0] prevMaxProduct = arr[0] prevMinProduct = arr[0] maxProduct = arr[0] minProduct = arr[0] # Process all elements after arr[0] for i in range(1, n): # Current maximum product is maximum of following # 1) prevMax * curelement (when curelement is +ve) # 2) prevMin * curelement (when curelement is -ve) # 3) Element itself # 4) Previous max product curMaxProduct = max(prevMaxProduct * arr[i], max(prevMinProduct * arr[i], arr[i])) curMaxProduct = max(curMaxProduct, prevMaxProduct) # Current min product computation is Similar to # that of current max product curMinProduct = min(prevMaxProduct * arr[i], min(prevMinProduct * arr[i], arr[i])) curMinProduct = min(curMinProduct, prevMinProduct) maxProduct = max(maxProduct, curMaxProduct) minProduct = min(minProduct, curMinProduct) # copy current values to previous values prevMaxProduct = curMaxProduct prevMinProduct = curMinProduct return (minProduct, maxProduct) # Driver Codeif __name__ == \"__main__\": arr = [-4, -2, 3, 7, 5, 0, 1] n = len(arr) product = getMaxandMinProduct(arr, n) print(\"Minimum product is\", product[0], \"and\", \"Maximum product is\", product[1]) # This code is contributed by# sanjeev2552",
"e": 6985,
"s": 5357,
"text": null
},
{
"code": "// C# program to find maximum and minimum// product from an arrayusing System; class GFG{public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // method returns maximum and minimum// obtainable product of array arrstatic pair getMaxandMinProduct(int []arr, int n){ // Initialize all products with arr[0] int curMaxProduct = arr[0]; int curMinProduct = arr[0]; int prevMaxProduct = arr[0]; int prevMinProduct = arr[0]; int maxProduct = arr[0]; int minProduct = arr[0]; // Process all elements after arr[0] for (int i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = Math.Max(prevMaxProduct * arr[i], Math.Max(prevMinProduct * arr[i], arr[i])); curMaxProduct = Math.Max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = Math.Min(prevMaxProduct * arr[i], Math.Min(prevMinProduct * arr[i], arr[i])); curMinProduct = Math.Min(curMinProduct, prevMinProduct); maxProduct = Math.Max(maxProduct, curMaxProduct); minProduct = Math.Min(minProduct, curMinProduct); // copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return new pair(minProduct, maxProduct);} // Driver Codepublic static void Main(String[] args){ int []arr = {-4, -2, 3, 7, 5, 0, 1}; int n = arr.Length; pair product = getMaxandMinProduct(arr, n); Console.Write(\"Minimum product is {0} and \" + \"Maximum product is {1}\", product.first, product.second);}} // This code is contributed by Princi Singh",
"e": 9203,
"s": 6985,
"text": null
},
{
"code": "<script> // Javascript program to find maximum and minimum// product from an array // method returns maximum and minimum obtainable// product of array arrfunction getMaxandMinProduct(arr, n){ // Initialize all products with arr[0] let curMaxProduct = arr[0]; let curMinProduct = arr[0]; let prevMaxProduct = arr[0]; let prevMinProduct = arr[0]; let maxProduct = arr[0]; let minProduct = arr[0]; // Process all elements after arr[0] for(let i = 1; i < n; ++i) { /* Current maximum product is maximum of following 1) prevMax * curelement (when curelement is +ve) 2) prevMin * curelement (when curelement is -ve) 3) Element itself 4) Previous max product */ curMaxProduct = Math.max(prevMaxProduct * arr[i], Math.max(prevMinProduct * arr[i], arr[i])); curMaxProduct = Math.max(curMaxProduct, prevMaxProduct); /* Current min product computation is Similar to that of current max product */ curMinProduct = Math.min(prevMaxProduct * arr[i], Math.min(prevMinProduct * arr[i], arr[i])); curMinProduct = Math.min(curMinProduct, prevMinProduct); maxProduct = Math.max(maxProduct, curMaxProduct); minProduct = Math.min(minProduct, curMinProduct); // Copy current values to previous values prevMaxProduct = curMaxProduct; prevMinProduct = curMinProduct; } return [minProduct, maxProduct];} // Driver codelet arr = [ -4, -2, 3, 7, 5, 0, 1 ];let n = arr.length;let product = getMaxandMinProduct(arr, n); document.write(\"Minimum product is \" + product[0] + \" and Maximum product is \" + product[1]); // This code is contributed by _saurabh_jaiswal </script>",
"e": 11168,
"s": 9203,
"text": null
},
{
"code": null,
"e": 11220,
"s": 11168,
"text": "Minimum product is -420 and Maximum product is 840n"
},
{
"code": null,
"e": 11520,
"s": 11220,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 11530,
"s": 11520,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11543,
"s": 11530,
"text": "princi singh"
},
{
"code": null,
"e": 11555,
"s": 11543,
"text": "sanjeev2552"
},
{
"code": null,
"e": 11572,
"s": 11555,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 11586,
"s": 11572,
"text": "sumitgumber28"
},
{
"code": null,
"e": 11603,
"s": 11586,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 11610,
"s": 11603,
"text": "Arrays"
},
{
"code": null,
"e": 11617,
"s": 11610,
"text": "Arrays"
},
{
"code": null,
"e": 11715,
"s": 11617,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11747,
"s": 11715,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 11794,
"s": 11747,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 11819,
"s": 11794,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 11850,
"s": 11819,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 11908,
"s": 11850,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 11929,
"s": 11908,
"text": "Next Greater Element"
},
{
"code": null,
"e": 12014,
"s": 11929,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 12078,
"s": 12014,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 12105,
"s": 12078,
"text": "Count pairs with given sum"
}
] |
React Suite DateRangePicker Component
|
11 Apr, 2022
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. DateRangePicker component allows the user to quickly select a date range. We can use the following approach in ReactJS to use the React Suite DateRangePicker Component.
DateRangePicker Props:
appearance: It is used for the component appearance.
block: It is used to block an entire row.
cleanable: It is used to indicate whether the option can be emptied or not.
container: It is used to set the rendering container.
defaultCalendarValue: It is used to denote the default calendar panel date.
defaultOpen: It is used to denote the default value of the open property.
defaultValue: It is used to denote the default value.
disabled: It is used to indicate whether the component is disabled or not.
disabledDate: It is used to disable the date.
hoverRange: It is used to select the date range when you click on the date.
isoWeek: It is a boolean value denoting the ISO 8601 standard set or not.
limitEndYear: It is used to set the lower limit of the available year relative to the currently selected date.
onChange: It is a callback function that is triggered when the value changes.
onClean: It is a callback function that is triggered when value clean.
onClose: It is a callback function that is triggered on a close event.
onEnter: It is a callback function that is triggered before the overlay transitions in.
onEntered: It is a callback function that is triggered after the overlay finishes transitioning in.
onEntering: It is a callback function that is triggered as the overlay begins to transition in.
onExit: It is a callback function that is triggered right before the overlay transitions out.
onExited: It is a callback function that is triggered after the overlay finishes transitioning out.
onExiting: It is a callback function that is triggered as the overlay begins to transition out.
onOk: It is a callback function that is triggered on click ok the Ok button.
onOpen: It is a callback function that is triggered on open of the component.
onSelect: It is a callback function that is triggered on the selection of date or time.
oneTap: It is used to indicate whether to enable One-click to complete the selection date or not.
open: It is used to indicate whether open the component or not.
placeholder: It is used to denote the placeholder.
placement: It is used for the placement of component.
preventOverflow: It is used to prevent floating element overflow.
ranges: It is used for the shortcut config.
renderValue: It is used for the custom render selected date range.
showOneCalendar: It is used to indicate whether to show only one calendar or not.
showWeekNumbers: It is used to indicate whether to show week numbers or not.
size: It is used to denote the picker size.
toggleComponentClass: It can be used for the custom element for this component.
value: It is used to denote the value (Controlled).
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install rsuite
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install rsuite
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import 'rsuite/dist/styles/rsuite-default.css';import { DateRangePicker } from 'rsuite'; export default function App() { return ( <div style={{ display: 'block', width: 600, paddingLeft: 30 }}> <h4>React Suite DateRangePicker Component</h4> <DateRangePicker style={{ width: 300 }} placeholder="Select Date Range" /> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://rsuitejs.com/components/date-range-picker/
React-Suite
React-Suite Components
React-Suite Data Entry
JavaScript
ReactJS
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
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 336,
"s": 28,
"text": "React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. DateRangePicker component allows the user to quickly select a date range. We can use the following approach in ReactJS to use the React Suite DateRangePicker Component."
},
{
"code": null,
"e": 359,
"s": 336,
"text": "DateRangePicker Props:"
},
{
"code": null,
"e": 412,
"s": 359,
"text": "appearance: It is used for the component appearance."
},
{
"code": null,
"e": 454,
"s": 412,
"text": "block: It is used to block an entire row."
},
{
"code": null,
"e": 530,
"s": 454,
"text": "cleanable: It is used to indicate whether the option can be emptied or not."
},
{
"code": null,
"e": 584,
"s": 530,
"text": "container: It is used to set the rendering container."
},
{
"code": null,
"e": 660,
"s": 584,
"text": "defaultCalendarValue: It is used to denote the default calendar panel date."
},
{
"code": null,
"e": 734,
"s": 660,
"text": "defaultOpen: It is used to denote the default value of the open property."
},
{
"code": null,
"e": 788,
"s": 734,
"text": "defaultValue: It is used to denote the default value."
},
{
"code": null,
"e": 863,
"s": 788,
"text": "disabled: It is used to indicate whether the component is disabled or not."
},
{
"code": null,
"e": 909,
"s": 863,
"text": "disabledDate: It is used to disable the date."
},
{
"code": null,
"e": 985,
"s": 909,
"text": "hoverRange: It is used to select the date range when you click on the date."
},
{
"code": null,
"e": 1059,
"s": 985,
"text": "isoWeek: It is a boolean value denoting the ISO 8601 standard set or not."
},
{
"code": null,
"e": 1170,
"s": 1059,
"text": "limitEndYear: It is used to set the lower limit of the available year relative to the currently selected date."
},
{
"code": null,
"e": 1248,
"s": 1170,
"text": "onChange: It is a callback function that is triggered when the value changes."
},
{
"code": null,
"e": 1319,
"s": 1248,
"text": "onClean: It is a callback function that is triggered when value clean."
},
{
"code": null,
"e": 1390,
"s": 1319,
"text": "onClose: It is a callback function that is triggered on a close event."
},
{
"code": null,
"e": 1478,
"s": 1390,
"text": "onEnter: It is a callback function that is triggered before the overlay transitions in."
},
{
"code": null,
"e": 1578,
"s": 1478,
"text": "onEntered: It is a callback function that is triggered after the overlay finishes transitioning in."
},
{
"code": null,
"e": 1674,
"s": 1578,
"text": "onEntering: It is a callback function that is triggered as the overlay begins to transition in."
},
{
"code": null,
"e": 1768,
"s": 1674,
"text": "onExit: It is a callback function that is triggered right before the overlay transitions out."
},
{
"code": null,
"e": 1868,
"s": 1768,
"text": "onExited: It is a callback function that is triggered after the overlay finishes transitioning out."
},
{
"code": null,
"e": 1964,
"s": 1868,
"text": "onExiting: It is a callback function that is triggered as the overlay begins to transition out."
},
{
"code": null,
"e": 2041,
"s": 1964,
"text": "onOk: It is a callback function that is triggered on click ok the Ok button."
},
{
"code": null,
"e": 2119,
"s": 2041,
"text": "onOpen: It is a callback function that is triggered on open of the component."
},
{
"code": null,
"e": 2207,
"s": 2119,
"text": "onSelect: It is a callback function that is triggered on the selection of date or time."
},
{
"code": null,
"e": 2305,
"s": 2207,
"text": "oneTap: It is used to indicate whether to enable One-click to complete the selection date or not."
},
{
"code": null,
"e": 2369,
"s": 2305,
"text": "open: It is used to indicate whether open the component or not."
},
{
"code": null,
"e": 2420,
"s": 2369,
"text": "placeholder: It is used to denote the placeholder."
},
{
"code": null,
"e": 2474,
"s": 2420,
"text": "placement: It is used for the placement of component."
},
{
"code": null,
"e": 2540,
"s": 2474,
"text": "preventOverflow: It is used to prevent floating element overflow."
},
{
"code": null,
"e": 2584,
"s": 2540,
"text": "ranges: It is used for the shortcut config."
},
{
"code": null,
"e": 2651,
"s": 2584,
"text": "renderValue: It is used for the custom render selected date range."
},
{
"code": null,
"e": 2733,
"s": 2651,
"text": "showOneCalendar: It is used to indicate whether to show only one calendar or not."
},
{
"code": null,
"e": 2810,
"s": 2733,
"text": "showWeekNumbers: It is used to indicate whether to show week numbers or not."
},
{
"code": null,
"e": 2854,
"s": 2810,
"text": "size: It is used to denote the picker size."
},
{
"code": null,
"e": 2934,
"s": 2854,
"text": "toggleComponentClass: It can be used for the custom element for this component."
},
{
"code": null,
"e": 2986,
"s": 2934,
"text": "value: It is used to denote the value (Controlled)."
},
{
"code": null,
"e": 3036,
"s": 2986,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 3131,
"s": 3036,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 3195,
"s": 3131,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 3227,
"s": 3195,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 3342,
"s": 3229,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 3442,
"s": 3342,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 3456,
"s": 3442,
"text": "cd foldername"
},
{
"code": null,
"e": 3579,
"s": 3456,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install rsuite"
},
{
"code": null,
"e": 3684,
"s": 3579,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 3703,
"s": 3684,
"text": "npm install rsuite"
},
{
"code": null,
"e": 3755,
"s": 3703,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 3773,
"s": 3755,
"text": "Project Structure"
},
{
"code": null,
"e": 3903,
"s": 3773,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 3910,
"s": 3903,
"text": "App.js"
},
{
"code": "import React from 'react'import 'rsuite/dist/styles/rsuite-default.css';import { DateRangePicker } from 'rsuite'; export default function App() { return ( <div style={{ display: 'block', width: 600, paddingLeft: 30 }}> <h4>React Suite DateRangePicker Component</h4> <DateRangePicker style={{ width: 300 }} placeholder=\"Select Date Range\" /> </div> );}",
"e": 4310,
"s": 3910,
"text": null
},
{
"code": null,
"e": 4423,
"s": 4310,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 4433,
"s": 4423,
"text": "npm start"
},
{
"code": null,
"e": 4532,
"s": 4433,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 4594,
"s": 4532,
"text": "Reference: https://rsuitejs.com/components/date-range-picker/"
},
{
"code": null,
"e": 4606,
"s": 4594,
"text": "React-Suite"
},
{
"code": null,
"e": 4629,
"s": 4606,
"text": "React-Suite Components"
},
{
"code": null,
"e": 4652,
"s": 4629,
"text": "React-Suite Data Entry"
},
{
"code": null,
"e": 4663,
"s": 4652,
"text": "JavaScript"
},
{
"code": null,
"e": 4671,
"s": 4663,
"text": "ReactJS"
},
{
"code": null,
"e": 4688,
"s": 4671,
"text": "Web Technologies"
},
{
"code": null,
"e": 4786,
"s": 4688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4847,
"s": 4786,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4887,
"s": 4847,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4928,
"s": 4887,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4970,
"s": 4928,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4992,
"s": 4970,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 5035,
"s": 4992,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5080,
"s": 5035,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 5118,
"s": 5080,
"text": "Axios in React: A Guide for Beginners"
}
] |
How to detect Operating System through a C program
|
19 Jul, 2020
One can find out the operating system on which the program is running with the help of C programming. This piece of information is very useful for the case where we want to build platform independent program. To find the OS (Operating System) we check out the macro defined by the compiler, for example windows with 32-bit OS has “_WIN32” as macro so if the macro is defined then the system we are working on is windows with 32-bit operating system. Similarly other OS has different macro defined. The list of macro for some popular OS are as follows:
Note:
It must be noted that the macros are valid for GNU GCC and G++ and may vary for other compilers.
Below is the program to detect which OS we are working on:
C
// C program to detect Operating System #include <stdio.h> // Driver Codeint main(){ // Checking for windows OS with// _WIN32 macro#ifdef _WIN32 printf("Hey Geek it seems that" "you are working on a Windows OS.\n"); // Checking for mac OS with// __APPLE__ macro#elif __APPLE__ printf("Hey Geek it seems that you" "are working on a Mac OS.\n"); // Checking for linux OS with// __linux__ macro#elif __linux__ printf("Hey Geek it seems that you" "are working on a Linux OS.\n"); // Checking for iOS embedded OS with// TARGET_OS_EMBEDDED macro#elif TARGET_OS_EMBEDDED printf("Hey Geek it seems that you" "are working on an iOS embedded OS.\n"); // Checking for iOS simulator OS with// TARGET_IPHONE_SIMULATOR macro#elif TARGET_IPHONE_SIMULATOR printf("Hey Geek it seems that you" "are working on an iOS simulator OS.\n"); // Checking for iPhone OS with// TARGET_OS_IPHONE macro#elif TARGET_OS_IPHONE printf("Hey Geek it seems that you" "are working on an iPhone OS.\n"); // Checking for MAC OS with// TARGET_OS_MAC macro#elif TARGET_OS_MAC printf("Hey Geek it seems that you" "are working on a MAC OS.\n"); // Checking for Android OS with// __ANDROID__ macro#elif__ANDROID__ printf("Hey Geek it seems that you" "are working on an android OS.\n"); // Checking for unix OS with// __unix__ macro#elif __unix__ printf("Hey Geek it seems that you" "are working on a unix OS.\n"); // Checking for POSIX based OS with// _POSIX_VERSION macro#elif _POSIX_VERSION printf("Hey Geek it seems that you" "are working on a POSIX based OS.\n"); // Checking for Solaris OS with// __sun macro#elif __sun printf("Hey Geek it seems that you" "are working on a Solaris OS.\n"); // Checking for HP UX OS with// __hpux macro#elif __hpux printf("Hey Geek it seems that you" "are working on a HP UX OS.\n"); // Checking for BSD OS with// BSD macro#elif BSD printf("Hey Geek it seems that you" "are working on a Solaris OS.\n"); // Checking for DragonFly BSD OS with// __DragonFly__ macro#elif __DragonFly__ printf("Hey Geek it seems that you" "are working on a DragonFly BSD OS.\n"); // Checking for FreeBSD OS with// __FreeBSD__ macro#elif __FreeBSD__ printf("Hey Geek it seems that you" "are working on a FreeBSD OS.\n"); // Checking for Net BSD OS with// __NetBSD__ macro#elif __NetBSD__ printf("Hey Geek it seems that you" "are working on a Net BSD OS.\n"); // Checking for Open BSD OS with// __OpenBSD__ macro#elif __OpenBSD__ printf("Hey Geek it seems that you" "are working on an Open BSD OS.\n"); // If neither of them is present// then this is printed...#else printf("Sorry, the system are" "not listed above.\n");#endif return 0;}
Similarly one can find out the operating system and can set the appropriate code for the system
C Macro
C Programs
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
C Hello World Program
C program to find the length of a string
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jul, 2020"
},
{
"code": null,
"e": 580,
"s": 28,
"text": "One can find out the operating system on which the program is running with the help of C programming. This piece of information is very useful for the case where we want to build platform independent program. To find the OS (Operating System) we check out the macro defined by the compiler, for example windows with 32-bit OS has “_WIN32” as macro so if the macro is defined then the system we are working on is windows with 32-bit operating system. Similarly other OS has different macro defined. The list of macro for some popular OS are as follows:"
},
{
"code": null,
"e": 586,
"s": 580,
"text": "Note:"
},
{
"code": null,
"e": 683,
"s": 586,
"text": "It must be noted that the macros are valid for GNU GCC and G++ and may vary for other compilers."
},
{
"code": null,
"e": 742,
"s": 683,
"text": "Below is the program to detect which OS we are working on:"
},
{
"code": null,
"e": 744,
"s": 742,
"text": "C"
},
{
"code": "// C program to detect Operating System #include <stdio.h> // Driver Codeint main(){ // Checking for windows OS with// _WIN32 macro#ifdef _WIN32 printf(\"Hey Geek it seems that\" \"you are working on a Windows OS.\\n\"); // Checking for mac OS with// __APPLE__ macro#elif __APPLE__ printf(\"Hey Geek it seems that you\" \"are working on a Mac OS.\\n\"); // Checking for linux OS with// __linux__ macro#elif __linux__ printf(\"Hey Geek it seems that you\" \"are working on a Linux OS.\\n\"); // Checking for iOS embedded OS with// TARGET_OS_EMBEDDED macro#elif TARGET_OS_EMBEDDED printf(\"Hey Geek it seems that you\" \"are working on an iOS embedded OS.\\n\"); // Checking for iOS simulator OS with// TARGET_IPHONE_SIMULATOR macro#elif TARGET_IPHONE_SIMULATOR printf(\"Hey Geek it seems that you\" \"are working on an iOS simulator OS.\\n\"); // Checking for iPhone OS with// TARGET_OS_IPHONE macro#elif TARGET_OS_IPHONE printf(\"Hey Geek it seems that you\" \"are working on an iPhone OS.\\n\"); // Checking for MAC OS with// TARGET_OS_MAC macro#elif TARGET_OS_MAC printf(\"Hey Geek it seems that you\" \"are working on a MAC OS.\\n\"); // Checking for Android OS with// __ANDROID__ macro#elif__ANDROID__ printf(\"Hey Geek it seems that you\" \"are working on an android OS.\\n\"); // Checking for unix OS with// __unix__ macro#elif __unix__ printf(\"Hey Geek it seems that you\" \"are working on a unix OS.\\n\"); // Checking for POSIX based OS with// _POSIX_VERSION macro#elif _POSIX_VERSION printf(\"Hey Geek it seems that you\" \"are working on a POSIX based OS.\\n\"); // Checking for Solaris OS with// __sun macro#elif __sun printf(\"Hey Geek it seems that you\" \"are working on a Solaris OS.\\n\"); // Checking for HP UX OS with// __hpux macro#elif __hpux printf(\"Hey Geek it seems that you\" \"are working on a HP UX OS.\\n\"); // Checking for BSD OS with// BSD macro#elif BSD printf(\"Hey Geek it seems that you\" \"are working on a Solaris OS.\\n\"); // Checking for DragonFly BSD OS with// __DragonFly__ macro#elif __DragonFly__ printf(\"Hey Geek it seems that you\" \"are working on a DragonFly BSD OS.\\n\"); // Checking for FreeBSD OS with// __FreeBSD__ macro#elif __FreeBSD__ printf(\"Hey Geek it seems that you\" \"are working on a FreeBSD OS.\\n\"); // Checking for Net BSD OS with// __NetBSD__ macro#elif __NetBSD__ printf(\"Hey Geek it seems that you\" \"are working on a Net BSD OS.\\n\"); // Checking for Open BSD OS with// __OpenBSD__ macro#elif __OpenBSD__ printf(\"Hey Geek it seems that you\" \"are working on an Open BSD OS.\\n\"); // If neither of them is present// then this is printed...#else printf(\"Sorry, the system are\" \"not listed above.\\n\");#endif return 0;}",
"e": 3613,
"s": 744,
"text": null
},
{
"code": null,
"e": 3709,
"s": 3613,
"text": "Similarly one can find out the operating system and can set the appropriate code for the system"
},
{
"code": null,
"e": 3717,
"s": 3709,
"text": "C Macro"
},
{
"code": null,
"e": 3728,
"s": 3717,
"text": "C Programs"
},
{
"code": null,
"e": 3746,
"s": 3728,
"text": "Operating Systems"
},
{
"code": null,
"e": 3764,
"s": 3746,
"text": "Operating Systems"
},
{
"code": null,
"e": 3862,
"s": 3764,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3903,
"s": 3862,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 3934,
"s": 3903,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 3987,
"s": 3934,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 4009,
"s": 3987,
"text": "C Hello World Program"
},
{
"code": null,
"e": 4050,
"s": 4009,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 4077,
"s": 4050,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 4116,
"s": 4077,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 4165,
"s": 4116,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 4192,
"s": 4165,
"text": "Disk Scheduling Algorithms"
}
] |
Python List index()
|
21 Jun, 2022
Python index() is an inbuilt function in Python, which searches for a given element from the start of the list and returns the lowest index where the element appears.
In this article, we will cover different examples to find the index, such as:
Find the index of the element
Working of the index() With Start and End Parameters
Working of the index() With two Parameters only
Index of the Element not Present in the List
How to fix list index out of range
Syntax: list_name.index(element, start, end)
Parameters:
element – The element whose lowest index will be returned.
start (Optional) – The position from where the search begins.
end (Optional) – The position from where the search ends.
Returns: the lowest index where the element appears.
Error: If any element which is not present is searched, it returns a ValueError
In this example, we will try to find out the index of an element of “bat” from python to get the index of items in the list.
Python3
# list of itemslist2 = ['cat', 'bat', 'mat', 'cat', 'pet'] # Will print the index of 'cat' in list2print(list2.index('bat'))
Output:
1
In this example, we find an element in list python, the index of an element of 4 in between the index at the 4th position and ending with the 8th position.
Python3
# list of itemslist1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] # Will print index of '4' in sublist# having index from 4 to 8.print(list1.index(4, 4, 8))
Output:
7
In this example, we will see when we pass two arguments in the index function, the first argument is treated as the element to be searched and the second argument is the index from where the searching begins.
list_name.index(element, start)
Python3
# list of itemslist1 = [6, 8, 5, 6, 1, 2] # Will print index of '3' in sublist# having index from 1 to end of the list.print(list1.index(6, 1))
Output:
3
In this example, we will see that if the Index of the Element will not Present in the List it will through a ValueError.
Python3
# Python3 program for demonstration# of index() method error list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] # Return ValueErrorprint(list1.index(10))
Output:
Traceback (most recent call last):
File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in
print(list1.index(10))
ValueError: 10 is not in list
In this example, The third argument which is the end, itself is not included in the range from start to end, i.e the searching takes place from start to end-1 index. Hence, The end index passed as an argument is not included.
list_name.index(element, start, end)
Python3
# Python3 program for demonstration# of index() method list1 = [6 , 2 , 14 , 8 , 9 , 10] # return error as index '4' is not included in the range# having index from 1 to 4.print(list1.index(9, 1, 4))
Output:
Traceback (most recent call last):
File "/home/3cbe5b7d0595ab3f8564f16af7a15172.py", line 9, in <module>
print(list1.index(9 , 1 , 4))
ValueError: 9 is not in list
Here we are going to create a list and then try to iterate the list using the constant values in for loops.
Python3
li = [1,2 ,3, 4, 5] for i in range(6): print(li[i])
Output:
1
2
3
4
5
IndexError: list index out of range
Reason of the error – The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.
Solving this error without using len() or constant Value:
To solve this error we will take the index of the last value of the list and then add one then it will become the exact value of length.
Python3
li = [1,2 ,3, 4, 5] for i in range(li.index(li[-1])+1): print(li[i])
Output:
1
2
3
4
5
riyaaggarwaldtu
AmiyaRanjanRout
susobhanakhuli
surajkumarguptaintern
Python-Built-in-functions
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 220,
"s": 52,
"text": "Python index() is an inbuilt function in Python, which searches for a given element from the start of the list and returns the lowest index where the element appears. "
},
{
"code": null,
"e": 298,
"s": 220,
"text": "In this article, we will cover different examples to find the index, such as:"
},
{
"code": null,
"e": 328,
"s": 298,
"text": "Find the index of the element"
},
{
"code": null,
"e": 381,
"s": 328,
"text": "Working of the index() With Start and End Parameters"
},
{
"code": null,
"e": 429,
"s": 381,
"text": "Working of the index() With two Parameters only"
},
{
"code": null,
"e": 474,
"s": 429,
"text": "Index of the Element not Present in the List"
},
{
"code": null,
"e": 509,
"s": 474,
"text": "How to fix list index out of range"
},
{
"code": null,
"e": 554,
"s": 509,
"text": "Syntax: list_name.index(element, start, end)"
},
{
"code": null,
"e": 568,
"s": 554,
"text": "Parameters: "
},
{
"code": null,
"e": 627,
"s": 568,
"text": "element – The element whose lowest index will be returned."
},
{
"code": null,
"e": 689,
"s": 627,
"text": "start (Optional) – The position from where the search begins."
},
{
"code": null,
"e": 747,
"s": 689,
"text": "end (Optional) – The position from where the search ends."
},
{
"code": null,
"e": 800,
"s": 747,
"text": "Returns: the lowest index where the element appears."
},
{
"code": null,
"e": 880,
"s": 800,
"text": "Error: If any element which is not present is searched, it returns a ValueError"
},
{
"code": null,
"e": 1005,
"s": 880,
"text": "In this example, we will try to find out the index of an element of “bat” from python to get the index of items in the list."
},
{
"code": null,
"e": 1013,
"s": 1005,
"text": "Python3"
},
{
"code": "# list of itemslist2 = ['cat', 'bat', 'mat', 'cat', 'pet'] # Will print the index of 'cat' in list2print(list2.index('bat'))",
"e": 1138,
"s": 1013,
"text": null
},
{
"code": null,
"e": 1148,
"s": 1138,
"text": "Output: "
},
{
"code": null,
"e": 1150,
"s": 1148,
"text": "1"
},
{
"code": null,
"e": 1308,
"s": 1150,
"text": " In this example, we find an element in list python, the index of an element of 4 in between the index at the 4th position and ending with the 8th position. "
},
{
"code": null,
"e": 1316,
"s": 1308,
"text": "Python3"
},
{
"code": "# list of itemslist1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] # Will print index of '4' in sublist# having index from 4 to 8.print(list1.index(4, 4, 8))",
"e": 1458,
"s": 1316,
"text": null
},
{
"code": null,
"e": 1467,
"s": 1458,
"text": "Output: "
},
{
"code": null,
"e": 1469,
"s": 1467,
"text": "7"
},
{
"code": null,
"e": 1679,
"s": 1469,
"text": "In this example, we will see when we pass two arguments in the index function, the first argument is treated as the element to be searched and the second argument is the index from where the searching begins. "
},
{
"code": null,
"e": 1711,
"s": 1679,
"text": "list_name.index(element, start)"
},
{
"code": null,
"e": 1719,
"s": 1711,
"text": "Python3"
},
{
"code": "# list of itemslist1 = [6, 8, 5, 6, 1, 2] # Will print index of '3' in sublist# having index from 1 to end of the list.print(list1.index(6, 1))",
"e": 1863,
"s": 1719,
"text": null
},
{
"code": null,
"e": 1871,
"s": 1863,
"text": "Output:"
},
{
"code": null,
"e": 1873,
"s": 1871,
"text": "3"
},
{
"code": null,
"e": 1994,
"s": 1873,
"text": "In this example, we will see that if the Index of the Element will not Present in the List it will through a ValueError."
},
{
"code": null,
"e": 2002,
"s": 1994,
"text": "Python3"
},
{
"code": "# Python3 program for demonstration# of index() method error list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] # Return ValueErrorprint(list1.index(10))",
"e": 2141,
"s": 2002,
"text": null
},
{
"code": null,
"e": 2150,
"s": 2141,
"text": "Output: "
},
{
"code": null,
"e": 2306,
"s": 2150,
"text": "Traceback (most recent call last):\n File \"/home/b910d8dcbc0f4f4b61499668654450d2.py\", line 8, in \n print(list1.index(10))\nValueError: 10 is not in list"
},
{
"code": null,
"e": 2532,
"s": 2306,
"text": "In this example, The third argument which is the end, itself is not included in the range from start to end, i.e the searching takes place from start to end-1 index. Hence, The end index passed as an argument is not included."
},
{
"code": null,
"e": 2569,
"s": 2532,
"text": "list_name.index(element, start, end)"
},
{
"code": null,
"e": 2577,
"s": 2569,
"text": "Python3"
},
{
"code": "# Python3 program for demonstration# of index() method list1 = [6 , 2 , 14 , 8 , 9 , 10] # return error as index '4' is not included in the range# having index from 1 to 4.print(list1.index(9, 1, 4))",
"e": 2777,
"s": 2577,
"text": null
},
{
"code": null,
"e": 2785,
"s": 2777,
"text": "Output:"
},
{
"code": null,
"e": 2955,
"s": 2785,
"text": "Traceback (most recent call last):\n File \"/home/3cbe5b7d0595ab3f8564f16af7a15172.py\", line 9, in <module>\n print(list1.index(9 , 1 , 4))\nValueError: 9 is not in list"
},
{
"code": null,
"e": 3063,
"s": 2955,
"text": "Here we are going to create a list and then try to iterate the list using the constant values in for loops."
},
{
"code": null,
"e": 3071,
"s": 3063,
"text": "Python3"
},
{
"code": "li = [1,2 ,3, 4, 5] for i in range(6): print(li[i])",
"e": 3126,
"s": 3071,
"text": null
},
{
"code": null,
"e": 3134,
"s": 3126,
"text": "Output:"
},
{
"code": null,
"e": 3180,
"s": 3134,
"text": "1\n2\n3\n4\n5\nIndexError: list index out of range"
},
{
"code": null,
"e": 3301,
"s": 3180,
"text": "Reason of the error – The length of the list is 5 and if we are an iterating list on 6 then it will generate the error."
},
{
"code": null,
"e": 3359,
"s": 3301,
"text": "Solving this error without using len() or constant Value:"
},
{
"code": null,
"e": 3496,
"s": 3359,
"text": "To solve this error we will take the index of the last value of the list and then add one then it will become the exact value of length."
},
{
"code": null,
"e": 3504,
"s": 3496,
"text": "Python3"
},
{
"code": "li = [1,2 ,3, 4, 5] for i in range(li.index(li[-1])+1): print(li[i])",
"e": 3576,
"s": 3504,
"text": null
},
{
"code": null,
"e": 3584,
"s": 3576,
"text": "Output:"
},
{
"code": null,
"e": 3594,
"s": 3584,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 3610,
"s": 3594,
"text": "riyaaggarwaldtu"
},
{
"code": null,
"e": 3626,
"s": 3610,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 3641,
"s": 3626,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 3663,
"s": 3641,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 3689,
"s": 3663,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 3701,
"s": 3689,
"text": "python-list"
},
{
"code": null,
"e": 3723,
"s": 3701,
"text": "python-list-functions"
},
{
"code": null,
"e": 3730,
"s": 3723,
"text": "Python"
},
{
"code": null,
"e": 3742,
"s": 3730,
"text": "python-list"
},
{
"code": null,
"e": 3840,
"s": 3742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3882,
"s": 3840,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3908,
"s": 3882,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3940,
"s": 3908,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3969,
"s": 3940,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3996,
"s": 3969,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4017,
"s": 3996,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4053,
"s": 4017,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4076,
"s": 4053,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4113,
"s": 4076,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Lodash _.delay() Method
|
23 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.delay() method is used to call the given function as the parameter after the stated wait time is over, which is in milliseconds. Any further arguments are provided to the function when it is called.
Syntax:
_.delay( func, wait, args )
Parameters: This method accepts three parameters as mentioned above and described below:
func: It is the function that has to be delayed.
wait: It is the number of milliseconds for which the function call is delayed.
args: It is the arguments with which the given function is being called. It is an optional parameter.
Return Value: This method returns the timer id.
Example 1: In this example, the content is printed after the delay of 3 seconds as the wait time is 3 seconds.
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Using the _.delay() method// with its parameter_.delay(function(content) { console.log(content); }, 3000, 'GeeksforGeeks!'); // Print the content after this lineconsole.log('Content:');
Output:
Content:
GeeksforGeeks!
Example 2: In this example, each integer is printed after a delay of 2 seconds.
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Defining func parameterlet func = number => { console.log(number);}; // Defining for loopfor(let i = 1; i <= 5; i++) { // Using the _.delay() method // with its parameter _.delay(func, 2000 * (i + 1), i);} // Prints the integer after this lineconsole.log('Integers are as follows:');
Output:
Integers are as follows:
1
2
3
4
5
JavaScript-Lodash
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": "\n23 Sep, 2020"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 373,
"s": 168,
"text": "The _.delay() method is used to call the given function as the parameter after the stated wait time is over, which is in milliseconds. Any further arguments are provided to the function when it is called."
},
{
"code": null,
"e": 381,
"s": 373,
"text": "Syntax:"
},
{
"code": null,
"e": 409,
"s": 381,
"text": "_.delay( func, wait, args )"
},
{
"code": null,
"e": 498,
"s": 409,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 547,
"s": 498,
"text": "func: It is the function that has to be delayed."
},
{
"code": null,
"e": 626,
"s": 547,
"text": "wait: It is the number of milliseconds for which the function call is delayed."
},
{
"code": null,
"e": 728,
"s": 626,
"text": "args: It is the arguments with which the given function is being called. It is an optional parameter."
},
{
"code": null,
"e": 776,
"s": 728,
"text": "Return Value: This method returns the timer id."
},
{
"code": null,
"e": 887,
"s": 776,
"text": "Example 1: In this example, the content is printed after the delay of 3 seconds as the wait time is 3 seconds."
},
{
"code": null,
"e": 898,
"s": 887,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Using the _.delay() method// with its parameter_.delay(function(content) { console.log(content); }, 3000, 'GeeksforGeeks!'); // Print the content after this lineconsole.log('Content:');",
"e": 1149,
"s": 898,
"text": null
},
{
"code": null,
"e": 1157,
"s": 1149,
"text": "Output:"
},
{
"code": null,
"e": 1181,
"s": 1157,
"text": "Content:\nGeeksforGeeks!"
},
{
"code": null,
"e": 1261,
"s": 1181,
"text": "Example 2: In this example, each integer is printed after a delay of 2 seconds."
},
{
"code": null,
"e": 1272,
"s": 1261,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Defining func parameterlet func = number => { console.log(number);}; // Defining for loopfor(let i = 1; i <= 5; i++) { // Using the _.delay() method // with its parameter _.delay(func, 2000 * (i + 1), i);} // Prints the integer after this lineconsole.log('Integers are as follows:');",
"e": 1634,
"s": 1272,
"text": null
},
{
"code": null,
"e": 1642,
"s": 1634,
"text": "Output:"
},
{
"code": null,
"e": 1677,
"s": 1642,
"text": "Integers are as follows:\n1\n2\n3\n4\n5"
},
{
"code": null,
"e": 1695,
"s": 1677,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1706,
"s": 1695,
"text": "JavaScript"
},
{
"code": null,
"e": 1723,
"s": 1706,
"text": "Web Technologies"
},
{
"code": null,
"e": 1821,
"s": 1723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1882,
"s": 1821,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1954,
"s": 1882,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1994,
"s": 1954,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2047,
"s": 1994,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2099,
"s": 2047,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2161,
"s": 2099,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2194,
"s": 2161,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2255,
"s": 2194,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2305,
"s": 2255,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Iterate Through Elements of LinkedHashSet in Java
|
07 Jan, 2021
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used.
Example:
Input:
["Geeks", "for", "Geeks"]
Output:
Geeks
for
Geeks
Input:
[9, 4, 6, 2, 8]
Output:
9
4
6
2
8
Different Ways to Iterate LinkedHashSet Elements:
Using the for-each loopUsing iteratorsUsing JDK 1.8 streams
Using the for-each loop
Using iterators
Using JDK 1.8 streams
Method 1: Using the for-each loop
Java
// Java Program to Iterate through linkedHashset// Using the for-each loop import java.io.*;import java.util.LinkedHashSet; class GFG { public static void main(String[] args) { LinkedHashSet<String> gfg = new LinkedHashSet<String>(); // Adding element to LinkedHashSet gfg.add("Geeks"); gfg.add("for"); gfg.add("geeks"); // iterating LinkedHashSet using enhanced for loop for (String itr : gfg) { System.out.println(itr); } }}
Geeks
for
geeks
Method 2: Using iterators
Iterate through the elements of LinkedHashSet using the iterator method. We will use the hasNext() method and the next() method along with the while loop to iterate through LinkedHashSet elements.
Type Parameters:
E – the type of elements maintained by this set.
Syntax:
public Iterator<E> iterator()
Return: This method returns the element of LinkedHashSet in the same order as the input.
Java
// Java code to demonstrate // the iterating over LinkedHashSet // Using iterators import java.io.*; import java.util.*; class IteratingLinkedHashSet { public static void main(String[] args) { // Instantiate an object of Set // Since LinkedHashSet implements Set // Set points to LinkedHashSet Set<String> gfg = new LinkedHashSet<String>(); // Elements are added using add() method gfg.add("Geek"); gfg.add("For"); gfg.add("Geeks"); gfg.add("Courses"); gfg.add("Interview Prep"); gfg.add("Doubt Classes"); // Iterating through the LinkedHashSet Iterator itr = gfg.iterator(); while (itr.hasNext()){ System.out.println( itr.next() ); } }}
Geek
For
Geeks
Courses
Interview Prep
Doubt Classes
Method 3: Using JDK 1.8 streams
Iterate through the elements of LinkedHashSet using the forEach method. We will iterate through the entire content using Stream. The stream represents a sequence of objects from a source, which supports aggregate operations.
Syntax:
set.stream().forEach()
Return: Returns a sequential stream considering collection as its source.
Java
// Java code to demonstrate// the iterating over LinkedHashSet// Using JDK 1.8 streams import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { LinkedHashSet<Integer> gfg = new LinkedHashSet<Integer>(); // Elements are added using add() method gfg.add(9); gfg.add(7); gfg.add(11); gfg.add(43); gfg.add(2); // Using forEach Method using Stream. gfg.stream().forEach(System.out::println); }}
9
7
11
43
2
Time complexity: O(N), where N is no. of elements of LinkedHashSet.
Java-Collections
java-LinkedHashSet
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
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": "\n07 Jan, 2021"
},
{
"code": null,
"e": 208,
"s": 28,
"text": "The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used."
},
{
"code": null,
"e": 217,
"s": 208,
"text": "Example:"
},
{
"code": null,
"e": 326,
"s": 217,
"text": "Input: \n[\"Geeks\", \"for\", \"Geeks\"]\n\n\nOutput:\nGeeks\nfor\nGeeks\n \nInput: \n[9, 4, 6, 2, 8]\n\n\nOutput:\n9\n4\n6\n2\n8"
},
{
"code": null,
"e": 376,
"s": 326,
"text": "Different Ways to Iterate LinkedHashSet Elements:"
},
{
"code": null,
"e": 436,
"s": 376,
"text": "Using the for-each loopUsing iteratorsUsing JDK 1.8 streams"
},
{
"code": null,
"e": 460,
"s": 436,
"text": "Using the for-each loop"
},
{
"code": null,
"e": 476,
"s": 460,
"text": "Using iterators"
},
{
"code": null,
"e": 498,
"s": 476,
"text": "Using JDK 1.8 streams"
},
{
"code": null,
"e": 533,
"s": 498,
"text": "Method 1: Using the for-each loop"
},
{
"code": null,
"e": 538,
"s": 533,
"text": "Java"
},
{
"code": "// Java Program to Iterate through linkedHashset// Using the for-each loop import java.io.*;import java.util.LinkedHashSet; class GFG { public static void main(String[] args) { LinkedHashSet<String> gfg = new LinkedHashSet<String>(); // Adding element to LinkedHashSet gfg.add(\"Geeks\"); gfg.add(\"for\"); gfg.add(\"geeks\"); // iterating LinkedHashSet using enhanced for loop for (String itr : gfg) { System.out.println(itr); } }}",
"e": 1060,
"s": 538,
"text": null
},
{
"code": null,
"e": 1076,
"s": 1060,
"text": "Geeks\nfor\ngeeks"
},
{
"code": null,
"e": 1102,
"s": 1076,
"text": "Method 2: Using iterators"
},
{
"code": null,
"e": 1301,
"s": 1102,
"text": "Iterate through the elements of LinkedHashSet using the iterator method. We will use the hasNext() method and the next() method along with the while loop to iterate through LinkedHashSet elements."
},
{
"code": null,
"e": 1318,
"s": 1301,
"text": "Type Parameters:"
},
{
"code": null,
"e": 1367,
"s": 1318,
"text": "E – the type of elements maintained by this set."
},
{
"code": null,
"e": 1375,
"s": 1367,
"text": "Syntax:"
},
{
"code": null,
"e": 1405,
"s": 1375,
"text": "public Iterator<E> iterator()"
},
{
"code": null,
"e": 1494,
"s": 1405,
"text": "Return: This method returns the element of LinkedHashSet in the same order as the input."
},
{
"code": null,
"e": 1499,
"s": 1494,
"text": "Java"
},
{
"code": "// Java code to demonstrate // the iterating over LinkedHashSet // Using iterators import java.io.*; import java.util.*; class IteratingLinkedHashSet { public static void main(String[] args) { // Instantiate an object of Set // Since LinkedHashSet implements Set // Set points to LinkedHashSet Set<String> gfg = new LinkedHashSet<String>(); // Elements are added using add() method gfg.add(\"Geek\"); gfg.add(\"For\"); gfg.add(\"Geeks\"); gfg.add(\"Courses\"); gfg.add(\"Interview Prep\"); gfg.add(\"Doubt Classes\"); // Iterating through the LinkedHashSet Iterator itr = gfg.iterator(); while (itr.hasNext()){ System.out.println( itr.next() ); } }}",
"e": 2307,
"s": 1499,
"text": null
},
{
"code": null,
"e": 2359,
"s": 2307,
"text": "Geek\nFor\nGeeks\nCourses\nInterview Prep\nDoubt Classes"
},
{
"code": null,
"e": 2391,
"s": 2359,
"text": "Method 3: Using JDK 1.8 streams"
},
{
"code": null,
"e": 2616,
"s": 2391,
"text": "Iterate through the elements of LinkedHashSet using the forEach method. We will iterate through the entire content using Stream. The stream represents a sequence of objects from a source, which supports aggregate operations."
},
{
"code": null,
"e": 2624,
"s": 2616,
"text": "Syntax:"
},
{
"code": null,
"e": 2647,
"s": 2624,
"text": "set.stream().forEach()"
},
{
"code": null,
"e": 2721,
"s": 2647,
"text": "Return: Returns a sequential stream considering collection as its source."
},
{
"code": null,
"e": 2726,
"s": 2721,
"text": "Java"
},
{
"code": "// Java code to demonstrate// the iterating over LinkedHashSet// Using JDK 1.8 streams import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { LinkedHashSet<Integer> gfg = new LinkedHashSet<Integer>(); // Elements are added using add() method gfg.add(9); gfg.add(7); gfg.add(11); gfg.add(43); gfg.add(2); // Using forEach Method using Stream. gfg.stream().forEach(System.out::println); }}",
"e": 3229,
"s": 2726,
"text": null
},
{
"code": null,
"e": 3241,
"s": 3229,
"text": "9\n7\n11\n43\n2"
},
{
"code": null,
"e": 3309,
"s": 3241,
"text": "Time complexity: O(N), where N is no. of elements of LinkedHashSet."
},
{
"code": null,
"e": 3326,
"s": 3309,
"text": "Java-Collections"
},
{
"code": null,
"e": 3345,
"s": 3326,
"text": "java-LinkedHashSet"
},
{
"code": null,
"e": 3352,
"s": 3345,
"text": "Picked"
},
{
"code": null,
"e": 3376,
"s": 3352,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3381,
"s": 3376,
"text": "Java"
},
{
"code": null,
"e": 3395,
"s": 3381,
"text": "Java Programs"
},
{
"code": null,
"e": 3414,
"s": 3395,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3419,
"s": 3414,
"text": "Java"
},
{
"code": null,
"e": 3436,
"s": 3419,
"text": "Java-Collections"
}
] |
Spring Interview Questions
|
Dear readers, these Spring Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Spring. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
Following is the list of few of the great benefits of using Spring Framework:
Lightweight − Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Lightweight − Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Inversion of control (IOC) − Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Inversion of control (IOC) − Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP) − Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Aspect oriented (AOP) − Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container − Spring contains and manages the life cycle and configuration of application objects.
Container − Spring contains and manages the life cycle and configuration of application objects.
MVC Framework − Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
MVC Framework − Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Transaction Management − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Transaction Management − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Exception Handling − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
Exception Handling − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
Following are the modules of the Spring framework:
Core module
Bean module
Context module
Expression Language module
JDBC module
ORM module
OXM module
Java Messaging Service(JMS) module
Transaction module
Web module
Web-Servlet module
Web-Struts module
Web-Portlet module
Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.
Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.
This concept says that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.
Types of IoC are −
Constructor-based dependency injection − Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
Constructor-based dependency injection − Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
Setter-based dependency injection − Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Setter-based dependency injection − Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies.
The main benefits of IOC or dependency injection are −
It minimizes the amount of code in your application.
It minimizes the amount of code in your application.
It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.
It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.
Loose coupling is promoted with minimal effort and least intrusive mechanism.
Loose coupling is promoted with minimal effort and least intrusive mechanism.
IOC containers support eager instantiation and lazy loading of services.
IOC containers support eager instantiation and lazy loading of services.
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.
The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.
There are two types of IoC containers −
Bean Factory container − This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
Bean Factory container − This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
Spring ApplicationContext Container − This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
Spring ApplicationContext Container − This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.
The three commonly used implementation of 'Application Context' are −
FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application.
WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application.
Following are some of the differences −
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
Application contexts can publish events to beans that are registered as listeners.
Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions.
The bean definition contains the information called configuration metadata which is needed for the container to know the followings −
How to create a bean
Bean's lifecycle details
Bean's dependencies
There are following three important methods to provide configuration metadata to the Spring Container −
XML based configuration file.
Annotation-based configuration
Java-based configuration
Check the following example −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.
The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.
singleton − This scopes the bean definition to a single instance per Spring IoC container.
singleton − This scopes the bean definition to a single instance per Spring IoC container.
prototype − This scopes a single bean definition to have any number of object instances.
prototype − This scopes a single bean definition to have any number of object instances.
request − This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
request − This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
session − This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
session − This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session − This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session − This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
The default scope of bean is Singleton for Spring framework.
No, singleton beans are not thread-safe in Spring framework.
Following is sequence of a bean lifecycle in Spring −
Instantiate − First the spring container finds the bean's definition from the XML file and instantiates the bean..
Instantiate − First the spring container finds the bean's definition from the XML file and instantiates the bean..
Populate properties − Using the dependency injection, spring populates all of the properties as specified in the bean definition.
Populate properties − Using the dependency injection, spring populates all of the properties as specified in the bean definition.
Set Bean Name − If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
Set Bean Name − If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
Set Bean factory − If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
Set Bean factory − If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
Pre Initialization − Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
Pre Initialization − Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
Initialize beans − If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
Initialize beans − If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
Post Initialization − If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Post Initialization − If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Ready to use − Now the bean is ready to use by the application.
Ready to use − Now the bean is ready to use by the application.
Destroy − If the bean implements DisposableBean , it will call the destroy() method .
Destroy − If the bean implements DisposableBean , it will call the destroy() method .
A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes.
Spring offers four types of collection configuration elements which are as follows −
<list> − This helps in wiring i.e. injecting a list of values, allowing duplicates.
<list> − This helps in wiring i.e. injecting a list of values, allowing duplicates.
<set> − This helps in wiring a set of values but without any duplicates.
<set> − This helps in wiring a set of values but without any duplicates.
<map> − This can be used to inject a collection of name-value pairs where name and value can be of any type.
<map> − This can be used to inject a collection of name-value pairs where name and value can be of any type.
<props> − This can be used to inject a collection of name-value pairs where the name and value are both Strings.
<props> − This can be used to inject a collection of name-value pairs where the name and value are both Strings.
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection −
no − This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.
no − This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.
byName − Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
byName − Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
byType − Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
byType − Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor − Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
constructor − Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
autodetect − Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
autodetect − Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
Limitations of autowiring are −
Overriding possibility − You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
Overriding possibility − You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
Primitive data types − You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
Primitive data types − You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
Confusing nature − Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
Confusing nature − Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
Yes.
An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.
This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.
This annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.
Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.
@PostConstruct − This annotation can be used as an alternate of initialization callback.
@PostConstruct − This annotation can be used as an alternate of initialization callback.
@PreDestroy − This annotation can be used as an alternate of destruction callback.
@PreDestroy − This annotation can be used as an alternate of destruction callback.
@Resource − This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.
@Resource − This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.
Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations.
For example: Annotation @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.
Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.
Spring provides the following standard events −
ContextRefreshedEvent − This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
ContextRefreshedEvent − This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
ContextStartedEvent − This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
ContextStartedEvent − This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
ContextStoppedEvent − This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event.
ContextStoppedEvent − This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event.
ContextClosedEvent − This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
ContextClosedEvent − This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
RequestHandledEvent − This is a web-specific event telling all beans that an HTTP request has been serviced.
RequestHandledEvent − This is a web-specific event telling all beans that an HTTP request has been serviced.
A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).
Concern − Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns.
Cross-cutting concern − It's a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.
This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.
This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.
This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.
An introduction allows you to add new methods or attributes to existing classes.
The object being advised by one or more aspects, this object will always be a proxy object. Also referred to as the advised object.
Weaving is the process of linking aspects with other application types or objects to create an advised object.
Weaving can be done at compile time, load time, or at runtime.
Spring aspects can work with five kinds of advice mentioned below −
before − Run advice before the a method execution.
before − Run advice before the a method execution.
after − Run advice after the a method execution regardless of its outcome.
after − Run advice after the a method execution regardless of its outcome.
after-returning − Run advice after the a method execution only if method completes successfully.
after-returning − Run advice after the a method execution only if method completes successfully.
after-throwing − Run advice after the a method execution only if method exits by throwing an exception.
after-throwing − Run advice after the a method execution only if method exits by throwing an exception.
around − Run advice before and after the advised method is invoked.
around − Run advice before and after the advised method is invoked.
Aspects are implemented using regular classes along with XML based configuration.
@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.
JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.
With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.
Spring supports two types of transaction management −
Programmatic transaction management − This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Programmatic transaction management − This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.
The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.
The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with.
Following are some of the advantages of Spring MVC over Struts MVC −
Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.
Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.
Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests.
Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests.
Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface.
Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface.
In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy.
In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy.
Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend.
Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend.
In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality.
In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality.
With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.
With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.
Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.
@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
There are two ways to access hibernate using spring −
Inversion of Control with a Hibernate Template and Callback.
Inversion of Control with a Hibernate Template and Callback.
Extending HibernateDAOSupport and Applying an AOP Interceptor node.
Extending HibernateDAOSupport and Applying an AOP Interceptor node.
Spring supports the following ORM's −
Hibernate
iBatis
JPA (Java Persistence API)
TopLink
JDO (Java Data Objects)
OJB
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
|
[
{
"code": null,
"e": 2862,
"s": 2426,
"text": "Dear readers, these Spring Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Spring. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:"
},
{
"code": null,
"e": 3253,
"s": 2862,
"text": "Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model."
},
{
"code": null,
"e": 3331,
"s": 3253,
"text": "Following is the list of few of the great benefits of using Spring Framework:"
},
{
"code": null,
"e": 3460,
"s": 3331,
"text": "Lightweight − Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB."
},
{
"code": null,
"e": 3589,
"s": 3460,
"text": "Lightweight − Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB."
},
{
"code": null,
"e": 3787,
"s": 3589,
"text": "Inversion of control (IOC) − Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects."
},
{
"code": null,
"e": 3985,
"s": 3787,
"text": "Inversion of control (IOC) − Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects."
},
{
"code": null,
"e": 4149,
"s": 3985,
"text": "Aspect oriented (AOP) − Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services."
},
{
"code": null,
"e": 4313,
"s": 4149,
"text": "Aspect oriented (AOP) − Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services."
},
{
"code": null,
"e": 4410,
"s": 4313,
"text": "Container − Spring contains and manages the life cycle and configuration of application objects."
},
{
"code": null,
"e": 4507,
"s": 4410,
"text": "Container − Spring contains and manages the life cycle and configuration of application objects."
},
{
"code": null,
"e": 4709,
"s": 4507,
"text": "MVC Framework − Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks."
},
{
"code": null,
"e": 4911,
"s": 4709,
"text": "MVC Framework − Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks."
},
{
"code": null,
"e": 5142,
"s": 4911,
"text": "Transaction Management − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example)."
},
{
"code": null,
"e": 5373,
"s": 5142,
"text": "Transaction Management − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example)."
},
{
"code": null,
"e": 5559,
"s": 5373,
"text": "Exception Handling − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions."
},
{
"code": null,
"e": 5745,
"s": 5559,
"text": "Exception Handling − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions."
},
{
"code": null,
"e": 5796,
"s": 5745,
"text": "Following are the modules of the Spring framework:"
},
{
"code": null,
"e": 5808,
"s": 5796,
"text": "Core module"
},
{
"code": null,
"e": 5820,
"s": 5808,
"text": "Bean module"
},
{
"code": null,
"e": 5835,
"s": 5820,
"text": "Context module"
},
{
"code": null,
"e": 5862,
"s": 5835,
"text": "Expression Language module"
},
{
"code": null,
"e": 5874,
"s": 5862,
"text": "JDBC module"
},
{
"code": null,
"e": 5885,
"s": 5874,
"text": "ORM module"
},
{
"code": null,
"e": 5896,
"s": 5885,
"text": "OXM module"
},
{
"code": null,
"e": 5931,
"s": 5896,
"text": "Java Messaging Service(JMS) module"
},
{
"code": null,
"e": 5950,
"s": 5931,
"text": "Transaction module"
},
{
"code": null,
"e": 5961,
"s": 5950,
"text": "Web module"
},
{
"code": null,
"e": 5980,
"s": 5961,
"text": "Web-Servlet module"
},
{
"code": null,
"e": 5998,
"s": 5980,
"text": "Web-Struts module"
},
{
"code": null,
"e": 6017,
"s": 5998,
"text": "Web-Portlet module"
},
{
"code": null,
"e": 6179,
"s": 6017,
"text": "Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other."
},
{
"code": null,
"e": 6356,
"s": 6179,
"text": "Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control."
},
{
"code": null,
"e": 6683,
"s": 6356,
"text": "This concept says that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up."
},
{
"code": null,
"e": 6702,
"s": 6683,
"text": "Types of IoC are −"
},
{
"code": null,
"e": 6902,
"s": 6702,
"text": "Constructor-based dependency injection − Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class."
},
{
"code": null,
"e": 7102,
"s": 6902,
"text": "Constructor-based dependency injection − Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class."
},
{
"code": null,
"e": 7328,
"s": 7102,
"text": "Setter-based dependency injection − Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean."
},
{
"code": null,
"e": 7554,
"s": 7328,
"text": "Setter-based dependency injection − Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean."
},
{
"code": null,
"e": 7841,
"s": 7554,
"text": "Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies."
},
{
"code": null,
"e": 7896,
"s": 7841,
"text": "The main benefits of IOC or dependency injection are −"
},
{
"code": null,
"e": 7949,
"s": 7896,
"text": "It minimizes the amount of code in your application."
},
{
"code": null,
"e": 8002,
"s": 7949,
"text": "It minimizes the amount of code in your application."
},
{
"code": null,
"e": 8129,
"s": 8002,
"text": "It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases."
},
{
"code": null,
"e": 8256,
"s": 8129,
"text": "It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases."
},
{
"code": null,
"e": 8334,
"s": 8256,
"text": "Loose coupling is promoted with minimal effort and least intrusive mechanism."
},
{
"code": null,
"e": 8412,
"s": 8334,
"text": "Loose coupling is promoted with minimal effort and least intrusive mechanism."
},
{
"code": null,
"e": 8485,
"s": 8412,
"text": "IOC containers support eager instantiation and lazy loading of services."
},
{
"code": null,
"e": 8558,
"s": 8485,
"text": "IOC containers support eager instantiation and lazy loading of services."
},
{
"code": null,
"e": 8917,
"s": 8558,
"text": "Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules."
},
{
"code": null,
"e": 9163,
"s": 8917,
"text": "The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application."
},
{
"code": null,
"e": 9203,
"s": 9163,
"text": "There are two types of IoC containers −"
},
{
"code": null,
"e": 9409,
"s": 9203,
"text": "Bean Factory container − This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications"
},
{
"code": null,
"e": 9615,
"s": 9409,
"text": "Bean Factory container − This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications"
},
{
"code": null,
"e": 9860,
"s": 9615,
"text": "Spring ApplicationContext Container − This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners."
},
{
"code": null,
"e": 10105,
"s": 9860,
"text": "Spring ApplicationContext Container − This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners."
},
{
"code": null,
"e": 10313,
"s": 10105,
"text": "The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application."
},
{
"code": null,
"e": 10383,
"s": 10313,
"text": "The three commonly used implementation of 'Application Context' are −"
},
{
"code": null,
"e": 10579,
"s": 10383,
"text": "FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor."
},
{
"code": null,
"e": 10775,
"s": 10579,
"text": "FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor."
},
{
"code": null,
"e": 11052,
"s": 10775,
"text": "ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH."
},
{
"code": null,
"e": 11329,
"s": 11052,
"text": "ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH."
},
{
"code": null,
"e": 11451,
"s": 11329,
"text": "WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application."
},
{
"code": null,
"e": 11573,
"s": 11451,
"text": "WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application."
},
{
"code": null,
"e": 11613,
"s": 11573,
"text": "Following are some of the differences −"
},
{
"code": null,
"e": 11725,
"s": 11613,
"text": "Application contexts provide a means for resolving text messages, including support for i18n of those messages."
},
{
"code": null,
"e": 11837,
"s": 11725,
"text": "Application contexts provide a means for resolving text messages, including support for i18n of those messages."
},
{
"code": null,
"e": 11920,
"s": 11837,
"text": "Application contexts provide a generic way to load file resources, such as images."
},
{
"code": null,
"e": 12003,
"s": 11920,
"text": "Application contexts provide a generic way to load file resources, such as images."
},
{
"code": null,
"e": 12086,
"s": 12003,
"text": "Application contexts can publish events to beans that are registered as listeners."
},
{
"code": null,
"e": 12169,
"s": 12086,
"text": "Application contexts can publish events to beans that are registered as listeners."
},
{
"code": null,
"e": 12360,
"s": 12169,
"text": "Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context."
},
{
"code": null,
"e": 12551,
"s": 12360,
"text": "Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context."
},
{
"code": null,
"e": 12697,
"s": 12551,
"text": "The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable."
},
{
"code": null,
"e": 12843,
"s": 12697,
"text": "The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable."
},
{
"code": null,
"e": 13210,
"s": 12843,
"text": "The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions."
},
{
"code": null,
"e": 13344,
"s": 13210,
"text": "The bean definition contains the information called configuration metadata which is needed for the container to know the followings −"
},
{
"code": null,
"e": 13365,
"s": 13344,
"text": "How to create a bean"
},
{
"code": null,
"e": 13390,
"s": 13365,
"text": "Bean's lifecycle details"
},
{
"code": null,
"e": 13410,
"s": 13390,
"text": "Bean's dependencies"
},
{
"code": null,
"e": 13514,
"s": 13410,
"text": "There are following three important methods to provide configuration metadata to the Spring Container −"
},
{
"code": null,
"e": 13544,
"s": 13514,
"text": "XML based configuration file."
},
{
"code": null,
"e": 13575,
"s": 13544,
"text": "Annotation-based configuration"
},
{
"code": null,
"e": 13600,
"s": 13575,
"text": "Java-based configuration"
},
{
"code": null,
"e": 13630,
"s": 13600,
"text": "Check the following example −"
},
{
"code": null,
"e": 14077,
"s": 13630,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 14468,
"s": 14077,
"text": "When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton."
},
{
"code": null,
"e": 14598,
"s": 14468,
"text": "The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext."
},
{
"code": null,
"e": 14689,
"s": 14598,
"text": "singleton − This scopes the bean definition to a single instance per Spring IoC container."
},
{
"code": null,
"e": 14780,
"s": 14689,
"text": "singleton − This scopes the bean definition to a single instance per Spring IoC container."
},
{
"code": null,
"e": 14869,
"s": 14780,
"text": "prototype − This scopes a single bean definition to have any number of object instances."
},
{
"code": null,
"e": 14958,
"s": 14869,
"text": "prototype − This scopes a single bean definition to have any number of object instances."
},
{
"code": null,
"e": 15086,
"s": 14958,
"text": "request − This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext."
},
{
"code": null,
"e": 15214,
"s": 15086,
"text": "request − This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext."
},
{
"code": null,
"e": 15342,
"s": 15214,
"text": "session − This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext."
},
{
"code": null,
"e": 15470,
"s": 15342,
"text": "session − This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext."
},
{
"code": null,
"e": 15611,
"s": 15470,
"text": "global-session − This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext."
},
{
"code": null,
"e": 15752,
"s": 15611,
"text": "global-session − This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext."
},
{
"code": null,
"e": 15813,
"s": 15752,
"text": "The default scope of bean is Singleton for Spring framework."
},
{
"code": null,
"e": 15874,
"s": 15813,
"text": "No, singleton beans are not thread-safe in Spring framework."
},
{
"code": null,
"e": 15928,
"s": 15874,
"text": "Following is sequence of a bean lifecycle in Spring −"
},
{
"code": null,
"e": 16043,
"s": 15928,
"text": "Instantiate − First the spring container finds the bean's definition from the XML file and instantiates the bean.."
},
{
"code": null,
"e": 16158,
"s": 16043,
"text": "Instantiate − First the spring container finds the bean's definition from the XML file and instantiates the bean.."
},
{
"code": null,
"e": 16288,
"s": 16158,
"text": "Populate properties − Using the dependency injection, spring populates all of the properties as specified in the bean definition."
},
{
"code": null,
"e": 16418,
"s": 16288,
"text": "Populate properties − Using the dependency injection, spring populates all of the properties as specified in the bean definition."
},
{
"code": null,
"e": 16536,
"s": 16418,
"text": "Set Bean Name − If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method."
},
{
"code": null,
"e": 16654,
"s": 16536,
"text": "Set Bean Name − If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method."
},
{
"code": null,
"e": 16778,
"s": 16654,
"text": "Set Bean factory − If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method."
},
{
"code": null,
"e": 16902,
"s": 16778,
"text": "Set Bean factory − If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method."
},
{
"code": null,
"e": 17081,
"s": 16902,
"text": "Pre Initialization − Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method."
},
{
"code": null,
"e": 17260,
"s": 17081,
"text": "Pre Initialization − Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method."
},
{
"code": null,
"e": 17447,
"s": 17260,
"text": "Initialize beans − If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called."
},
{
"code": null,
"e": 17634,
"s": 17447,
"text": "Initialize beans − If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called."
},
{
"code": null,
"e": 17781,
"s": 17634,
"text": "Post Initialization − If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called."
},
{
"code": null,
"e": 17928,
"s": 17781,
"text": "Post Initialization − If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called."
},
{
"code": null,
"e": 17992,
"s": 17928,
"text": "Ready to use − Now the bean is ready to use by the application."
},
{
"code": null,
"e": 18056,
"s": 17992,
"text": "Ready to use − Now the bean is ready to use by the application."
},
{
"code": null,
"e": 18142,
"s": 18056,
"text": "Destroy − If the bean implements DisposableBean , it will call the destroy() method ."
},
{
"code": null,
"e": 18228,
"s": 18142,
"text": "Destroy − If the bean implements DisposableBean , it will call the destroy() method ."
},
{
"code": null,
"e": 18540,
"s": 18228,
"text": "A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes."
},
{
"code": null,
"e": 18625,
"s": 18540,
"text": "Spring offers four types of collection configuration elements which are as follows −"
},
{
"code": null,
"e": 18709,
"s": 18625,
"text": "<list> − This helps in wiring i.e. injecting a list of values, allowing duplicates."
},
{
"code": null,
"e": 18793,
"s": 18709,
"text": "<list> − This helps in wiring i.e. injecting a list of values, allowing duplicates."
},
{
"code": null,
"e": 18866,
"s": 18793,
"text": "<set> − This helps in wiring a set of values but without any duplicates."
},
{
"code": null,
"e": 18939,
"s": 18866,
"text": "<set> − This helps in wiring a set of values but without any duplicates."
},
{
"code": null,
"e": 19048,
"s": 18939,
"text": "<map> − This can be used to inject a collection of name-value pairs where name and value can be of any type."
},
{
"code": null,
"e": 19157,
"s": 19048,
"text": "<map> − This can be used to inject a collection of name-value pairs where name and value can be of any type."
},
{
"code": null,
"e": 19270,
"s": 19157,
"text": "<props> −\tThis can be used to inject a collection of name-value pairs where the name and value are both Strings."
},
{
"code": null,
"e": 19383,
"s": 19270,
"text": "<props> −\tThis can be used to inject a collection of name-value pairs where the name and value are both Strings."
},
{
"code": null,
"e": 19679,
"s": 19383,
"text": "The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements."
},
{
"code": null,
"e": 19815,
"s": 19679,
"text": "The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection −"
},
{
"code": null,
"e": 20041,
"s": 19815,
"text": "no − This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter."
},
{
"code": null,
"e": 20267,
"s": 20041,
"text": "no − This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter."
},
{
"code": null,
"e": 20550,
"s": 20267,
"text": "byName − Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file."
},
{
"code": null,
"e": 20833,
"s": 20550,
"text": "byName − Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file."
},
{
"code": null,
"e": 21190,
"s": 20833,
"text": "byType − Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown."
},
{
"code": null,
"e": 21547,
"s": 21190,
"text": "byType − Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown."
},
{
"code": null,
"e": 21732,
"s": 21547,
"text": "constructor − Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised."
},
{
"code": null,
"e": 21917,
"s": 21732,
"text": "constructor − Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised."
},
{
"code": null,
"e": 22045,
"s": 21917,
"text": "autodetect − Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType."
},
{
"code": null,
"e": 22173,
"s": 22045,
"text": "autodetect − Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType."
},
{
"code": null,
"e": 22205,
"s": 22173,
"text": "Limitations of autowiring are −"
},
{
"code": null,
"e": 22352,
"s": 22205,
"text": "Overriding possibility − You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring."
},
{
"code": null,
"e": 22499,
"s": 22352,
"text": "Overriding possibility − You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring."
},
{
"code": null,
"e": 22612,
"s": 22499,
"text": "Primitive data types − You cannot autowire so-called simple properties such as primitives, Strings, and Classes."
},
{
"code": null,
"e": 22725,
"s": 22612,
"text": "Primitive data types − You cannot autowire so-called simple properties such as primitives, Strings, and Classes."
},
{
"code": null,
"e": 22836,
"s": 22725,
"text": "Confusing nature − Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring."
},
{
"code": null,
"e": 22947,
"s": 22836,
"text": "Confusing nature − Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring."
},
{
"code": null,
"e": 22952,
"s": 22947,
"text": "Yes."
},
{
"code": null,
"e": 23321,
"s": 22952,
"text": "An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration."
},
{
"code": null,
"e": 23544,
"s": 23321,
"text": "Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>. "
},
{
"code": null,
"e": 23832,
"s": 23544,
"text": "This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated."
},
{
"code": null,
"e": 24128,
"s": 23832,
"text": "This annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments."
},
{
"code": null,
"e": 24396,
"s": 24128,
"text": "There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired. "
},
{
"code": null,
"e": 24502,
"s": 24396,
"text": "Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations."
},
{
"code": null,
"e": 24591,
"s": 24502,
"text": "@PostConstruct − This annotation can be used as an alternate of initialization callback."
},
{
"code": null,
"e": 24680,
"s": 24591,
"text": "@PostConstruct − This annotation can be used as an alternate of initialization callback."
},
{
"code": null,
"e": 24763,
"s": 24680,
"text": "@PreDestroy − This annotation can be used as an alternate of destruction callback."
},
{
"code": null,
"e": 24846,
"s": 24763,
"text": "@PreDestroy − This annotation can be used as an alternate of destruction callback."
},
{
"code": null,
"e": 25079,
"s": 24846,
"text": "@Resource − This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics."
},
{
"code": null,
"e": 25312,
"s": 25079,
"text": "@Resource − This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics."
},
{
"code": null,
"e": 25460,
"s": 25312,
"text": "Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations."
},
{
"code": null,
"e": 25760,
"s": 25460,
"text": "For example: Annotation @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. "
},
{
"code": null,
"e": 26033,
"s": 25760,
"text": "Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified."
},
{
"code": null,
"e": 26081,
"s": 26033,
"text": "Spring provides the following standard events −"
},
{
"code": null,
"e": 26294,
"s": 26081,
"text": "ContextRefreshedEvent − This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface. "
},
{
"code": null,
"e": 26507,
"s": 26294,
"text": "ContextRefreshedEvent − This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface. "
},
{
"code": null,
"e": 26765,
"s": 26507,
"text": "ContextStartedEvent − This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event."
},
{
"code": null,
"e": 27023,
"s": 26765,
"text": "ContextStartedEvent − This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event."
},
{
"code": null,
"e": 27244,
"s": 27023,
"text": "ContextStoppedEvent − This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event."
},
{
"code": null,
"e": 27465,
"s": 27244,
"text": "ContextStoppedEvent − This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event."
},
{
"code": null,
"e": 27701,
"s": 27465,
"text": "ContextClosedEvent − This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted."
},
{
"code": null,
"e": 27937,
"s": 27701,
"text": "ContextClosedEvent − This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted."
},
{
"code": null,
"e": 28046,
"s": 27937,
"text": "RequestHandledEvent − This is a web-specific event telling all beans that an HTTP request has been serviced."
},
{
"code": null,
"e": 28155,
"s": 28046,
"text": "RequestHandledEvent − This is a web-specific event telling all beans that an HTTP request has been serviced."
},
{
"code": null,
"e": 28536,
"s": 28155,
"text": "A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style)."
},
{
"code": null,
"e": 28738,
"s": 28536,
"text": "Concern − Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns."
},
{
"code": null,
"e": 29015,
"s": 28738,
"text": "Cross-cutting concern − It's a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns."
},
{
"code": null,
"e": 29211,
"s": 29015,
"text": "This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework."
},
{
"code": null,
"e": 29389,
"s": 29211,
"text": "This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework."
},
{
"code": null,
"e": 29557,
"s": 29389,
"text": "This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples."
},
{
"code": null,
"e": 29638,
"s": 29557,
"text": "An introduction allows you to add new methods or attributes to existing classes."
},
{
"code": null,
"e": 29770,
"s": 29638,
"text": "The object being advised by one or more aspects, this object will always be a proxy object. Also referred to as the advised object."
},
{
"code": null,
"e": 29881,
"s": 29770,
"text": "Weaving is the process of linking aspects with other application types or objects to create an advised object."
},
{
"code": null,
"e": 29944,
"s": 29881,
"text": "Weaving can be done at compile time, load time, or at runtime."
},
{
"code": null,
"e": 30012,
"s": 29944,
"text": "Spring aspects can work with five kinds of advice mentioned below −"
},
{
"code": null,
"e": 30063,
"s": 30012,
"text": "before − Run advice before the a method execution."
},
{
"code": null,
"e": 30114,
"s": 30063,
"text": "before − Run advice before the a method execution."
},
{
"code": null,
"e": 30189,
"s": 30114,
"text": "after − Run advice after the a method execution regardless of its outcome."
},
{
"code": null,
"e": 30264,
"s": 30189,
"text": "after − Run advice after the a method execution regardless of its outcome."
},
{
"code": null,
"e": 30361,
"s": 30264,
"text": "after-returning − Run advice after the a method execution only if method completes successfully."
},
{
"code": null,
"e": 30458,
"s": 30361,
"text": "after-returning − Run advice after the a method execution only if method completes successfully."
},
{
"code": null,
"e": 30562,
"s": 30458,
"text": "after-throwing − Run advice after the a method execution only if method exits by throwing an exception."
},
{
"code": null,
"e": 30666,
"s": 30562,
"text": "after-throwing − Run advice after the a method execution only if method exits by throwing an exception."
},
{
"code": null,
"e": 30734,
"s": 30666,
"text": "around − Run advice before and after the advised method is invoked."
},
{
"code": null,
"e": 30802,
"s": 30734,
"text": "around − Run advice before and after the advised method is invoked."
},
{
"code": null,
"e": 30884,
"s": 30802,
"text": "Aspects are implemented using regular classes along with XML based configuration."
},
{
"code": null,
"e": 30991,
"s": 30884,
"text": "@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations."
},
{
"code": null,
"e": 31112,
"s": 30991,
"text": "JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate."
},
{
"code": null,
"e": 31535,
"s": 31112,
"text": "With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling. "
},
{
"code": null,
"e": 31589,
"s": 31535,
"text": "Spring supports two types of transaction management −"
},
{
"code": null,
"e": 31775,
"s": 31589,
"text": "Programmatic transaction management − This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain."
},
{
"code": null,
"e": 31961,
"s": 31775,
"text": "Programmatic transaction management − This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain."
},
{
"code": null,
"e": 32149,
"s": 31961,
"text": "Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions."
},
{
"code": null,
"e": 32337,
"s": 32149,
"text": "Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions."
},
{
"code": null,
"e": 32557,
"s": 32337,
"text": "Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. "
},
{
"code": null,
"e": 32907,
"s": 32557,
"text": "The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements."
},
{
"code": null,
"e": 33026,
"s": 32907,
"text": "The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. "
},
{
"code": null,
"e": 33303,
"s": 33026,
"text": "The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with."
},
{
"code": null,
"e": 33372,
"s": 33303,
"text": "Following are some of the advantages of Spring MVC over Struts MVC −"
},
{
"code": null,
"e": 33505,
"s": 33372,
"text": "Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance."
},
{
"code": null,
"e": 33638,
"s": 33505,
"text": "Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance."
},
{
"code": null,
"e": 33764,
"s": 33638,
"text": "Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests."
},
{
"code": null,
"e": 33890,
"s": 33764,
"text": "Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests."
},
{
"code": null,
"e": 34091,
"s": 33890,
"text": "Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface."
},
{
"code": null,
"e": 34292,
"s": 34091,
"text": "Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface."
},
{
"code": null,
"e": 34396,
"s": 34292,
"text": "In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy."
},
{
"code": null,
"e": 34500,
"s": 34396,
"text": "In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy."
},
{
"code": null,
"e": 34683,
"s": 34500,
"text": "Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet."
},
{
"code": null,
"e": 34866,
"s": 34683,
"text": "Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet."
},
{
"code": null,
"e": 35026,
"s": 34866,
"text": "Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend."
},
{
"code": null,
"e": 35186,
"s": 35026,
"text": "Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend."
},
{
"code": null,
"e": 35362,
"s": 35186,
"text": "In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality."
},
{
"code": null,
"e": 35538,
"s": 35362,
"text": "In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality."
},
{
"code": null,
"e": 35840,
"s": 35538,
"text": "With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database."
},
{
"code": null,
"e": 36142,
"s": 35840,
"text": "With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database."
},
{
"code": null,
"e": 36474,
"s": 36142,
"text": "Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers."
},
{
"code": null,
"e": 36662,
"s": 36474,
"text": "The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API."
},
{
"code": null,
"e": 36768,
"s": 36662,
"text": "@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method."
},
{
"code": null,
"e": 36822,
"s": 36768,
"text": "There are two ways to access hibernate using spring −"
},
{
"code": null,
"e": 36883,
"s": 36822,
"text": "Inversion of Control with a Hibernate Template and Callback."
},
{
"code": null,
"e": 36944,
"s": 36883,
"text": "Inversion of Control with a Hibernate Template and Callback."
},
{
"code": null,
"e": 37012,
"s": 36944,
"text": "Extending HibernateDAOSupport and Applying an AOP Interceptor node."
},
{
"code": null,
"e": 37080,
"s": 37012,
"text": "Extending HibernateDAOSupport and Applying an AOP Interceptor node."
},
{
"code": null,
"e": 37118,
"s": 37080,
"text": "Spring supports the following ORM's −"
},
{
"code": null,
"e": 37128,
"s": 37118,
"text": "Hibernate"
},
{
"code": null,
"e": 37135,
"s": 37128,
"text": "iBatis"
},
{
"code": null,
"e": 37162,
"s": 37135,
"text": "JPA (Java Persistence API)"
},
{
"code": null,
"e": 37170,
"s": 37162,
"text": "TopLink"
},
{
"code": null,
"e": 37194,
"s": 37170,
"text": "JDO (Java Data Objects)"
},
{
"code": null,
"e": 37198,
"s": 37194,
"text": "OJB"
},
{
"code": null,
"e": 37485,
"s": 37198,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
}
] |
How to use Vision API from Google Cloud
|
22 Oct, 2021
The Vision API from Google Cloud has multiple functionalities. In this article, we will see how to access them. Before using the API, you need to open a Google Developer account, create a Virtual Machine instance and set up an API. For that, refer to this article. We need to download the following packages –
pip install google.cloud.vision
The various services performed by Google Vision API are –
It can detect multiple faces in an image and express the emotional state of the faces.Save the ‘credentials.json’ file in the same folder as the .py file with the Python code. We need to save the path of ‘credentials.json’ (C:\Users\...) as ‘GOOGLE_APPLICATION_CREDENTIALS’ which has been done in line-7 of the following code.
Python3
import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as pltfrom matplotlib import patches as pch os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.face_detection(image = image)faces = response.face_annotations possibility = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY') a = plt.imread(f)fig, ax = plt.subplots(1)ax.imshow(a) for face in faces: print('Possibility of anger: {}'.format(possibility[face.anger_likelihood])) print('Possibility of joy: {}'.format(possibility[face.joy_likelihood])) print('Possibility of surprise: {}'.format(possibility[face.surprise_likelihood])) print('Possibility of sorrow: {}'.format(possibility[face.sorrow_likelihood])) vertices = ([(vertex.x, vertex.y) for vertex in face.bounding_poly.vertices]) print('Vertices covering face: {}\n\n'.format(vertices)) rect = pch.Rectangle(vertices[0], (vertices[1][0] - vertices[0][0]), (vertices[2][1] - vertices[0][1]), linewidth = 1, edgecolor ='r', facecolor ='none') ax.add_patch(rect) print('Confidence in Detection: {}%'.format( face.detection_confidence * 100)) plt.show()
The above code detects multiple faces in a picture and determines the emotional expressions exhibited by the faces and whether any of the faces is wearing a headgear. It also returns the vertices which form a rectangle around the individual faces. Lastly, it prints the percentage of surety with which the conclusions were drawn.For example, when the following image is given as input –
Output:
Possibility of anger: VERY_UNLIKELY
Possibility of joy: VERY_LIKELY
Possibility of surprise: VERY_UNLIKELY
Possibility of sorrow: VERY_UNLIKELY
Vertices covering face: [(115, 84), (308, 84), (308, 309), (115, 309)]
Confidence in Detection: 99.93739128112793%
Detects popular product logos present in an image.
Python3
import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as plt os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.logo_detection(image = image)logos = response.logo_annotations a = plt.imread(f)plt.imshow(a) for logo in logos: print(logo.description)
The above code detects the logos of various companies in an image and prints the name of the companies. For example, when given the following image:
Output:
hp
Detects broad sets of categories in an image, which ranges from animals, trees to vehicles, buildings etc.
Python3
import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as plt os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.label_detection(image = image)labels = response.label_annotations a = plt.imread(f)plt.imshow(a) for label in labels: print(label.description)
All possible labels or tags are attached to an image. For example, when the following image is given as input:
Output:
Street
Neighbourhood
Café
Coffeehouse
Sitting
Leisure
Tourism
Restaurant
Street performance
City
Detects famous landmarks (mostly man-made) within an image.
Python3
import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as plt os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.landmark_detection(image = image)landmarks = response.landmark_annotations a = plt.imread(f)plt.imshow(a) for landmark in landmarks: print(landmark.description) for location in landmark.locations: print('Latitude: {}, Longitude: {}'.format( location.lat_lng.latitude, location.lat_lng.longitude))
The above code recognizes any famous landmark and also returns the location of that landmark using latitudes and longitudes. For example, when we input the following picture:
Output:
Victoria Memorial
Latitude: 22.545121, Longitude: 88.342781
For more information, visit the Google Vision API documentation here.
surindertarika1234
simmytarika5
Natural-language-processing
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Fuzzy Logic | Introduction
Mounting a Volume Inside Docker Container
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 340,
"s": 28,
"text": "The Vision API from Google Cloud has multiple functionalities. In this article, we will see how to access them. Before using the API, you need to open a Google Developer account, create a Virtual Machine instance and set up an API. For that, refer to this article. We need to download the following packages – "
},
{
"code": null,
"e": 372,
"s": 340,
"text": "pip install google.cloud.vision"
},
{
"code": null,
"e": 431,
"s": 372,
"text": "The various services performed by Google Vision API are – "
},
{
"code": null,
"e": 759,
"s": 431,
"text": "It can detect multiple faces in an image and express the emotional state of the faces.Save the ‘credentials.json’ file in the same folder as the .py file with the Python code. We need to save the path of ‘credentials.json’ (C:\\Users\\...) as ‘GOOGLE_APPLICATION_CREDENTIALS’ which has been done in line-7 of the following code. "
},
{
"code": null,
"e": 767,
"s": 759,
"text": "Python3"
},
{
"code": "import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as pltfrom matplotlib import patches as pch os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.face_detection(image = image)faces = response.face_annotations possibility = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY') a = plt.imread(f)fig, ax = plt.subplots(1)ax.imshow(a) for face in faces: print('Possibility of anger: {}'.format(possibility[face.anger_likelihood])) print('Possibility of joy: {}'.format(possibility[face.joy_likelihood])) print('Possibility of surprise: {}'.format(possibility[face.surprise_likelihood])) print('Possibility of sorrow: {}'.format(possibility[face.sorrow_likelihood])) vertices = ([(vertex.x, vertex.y) for vertex in face.bounding_poly.vertices]) print('Vertices covering face: {}\\n\\n'.format(vertices)) rect = pch.Rectangle(vertices[0], (vertices[1][0] - vertices[0][0]), (vertices[2][1] - vertices[0][1]), linewidth = 1, edgecolor ='r', facecolor ='none') ax.add_patch(rect) print('Confidence in Detection: {}%'.format( face.detection_confidence * 100)) plt.show()",
"e": 2249,
"s": 767,
"text": null
},
{
"code": null,
"e": 2638,
"s": 2249,
"text": "The above code detects multiple faces in a picture and determines the emotional expressions exhibited by the faces and whether any of the faces is wearing a headgear. It also returns the vertices which form a rectangle around the individual faces. Lastly, it prints the percentage of surety with which the conclusions were drawn.For example, when the following image is given as input – "
},
{
"code": null,
"e": 2648,
"s": 2638,
"text": "Output: "
},
{
"code": null,
"e": 2908,
"s": 2648,
"text": "Possibility of anger: VERY_UNLIKELY\nPossibility of joy: VERY_LIKELY\nPossibility of surprise: VERY_UNLIKELY\nPossibility of sorrow: VERY_UNLIKELY\nVertices covering face: [(115, 84), (308, 84), (308, 309), (115, 309)]\n\nConfidence in Detection: 99.93739128112793%"
},
{
"code": null,
"e": 2965,
"s": 2912,
"text": "Detects popular product logos present in an image. "
},
{
"code": null,
"e": 2973,
"s": 2965,
"text": "Python3"
},
{
"code": "import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as plt os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.logo_detection(image = image)logos = response.logo_annotations a = plt.imread(f)plt.imshow(a) for logo in logos: print(logo.description)",
"e": 3482,
"s": 2973,
"text": null
},
{
"code": null,
"e": 3633,
"s": 3482,
"text": "The above code detects the logos of various companies in an image and prints the name of the companies. For example, when given the following image: "
},
{
"code": null,
"e": 3643,
"s": 3633,
"text": "Output: "
},
{
"code": null,
"e": 3646,
"s": 3643,
"text": "hp"
},
{
"code": null,
"e": 3756,
"s": 3648,
"text": "Detects broad sets of categories in an image, which ranges from animals, trees to vehicles, buildings etc. "
},
{
"code": null,
"e": 3764,
"s": 3756,
"text": "Python3"
},
{
"code": "import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as plt os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.label_detection(image = image)labels = response.label_annotations a = plt.imread(f)plt.imshow(a) for label in labels: print(label.description)",
"e": 4278,
"s": 3764,
"text": null
},
{
"code": null,
"e": 4391,
"s": 4278,
"text": "All possible labels or tags are attached to an image. For example, when the following image is given as input: "
},
{
"code": null,
"e": 4401,
"s": 4391,
"text": "Output: "
},
{
"code": null,
"e": 4499,
"s": 4401,
"text": "Street\nNeighbourhood\nCafé\nCoffeehouse\nSitting\nLeisure\nTourism\nRestaurant\nStreet performance\nCity"
},
{
"code": null,
"e": 4562,
"s": 4501,
"text": "Detects famous landmarks (mostly man-made) within an image. "
},
{
"code": null,
"e": 4570,
"s": 4562,
"text": "Python3"
},
{
"code": "import osimport iofrom google.cloud import visionfrom matplotlib import pyplot as plt os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.curdir, 'credentials.json') client = vision.ImageAnnotatorClient() f = 'image_filename.jpg'with io.open(f, 'rb') as image: content = image.read() image = vision.types.Image(content = content)response = client.landmark_detection(image = image)landmarks = response.landmark_annotations a = plt.imread(f)plt.imshow(a) for landmark in landmarks: print(landmark.description) for location in landmark.locations: print('Latitude: {}, Longitude: {}'.format( location.lat_lng.latitude, location.lat_lng.longitude))",
"e": 5261,
"s": 4570,
"text": null
},
{
"code": null,
"e": 5438,
"s": 5261,
"text": "The above code recognizes any famous landmark and also returns the location of that landmark using latitudes and longitudes. For example, when we input the following picture: "
},
{
"code": null,
"e": 5448,
"s": 5438,
"text": "Output: "
},
{
"code": null,
"e": 5508,
"s": 5448,
"text": "Victoria Memorial\nLatitude: 22.545121, Longitude: 88.342781"
},
{
"code": null,
"e": 5579,
"s": 5508,
"text": "For more information, visit the Google Vision API documentation here. "
},
{
"code": null,
"e": 5598,
"s": 5579,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5611,
"s": 5598,
"text": "simmytarika5"
},
{
"code": null,
"e": 5639,
"s": 5611,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 5665,
"s": 5639,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 5763,
"s": 5665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5799,
"s": 5763,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5843,
"s": 5799,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 5879,
"s": 5843,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 5903,
"s": 5879,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 5938,
"s": 5903,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 5979,
"s": 5938,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 6027,
"s": 5979,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 6068,
"s": 6027,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 6095,
"s": 6068,
"text": "Fuzzy Logic | Introduction"
}
] |
How to create Neumorphism Effect using HTML and CSS ?
|
14 Jan, 2021
Neumorphism (neomorphism) is a modern way of styling web-elements of any web-page and providing a 3D effect. This animation effect can be easily generated by using HTML and CSS. Box-shadow property of CSS can be used to implemented Neumorphism. It is used to add a dark shadow to one side and a light shadow to the other side of the given element.
HTML code: In this section we will make the layout of the box.
index.html:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"></head> <body> <div class="container"> <div class="neu-1"> GeeksForGeeks</div> <div class="neu-2">GeeksForGeeks</div> </div></body> </html>
CSS code: In this section, we will use some CSS properties to design the box.
index.css:
HTML
<style> *{ padding: 0; margin: 0; box-sizing: border-box; } .container { height: 100vh; display: flex; flex-direction: row; justify-content: center; align-items: center; padding: 30px; background: #dde1e7; } .neu-1 { height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: -3px -3px 7px #ffffffb2, 3px 3px 5px rgba(94, 104, 121, 0.945); } .neu-2 { margin: 50px; height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: inset -3px -3px 7px #ffffffb0, inset 3px 3px 5px rgba(94, 104, 121, 0.692); }</style>
Complete Code: In this section, we will combine the above two section to create a Neumorphism using HTML and CSS.
HTML
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <style> *{ padding: 0; margin: 0; box-sizing: border-box; } .container { height: 100vh; display: flex; flex-direction: row; justify-content: center; align-items: center; padding: 30px; background: #dde1e7; } .neu-1 { height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: -3px -3px 7px #ffffffb2, 3px 3px 5px rgba(94, 104, 121, 0.945); } .neu-2 { margin: 50px; height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: inset -3px -3px 7px #ffffffb0, inset 3px 3px 5px rgba(94, 104, 121, 0.692); } </style> </head> <body> <div class="container"> <div class="neu-1"> GeeksForGeeks</div> <div class="neu-2">GeeksForGeeks</div> </div></body> </html>
Output:
CSS-Misc
HTML-Misc
Technical Scripter 2020
CSS
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jan, 2021"
},
{
"code": null,
"e": 401,
"s": 52,
"text": "Neumorphism (neomorphism) is a modern way of styling web-elements of any web-page and providing a 3D effect. This animation effect can be easily generated by using HTML and CSS. Box-shadow property of CSS can be used to implemented Neumorphism. It is used to add a dark shadow to one side and a light shadow to the other side of the given element. "
},
{
"code": null,
"e": 464,
"s": 401,
"text": "HTML code: In this section we will make the layout of the box."
},
{
"code": null,
"e": 476,
"s": 464,
"text": "index.html:"
},
{
"code": null,
"e": 481,
"s": 476,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"></head> <body> <div class=\"container\"> <div class=\"neu-1\"> GeeksForGeeks</div> <div class=\"neu-2\">GeeksForGeeks</div> </div></body> </html>",
"e": 708,
"s": 481,
"text": null
},
{
"code": null,
"e": 786,
"s": 708,
"text": "CSS code: In this section, we will use some CSS properties to design the box."
},
{
"code": null,
"e": 797,
"s": 786,
"text": "index.css:"
},
{
"code": null,
"e": 802,
"s": 797,
"text": "HTML"
},
{
"code": "<style> *{ padding: 0; margin: 0; box-sizing: border-box; } .container { height: 100vh; display: flex; flex-direction: row; justify-content: center; align-items: center; padding: 30px; background: #dde1e7; } .neu-1 { height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: -3px -3px 7px #ffffffb2, 3px 3px 5px rgba(94, 104, 121, 0.945); } .neu-2 { margin: 50px; height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: inset -3px -3px 7px #ffffffb0, inset 3px 3px 5px rgba(94, 104, 121, 0.692); }</style>",
"e": 1454,
"s": 802,
"text": null
},
{
"code": null,
"e": 1568,
"s": 1454,
"text": "Complete Code: In this section, we will combine the above two section to create a Neumorphism using HTML and CSS."
},
{
"code": null,
"e": 1573,
"s": 1568,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <style> *{ padding: 0; margin: 0; box-sizing: border-box; } .container { height: 100vh; display: flex; flex-direction: row; justify-content: center; align-items: center; padding: 30px; background: #dde1e7; } .neu-1 { height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: -3px -3px 7px #ffffffb2, 3px 3px 5px rgba(94, 104, 121, 0.945); } .neu-2 { margin: 50px; height: 300px; width: 300px; background: #dde1e7; border-radius: 6px; box-shadow: inset -3px -3px 7px #ffffffb0, inset 3px 3px 5px rgba(94, 104, 121, 0.692); } </style> </head> <body> <div class=\"container\"> <div class=\"neu-1\"> GeeksForGeeks</div> <div class=\"neu-2\">GeeksForGeeks</div> </div></body> </html>",
"e": 2577,
"s": 1573,
"text": null
},
{
"code": null,
"e": 2585,
"s": 2577,
"text": "Output:"
},
{
"code": null,
"e": 2594,
"s": 2585,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2604,
"s": 2594,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2628,
"s": 2604,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2632,
"s": 2628,
"text": "CSS"
},
{
"code": null,
"e": 2637,
"s": 2632,
"text": "HTML"
},
{
"code": null,
"e": 2656,
"s": 2637,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2673,
"s": 2656,
"text": "Web Technologies"
},
{
"code": null,
"e": 2700,
"s": 2673,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2705,
"s": 2700,
"text": "HTML"
}
] |
w command in Linux with Examples
|
27 May, 2019
w command in Linux is used to show who is logged on and what they are doing. This command shows the information about the users currently on the machine and their processes. The header shows, in this order, the current time, how long the system has been running, how many users are currently logged on, and the system load averages for the past 1, 5, and 15 minutes. The following entries are displayed for each user: login name, the tty name, the remote host, login time, idle time, JCPU, PCPU, and the command line of their current process. The JCPU time is the time used by all processes attached to the tty. It does not include past background jobs but does include currently running background jobs. The PCPU time is the time used by the current process, named in the “what” field.
Syntax:
w [options] user [...]
Example:
Options:
w -h: This option don’t print the header.w -h
w -h
w -u: This option will ignore the username while figuring out the current process and cpu times.w -u
w -u
w -s : This option uses the short format. It will not print the login time, JCPU or PCPU times.w -s
w -s
w -f : This option will toggle printing the from (remote hostname) field. The default as released is from field which not be printed. Although your system administrator or your distribution maintainer may have compiled a version in which the from field is shown by default.w -f
w -f
w –help: This option will display help message and exit.w --help
w --help
w -i : This option will display IP address instead of hostname for from field.w -i
w -i
w -V : This option will display version information.w -V
w -V
w -o : This option will print blank space for idle times less than one minute.w -o
w -o
w user : This option will show information about the specified user only.w user
w user
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 815,
"s": 28,
"text": "w command in Linux is used to show who is logged on and what they are doing. This command shows the information about the users currently on the machine and their processes. The header shows, in this order, the current time, how long the system has been running, how many users are currently logged on, and the system load averages for the past 1, 5, and 15 minutes. The following entries are displayed for each user: login name, the tty name, the remote host, login time, idle time, JCPU, PCPU, and the command line of their current process. The JCPU time is the time used by all processes attached to the tty. It does not include past background jobs but does include currently running background jobs. The PCPU time is the time used by the current process, named in the “what” field."
},
{
"code": null,
"e": 823,
"s": 815,
"text": "Syntax:"
},
{
"code": null,
"e": 847,
"s": 823,
"text": "w [options] user [...]\n"
},
{
"code": null,
"e": 856,
"s": 847,
"text": "Example:"
},
{
"code": null,
"e": 865,
"s": 856,
"text": "Options:"
},
{
"code": null,
"e": 911,
"s": 865,
"text": "w -h: This option don’t print the header.w -h"
},
{
"code": null,
"e": 916,
"s": 911,
"text": "w -h"
},
{
"code": null,
"e": 1017,
"s": 916,
"text": "w -u: This option will ignore the username while figuring out the current process and cpu times.w -u"
},
{
"code": null,
"e": 1022,
"s": 1017,
"text": "w -u"
},
{
"code": null,
"e": 1122,
"s": 1022,
"text": "w -s : This option uses the short format. It will not print the login time, JCPU or PCPU times.w -s"
},
{
"code": null,
"e": 1127,
"s": 1122,
"text": "w -s"
},
{
"code": null,
"e": 1405,
"s": 1127,
"text": "w -f : This option will toggle printing the from (remote hostname) field. The default as released is from field which not be printed. Although your system administrator or your distribution maintainer may have compiled a version in which the from field is shown by default.w -f"
},
{
"code": null,
"e": 1410,
"s": 1405,
"text": "w -f"
},
{
"code": null,
"e": 1475,
"s": 1410,
"text": "w –help: This option will display help message and exit.w --help"
},
{
"code": null,
"e": 1484,
"s": 1475,
"text": "w --help"
},
{
"code": null,
"e": 1567,
"s": 1484,
"text": "w -i : This option will display IP address instead of hostname for from field.w -i"
},
{
"code": null,
"e": 1572,
"s": 1567,
"text": "w -i"
},
{
"code": null,
"e": 1629,
"s": 1572,
"text": "w -V : This option will display version information.w -V"
},
{
"code": null,
"e": 1634,
"s": 1629,
"text": "w -V"
},
{
"code": null,
"e": 1717,
"s": 1634,
"text": "w -o : This option will print blank space for idle times less than one minute.w -o"
},
{
"code": null,
"e": 1722,
"s": 1717,
"text": "w -o"
},
{
"code": null,
"e": 1802,
"s": 1722,
"text": "w user : This option will show information about the specified user only.w user"
},
{
"code": null,
"e": 1809,
"s": 1802,
"text": "w user"
},
{
"code": null,
"e": 1823,
"s": 1809,
"text": "linux-command"
},
{
"code": null,
"e": 1845,
"s": 1823,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 1856,
"s": 1845,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1954,
"s": 1856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1980,
"s": 1954,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2015,
"s": 1980,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2052,
"s": 2015,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2081,
"s": 2052,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2120,
"s": 2081,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2157,
"s": 2120,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2197,
"s": 2157,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2231,
"s": 2197,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2268,
"s": 2231,
"text": "chmod command in Linux with examples"
}
] |
PyQt5 | How to get the text of Push Button ?
|
19 Aug, 2021
In this article, we will see how to get the text of push button. When we create push button we set some text to it which will be visible on main window, we can retrieve the text using text method.
Syntax : button.text()Argument : It takes no argument.Return : It returns string.
Code :
Python3
# importing librariesfrom PyQt5.QtWidgets import *from 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 a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # getting text in button text = button.text() # creating label to print text label = QLabel(text, self) label.move(200, 200) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
sagar0719kumar
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 225,
"s": 28,
"text": "In this article, we will see how to get the text of push button. When we create push button we set some text to it which will be visible on main window, we can retrieve the text using text method."
},
{
"code": null,
"e": 307,
"s": 225,
"text": "Syntax : button.text()Argument : It takes no argument.Return : It returns string."
},
{
"code": null,
"e": 316,
"s": 307,
"text": "Code : "
},
{
"code": null,
"e": 324,
"s": 316,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from 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 a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # getting text in button text = button.text() # creating label to print text label = QLabel(text, self) label.move(200, 200) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1432,
"s": 324,
"text": null
},
{
"code": null,
"e": 1442,
"s": 1432,
"text": "Output : "
},
{
"code": null,
"e": 1459,
"s": 1444,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1470,
"s": 1459,
"text": "Python-gui"
},
{
"code": null,
"e": 1482,
"s": 1470,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1489,
"s": 1482,
"text": "Python"
}
] |
sum command in Linux with Examples
|
27 May, 2019
sum command in Linux is used to find checksum and count the blocks in a file. Basically, this command is used to show the checksum and block count for each specified file. When no file is specified then it will read the standard input.
Syntax:
sum [OPTION]... [FILE]...
Example: It will ask for the input of the file we want to calculate the checksum. In the following example, we are calculating the checksum for myfile.txt.
Options:
sum -r: This option will use BSD sum algorithm, use 1K blocks.Example:sum -r myfile.txt
Example:
sum -r myfile.txt
sum -s: This option will use System V sum algorithm, use 512 bytes blocks.Example:sum -s myfile.txt
Example:
sum -s myfile.txt
sum –help : This option displays the help text and exit.sum --help
sum --help
sum –version : This option will show the version information and exit.sum --version
sum --version
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 288,
"s": 52,
"text": "sum command in Linux is used to find checksum and count the blocks in a file. Basically, this command is used to show the checksum and block count for each specified file. When no file is specified then it will read the standard input."
},
{
"code": null,
"e": 296,
"s": 288,
"text": "Syntax:"
},
{
"code": null,
"e": 323,
"s": 296,
"text": "sum [OPTION]... [FILE]...\n"
},
{
"code": null,
"e": 479,
"s": 323,
"text": "Example: It will ask for the input of the file we want to calculate the checksum. In the following example, we are calculating the checksum for myfile.txt."
},
{
"code": null,
"e": 488,
"s": 479,
"text": "Options:"
},
{
"code": null,
"e": 576,
"s": 488,
"text": "sum -r: This option will use BSD sum algorithm, use 1K blocks.Example:sum -r myfile.txt"
},
{
"code": null,
"e": 585,
"s": 576,
"text": "Example:"
},
{
"code": null,
"e": 603,
"s": 585,
"text": "sum -r myfile.txt"
},
{
"code": null,
"e": 704,
"s": 603,
"text": "sum -s: This option will use System V sum algorithm, use 512 bytes blocks.Example:sum -s myfile.txt "
},
{
"code": null,
"e": 713,
"s": 704,
"text": "Example:"
},
{
"code": null,
"e": 732,
"s": 713,
"text": "sum -s myfile.txt "
},
{
"code": null,
"e": 799,
"s": 732,
"text": "sum –help : This option displays the help text and exit.sum --help"
},
{
"code": null,
"e": 810,
"s": 799,
"text": "sum --help"
},
{
"code": null,
"e": 894,
"s": 810,
"text": "sum –version : This option will show the version information and exit.sum --version"
},
{
"code": null,
"e": 908,
"s": 894,
"text": "sum --version"
},
{
"code": null,
"e": 922,
"s": 908,
"text": "linux-command"
},
{
"code": null,
"e": 942,
"s": 922,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 953,
"s": 942,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1051,
"s": 953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1077,
"s": 1051,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1112,
"s": 1077,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1149,
"s": 1112,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1178,
"s": 1149,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1215,
"s": 1178,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1249,
"s": 1215,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1286,
"s": 1249,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1326,
"s": 1286,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 1365,
"s": 1326,
"text": "Introduction to Linux Operating System"
}
] |
Splitting string into array of substrings in Julia – split() and rsplit() Method
|
26 Mar, 2020
The split() is an inbuilt function in julia which is used to split a specified string into an array of substrings on occurrences of the specified delimiter(s).
Syntax:split(str::AbstractString, dlm; limit::Integer, keepempty::Bool)orsplit(str::AbstractString; limit::Integer, keepempty::Bool)
Parameters:
str::AbstractString: Specified string.
Dlm: Specified delimiter.
Below arguments are optional:
limit::Integer: It is the maximum size of the result. It’s default value is zero (0).
keepempty::Bool: It says whether the empty fields should be kept in the result or not. Its Default value is false.
Returns: It returns an array of substrings of the specified string.
Example:
# Julia program to illustrate # the use of String split() method # Splitting of the specified stringsPrintln(split("Gee.ks", "."))Println(split("Geeks, for, Geeks", ", "))Println(split("GFG-gfg", "-", limit = 1))Println(split("GFG-gfg", "-", limit = 2))
Output:
rsplit() method works exactly like split() method but starting from the end of the string.
Syntax:rsplit(s::AbstractString; limit::Integer, keepempty::Bool)orrsplit(s::AbstractString, chars; limit::Integer, keepempty::Bool)
Parameters:
str::AbstractString: Specified string.
chars: Specified characters.
Below arguments are optional:
limit::Integer: It is the maximum size of the result. It’s default value is zero (0).
keepempty::Bool: It says whether the empty fields should be kept in the result or not. Its Default value is false.
Returns: It returns an array of substrings of the specified string.
Example:
# Julia program to illustrate # the use of String rsplit() method # Splitting of the specified stringsPrintln(rsplit("Gee.ks", "."))Println(rsplit("Geeks, for, Geeks", ", "))Println(rsplit("GFG-gfg", "-"; limit = 1))Println(rsplit("GFG-gfg", "-"; limit = 2))Println(rsplit("G-F-G-g-f-g", "-"; limit = 4))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 188,
"s": 28,
"text": "The split() is an inbuilt function in julia which is used to split a specified string into an array of substrings on occurrences of the specified delimiter(s)."
},
{
"code": null,
"e": 321,
"s": 188,
"text": "Syntax:split(str::AbstractString, dlm; limit::Integer, keepempty::Bool)orsplit(str::AbstractString; limit::Integer, keepempty::Bool)"
},
{
"code": null,
"e": 333,
"s": 321,
"text": "Parameters:"
},
{
"code": null,
"e": 372,
"s": 333,
"text": "str::AbstractString: Specified string."
},
{
"code": null,
"e": 398,
"s": 372,
"text": "Dlm: Specified delimiter."
},
{
"code": null,
"e": 428,
"s": 398,
"text": "Below arguments are optional:"
},
{
"code": null,
"e": 514,
"s": 428,
"text": "limit::Integer: It is the maximum size of the result. It’s default value is zero (0)."
},
{
"code": null,
"e": 629,
"s": 514,
"text": "keepempty::Bool: It says whether the empty fields should be kept in the result or not. Its Default value is false."
},
{
"code": null,
"e": 697,
"s": 629,
"text": "Returns: It returns an array of substrings of the specified string."
},
{
"code": null,
"e": 706,
"s": 697,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of String split() method # Splitting of the specified stringsPrintln(split(\"Gee.ks\", \".\"))Println(split(\"Geeks, for, Geeks\", \", \"))Println(split(\"GFG-gfg\", \"-\", limit = 1))Println(split(\"GFG-gfg\", \"-\", limit = 2))",
"e": 962,
"s": 706,
"text": null
},
{
"code": null,
"e": 970,
"s": 962,
"text": "Output:"
},
{
"code": null,
"e": 1061,
"s": 970,
"text": "rsplit() method works exactly like split() method but starting from the end of the string."
},
{
"code": null,
"e": 1194,
"s": 1061,
"text": "Syntax:rsplit(s::AbstractString; limit::Integer, keepempty::Bool)orrsplit(s::AbstractString, chars; limit::Integer, keepempty::Bool)"
},
{
"code": null,
"e": 1206,
"s": 1194,
"text": "Parameters:"
},
{
"code": null,
"e": 1245,
"s": 1206,
"text": "str::AbstractString: Specified string."
},
{
"code": null,
"e": 1274,
"s": 1245,
"text": "chars: Specified characters."
},
{
"code": null,
"e": 1304,
"s": 1274,
"text": "Below arguments are optional:"
},
{
"code": null,
"e": 1390,
"s": 1304,
"text": "limit::Integer: It is the maximum size of the result. It’s default value is zero (0)."
},
{
"code": null,
"e": 1505,
"s": 1390,
"text": "keepempty::Bool: It says whether the empty fields should be kept in the result or not. Its Default value is false."
},
{
"code": null,
"e": 1573,
"s": 1505,
"text": "Returns: It returns an array of substrings of the specified string."
},
{
"code": null,
"e": 1582,
"s": 1573,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of String rsplit() method # Splitting of the specified stringsPrintln(rsplit(\"Gee.ks\", \".\"))Println(rsplit(\"Geeks, for, Geeks\", \", \"))Println(rsplit(\"GFG-gfg\", \"-\"; limit = 1))Println(rsplit(\"GFG-gfg\", \"-\"; limit = 2))Println(rsplit(\"G-F-G-g-f-g\", \"-\"; limit = 4))",
"e": 1889,
"s": 1582,
"text": null
},
{
"code": null,
"e": 1897,
"s": 1889,
"text": "Output:"
},
{
"code": null,
"e": 1903,
"s": 1897,
"text": "Julia"
}
] |
Design a Loan Calculator using JavaScript
|
23 Feb, 2021
The Loan Calculator can be used to calculate monthly EMI of the loan by taking the total amount, months to repay and the rate of interest.
Approach: The approach is very simple, we will take 3 inputs from user i.e. amount (total loan amount), rate (the rate of interest) and months (number o months to repay). Using these three, we can calculate the total amount. At last we will display the total amount.
Formula:
interest = (amount * (rate * 0.01))/months;
total = ((amount/months) + interest);
Using HTML we are designing the simple structure and giving style using CSS(internal CSS). At the time of input we are calling calculate() function and displaying the result. The calculate() function takes input using HTML attribute named – onchange (the onchange attribute fires the moment when the value of the element is changed).
Prerequisite: Basics concepts of HTML, CSS and JavaScript.
Implementation: We will make two separate files i.e. HTML and JavaScript and link the JavaScript file within HTML file.
HTML – (index.html)
JavaScript – (app.js)
HTML File:
index.html
<!DOCTYPE html><html lang="en"> <head> <title>Loan Calculator</title> <style> body { background-color: yellow; font-family: 'Trebuchet MS'; } h1 { font-size: 35px; } h1 { font-size: 21px; margin-top: 20px; } .calculator { width: 400px; height: 450px; background-color: black; position: absolute; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); padding: 20px 0px 0px 100px; border-radius: 50px; color: white; } input { padding: 7px; width: 70%; margin-top: 7px; } </style></head> <body> <div class="calculator"> <h1>Loan Calculator</h1> <!-- Calling Calculate function defined in app.js --> <p>Amount (₹) : <input id="amount" type="number" onchange="Calculate()"> </p> <p>Interest Rate : <input id="rate" type="number" onchange="Calculate()"> </p> <p>Months to Pay : <input id="months" type="number" onchange="Calculate()"> </p> <h2 id="total"></h2> </div> <script src="app.js"></script></body> </html>
JavaScript File:
app.js
function Calculate() { // Extracting value in the amount // section in the variable const amount = document.querySelector("#amount").value; // Extracting value in the interest // rate section in the variable const rate = document.querySelector("#rate").value; // Extracting value in the months // section in the variable const months = document.querySelector("#months").value; // Calculating interest per month const interest = (amount * (rate * 0.01)) / months; // Calculating total payment const total = ((amount / months) + interest).toFixed(2); document.querySelector("#total") .innerHTML = "EMI : (₹)" + total;}
Outputs:
CSS-Questions
HTML-Questions
JavaScript-Questions
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 193,
"s": 54,
"text": "The Loan Calculator can be used to calculate monthly EMI of the loan by taking the total amount, months to repay and the rate of interest."
},
{
"code": null,
"e": 460,
"s": 193,
"text": "Approach: The approach is very simple, we will take 3 inputs from user i.e. amount (total loan amount), rate (the rate of interest) and months (number o months to repay). Using these three, we can calculate the total amount. At last we will display the total amount."
},
{
"code": null,
"e": 469,
"s": 460,
"text": "Formula:"
},
{
"code": null,
"e": 551,
"s": 469,
"text": "interest = (amount * (rate * 0.01))/months;\ntotal = ((amount/months) + interest);"
},
{
"code": null,
"e": 885,
"s": 551,
"text": "Using HTML we are designing the simple structure and giving style using CSS(internal CSS). At the time of input we are calling calculate() function and displaying the result. The calculate() function takes input using HTML attribute named – onchange (the onchange attribute fires the moment when the value of the element is changed)."
},
{
"code": null,
"e": 944,
"s": 885,
"text": "Prerequisite: Basics concepts of HTML, CSS and JavaScript."
},
{
"code": null,
"e": 1064,
"s": 944,
"text": "Implementation: We will make two separate files i.e. HTML and JavaScript and link the JavaScript file within HTML file."
},
{
"code": null,
"e": 1084,
"s": 1064,
"text": "HTML – (index.html)"
},
{
"code": null,
"e": 1106,
"s": 1084,
"text": "JavaScript – (app.js)"
},
{
"code": null,
"e": 1117,
"s": 1106,
"text": "HTML File:"
},
{
"code": null,
"e": 1128,
"s": 1117,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Loan Calculator</title> <style> body { background-color: yellow; font-family: 'Trebuchet MS'; } h1 { font-size: 35px; } h1 { font-size: 21px; margin-top: 20px; } .calculator { width: 400px; height: 450px; background-color: black; position: absolute; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); padding: 20px 0px 0px 100px; border-radius: 50px; color: white; } input { padding: 7px; width: 70%; margin-top: 7px; } </style></head> <body> <div class=\"calculator\"> <h1>Loan Calculator</h1> <!-- Calling Calculate function defined in app.js --> <p>Amount (₹) : <input id=\"amount\" type=\"number\" onchange=\"Calculate()\"> </p> <p>Interest Rate : <input id=\"rate\" type=\"number\" onchange=\"Calculate()\"> </p> <p>Months to Pay : <input id=\"months\" type=\"number\" onchange=\"Calculate()\"> </p> <h2 id=\"total\"></h2> </div> <script src=\"app.js\"></script></body> </html>",
"e": 2527,
"s": 1128,
"text": null
},
{
"code": null,
"e": 2544,
"s": 2527,
"text": "JavaScript File:"
},
{
"code": null,
"e": 2551,
"s": 2544,
"text": "app.js"
},
{
"code": "function Calculate() { // Extracting value in the amount // section in the variable const amount = document.querySelector(\"#amount\").value; // Extracting value in the interest // rate section in the variable const rate = document.querySelector(\"#rate\").value; // Extracting value in the months // section in the variable const months = document.querySelector(\"#months\").value; // Calculating interest per month const interest = (amount * (rate * 0.01)) / months; // Calculating total payment const total = ((amount / months) + interest).toFixed(2); document.querySelector(\"#total\") .innerHTML = \"EMI : (₹)\" + total;} ",
"e": 3237,
"s": 2551,
"text": null
},
{
"code": null,
"e": 3246,
"s": 3237,
"text": "Outputs:"
},
{
"code": null,
"e": 3260,
"s": 3246,
"text": "CSS-Questions"
},
{
"code": null,
"e": 3275,
"s": 3260,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3296,
"s": 3275,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3320,
"s": 3296,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3324,
"s": 3320,
"text": "CSS"
},
{
"code": null,
"e": 3329,
"s": 3324,
"text": "HTML"
},
{
"code": null,
"e": 3340,
"s": 3329,
"text": "JavaScript"
},
{
"code": null,
"e": 3359,
"s": 3340,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3376,
"s": 3359,
"text": "Web Technologies"
},
{
"code": null,
"e": 3381,
"s": 3376,
"text": "HTML"
},
{
"code": null,
"e": 3479,
"s": 3381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3518,
"s": 3479,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3555,
"s": 3518,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3594,
"s": 3555,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3658,
"s": 3594,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 3719,
"s": 3658,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3743,
"s": 3719,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3796,
"s": 3743,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3856,
"s": 3796,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3917,
"s": 3856,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Lodash _.chunk() Method
|
28 Jun, 2022
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc. Lodash.chunk() function is used to break the array in to small chunks. Each chunk is an array of size as given.
Syntax:
chunk(array, size)
Parameters: This function accepts two parameters as mentioned above and describe below.
array: An array to be processed by chunk function.
size: This describes the size of chunk.
Return Value: It returns the array of chunks that is also an array
Note: Please install lodash module by using command npm install lodash before using the code given below.
Example 1:
Javascript
// Requiring the lodash module// in the scriptconst _ = require("lodash");let arr = [1, 2, 3, 4, 5, 6]; // Making chunks of size 1console.log(_.chunk(arr, 1))
Output:
OUTPUT EXAMPLE 1
Example 2: The size of chunk can be varied and array of different data type can be used with chunk function.
Javascript
// Requiring the lodash module// in the scriptlet _ = require("lodash");let arr = [1, 2, 3, 4, 5, 6, "a", "b", "c", "d"];console.log("Before: ", arr) // Making chunks of size 3console.log("After: ", _.chunk(arr, 3))
Output:
Example 3: Using array of array with chunk.
Javascript
// Requiring the lodash module// in the script.let lodash = require("lodash");let arr = [ [1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 1, 2]]; console.log("Before: ", arr)console.log("After: ", lodash.chunk(arr, 2))
Output:
Example 4: Using array of Objects with chunk.
Javascript
let lodash = require("lodash");let arr = [ { "a": 1, "b": 2, "c": 3 }, { "d": 1, "e": 2, "f": 3 }, { "d": 1, "e": 2, "f": 3 }]; // Array before breaking in to chunksconsole.log("Before: ", arr) // Printing the first element// of the chunk as size 1console.log("After: ", lodash.chunk(arr, 1)[0]);
Output :
mohamedyasser99999
JavaScript-Lodash
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
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": "\n28 Jun, 2022"
},
{
"code": null,
"e": 279,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc. Lodash.chunk() function is used to break the array in to small chunks. Each chunk is an array of size as given."
},
{
"code": null,
"e": 287,
"s": 279,
"text": "Syntax:"
},
{
"code": null,
"e": 306,
"s": 287,
"text": "chunk(array, size)"
},
{
"code": null,
"e": 394,
"s": 306,
"text": "Parameters: This function accepts two parameters as mentioned above and describe below."
},
{
"code": null,
"e": 445,
"s": 394,
"text": "array: An array to be processed by chunk function."
},
{
"code": null,
"e": 485,
"s": 445,
"text": "size: This describes the size of chunk."
},
{
"code": null,
"e": 552,
"s": 485,
"text": "Return Value: It returns the array of chunks that is also an array"
},
{
"code": null,
"e": 658,
"s": 552,
"text": "Note: Please install lodash module by using command npm install lodash before using the code given below."
},
{
"code": null,
"e": 669,
"s": 658,
"text": "Example 1:"
},
{
"code": null,
"e": 680,
"s": 669,
"text": "Javascript"
},
{
"code": "// Requiring the lodash module// in the scriptconst _ = require(\"lodash\");let arr = [1, 2, 3, 4, 5, 6]; // Making chunks of size 1console.log(_.chunk(arr, 1))",
"e": 839,
"s": 680,
"text": null
},
{
"code": null,
"e": 848,
"s": 839,
"text": "Output: "
},
{
"code": null,
"e": 865,
"s": 848,
"text": "OUTPUT EXAMPLE 1"
},
{
"code": null,
"e": 974,
"s": 865,
"text": "Example 2: The size of chunk can be varied and array of different data type can be used with chunk function."
},
{
"code": null,
"e": 985,
"s": 974,
"text": "Javascript"
},
{
"code": "// Requiring the lodash module// in the scriptlet _ = require(\"lodash\");let arr = [1, 2, 3, 4, 5, 6, \"a\", \"b\", \"c\", \"d\"];console.log(\"Before: \", arr) // Making chunks of size 3console.log(\"After: \", _.chunk(arr, 3))",
"e": 1208,
"s": 985,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1208,
"text": "Output: "
},
{
"code": null,
"e": 1261,
"s": 1217,
"text": "Example 3: Using array of array with chunk."
},
{
"code": null,
"e": 1272,
"s": 1261,
"text": "Javascript"
},
{
"code": "// Requiring the lodash module// in the script.let lodash = require(\"lodash\");let arr = [ [1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 1, 2]]; console.log(\"Before: \", arr)console.log(\"After: \", lodash.chunk(arr, 2))",
"e": 1488,
"s": 1272,
"text": null
},
{
"code": null,
"e": 1497,
"s": 1488,
"text": "Output: "
},
{
"code": null,
"e": 1543,
"s": 1497,
"text": "Example 4: Using array of Objects with chunk."
},
{
"code": null,
"e": 1554,
"s": 1543,
"text": "Javascript"
},
{
"code": "let lodash = require(\"lodash\");let arr = [ { \"a\": 1, \"b\": 2, \"c\": 3 }, { \"d\": 1, \"e\": 2, \"f\": 3 }, { \"d\": 1, \"e\": 2, \"f\": 3 }]; // Array before breaking in to chunksconsole.log(\"Before: \", arr) // Printing the first element// of the chunk as size 1console.log(\"After: \", lodash.chunk(arr, 1)[0]);",
"e": 1863,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1872,
"s": 1863,
"text": "Output :"
},
{
"code": null,
"e": 1891,
"s": 1872,
"text": "mohamedyasser99999"
},
{
"code": null,
"e": 1909,
"s": 1891,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1920,
"s": 1909,
"text": "JavaScript"
},
{
"code": null,
"e": 1937,
"s": 1920,
"text": "Web Technologies"
},
{
"code": null,
"e": 2035,
"s": 1937,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2096,
"s": 2035,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2168,
"s": 2096,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2208,
"s": 2168,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2261,
"s": 2208,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2302,
"s": 2261,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2335,
"s": 2302,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2397,
"s": 2335,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2458,
"s": 2397,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2508,
"s": 2458,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Lodash _.sample() Method
|
10 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.sample() method will provide a random element from collection.
Syntax:
_.sample(collection)
Parameters: This method accepts single parameter as mentioned above and described below:
collection: This parameter holds the collection to sample.
Return Value: This method is used to return the random element.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array var array1 = ([ 3, 6, 9, 12 ]); // Use of _.sample() methodlet gfg = _.sample(array1); // Printing original Array console.log("original array1: ", array1) // Printing the output console.log(gfg);
Output:
original array1: [ 3, 6, 9, 12 ]
12
Example 2:
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array var array1 = ([ 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']); // Use of _.sample() methodlet gfg = _.sample(array1); // Printing original Array console.log("original array1: ", array1) // Printing the output console.log(gfg);
Output:
original array1: [ 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
mon
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2020"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.sample() method will provide a random element from collection."
},
{
"code": null,
"e": 255,
"s": 247,
"text": "Syntax:"
},
{
"code": null,
"e": 276,
"s": 255,
"text": "_.sample(collection)"
},
{
"code": null,
"e": 365,
"s": 276,
"text": "Parameters: This method accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 424,
"s": 365,
"text": "collection: This parameter holds the collection to sample."
},
{
"code": null,
"e": 488,
"s": 424,
"text": "Return Value: This method is used to return the random element."
},
{
"code": null,
"e": 583,
"s": 488,
"text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file."
},
{
"code": null,
"e": 594,
"s": 583,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var array1 = ([ 3, 6, 9, 12 ]); // Use of _.sample() methodlet gfg = _.sample(array1); // Printing original Array console.log(\"original array1: \", array1) // Printing the output console.log(gfg);",
"e": 880,
"s": 594,
"text": null
},
{
"code": null,
"e": 888,
"s": 880,
"text": "Output:"
},
{
"code": null,
"e": 925,
"s": 888,
"text": "original array1: [ 3, 6, 9, 12 ]\n12\n"
},
{
"code": null,
"e": 936,
"s": 925,
"text": "Example 2:"
},
{
"code": null,
"e": 947,
"s": 936,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var array1 = ([ 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']); // Use of _.sample() methodlet gfg = _.sample(array1); // Printing original Array console.log(\"original array1: \", array1) // Printing the output console.log(gfg);",
"e": 1272,
"s": 947,
"text": null
},
{
"code": null,
"e": 1280,
"s": 1272,
"text": "Output:"
},
{
"code": null,
"e": 1353,
"s": 1280,
"text": "original array1: [ 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']\nmon\n"
},
{
"code": null,
"e": 1460,
"s": 1353,
"text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 1478,
"s": 1460,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1489,
"s": 1478,
"text": "JavaScript"
},
{
"code": null,
"e": 1506,
"s": 1489,
"text": "Web Technologies"
}
] |
String Pairs | TCS Codevita 2020
|
15 Jan, 2021
One person hands over the list of digits to Mr. String, But Mr. String understands only strings. Within strings also he understands only vowels. Mr. String needs your help to find the total number of pairs which add up to a certain digit D.
The rules to calculate digit D are as follows:
Take all digits and convert them into their textual representation.
Next, sum up the number of vowels i.e. {a, e, i, o, u} from all textual representation. This sum is digit D.
Now, once digit D is known find out all unordered pairs of numbers in input whose sum is equal to D.
Problem Statement: Given an array arr[] consisting of N ( 1 ≤ N ≤ 100 ) integers, the task is to convert each array element ( 1 ≤ arr[i] ≤ 100 ) into their respective textual representations and print the lowercase representation of the count of all possible pairs from the array whose sum is equal to the total count of vowels present in their textual representation. If the count exceeds 100 print “greater 100”.Note: For the number 100, convert it to textual representation as hundred and not as one hundred.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}Output: oneExplanation:1 -> one -> o, e (2 vowels)2 -> two -> o (1 vowel)3 -> three -> e, e (2 vowels)4 -> four -> o, u (2 vowels)5 -> five – > i, e (2 vowels)The total count of vowels in their textual representations = {2 + 1 + 2 + 2 + 2} = 9.Now from the given array, only a single unordered pair {4, 5} sums up to 9. Therefore, the count is 1. Hence, the required output is “one“.
Input: arr[] = {7, 4, 2, }Output: zeroExplanation:7 -> seven -> e, e (2 vowels)4 -> four -> o, u (2 vowels)2 -> two -> o (1 vowel)The total count of vowels in their textual representation = {2 + 2 + 1} = 5.Now from the given array, no pair exists which adds up to 5. Therefore, the answer is “zero“.
Approach: Follow the steps below to solve this problem:
Store textual representation of each number from 0 to 100 in a Map.
Traverse the array and for each array element, convert each digit to its textual form.
Find the total number of vowels present in the textual forms and store it in a variable, say D.
Now, generate all the pairs possible from the given array.
Count all the pairs with sum D.
If the count exceeds 100, “greater 100”. Otherwise, print its textual form.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approach # Import combinationsfrom itertools import combinations # Function to check the string pairdef string_pair(n, nums): words = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 21: 'twentyone', 22: 'twentytwo', 23: 'twentythree', 24: 'twentyfour', 25: 'twentyfive', 26: 'twentysix', 27: 'twentyseven', 28: 'twentyeight', 29: 'twentynine', 30: 'thirty', 31: 'thirtyone', 32: 'thirtytwo', 33: 'thirtythree', 34: 'thirtyfour', 35: 'thirtyfive', 36: 'thirtysix', 37: 'thirtyseven', 38: 'thirtyeight', 39: 'thirtynine', 40: 'forty', 41: 'fortyone', 42: 'fortytwo', 43: 'fortythree', 44: 'fortyfour', 45: 'fortyfive', 46: 'fortysix', 47: 'fortyseven', 48: 'fortyeight', 49: 'fortynine', 50: 'fifty', 51: 'fiftyone', 52: 'fiftytwo', 53: 'fiftythree', 54: 'fiftyfour', 55: 'fiftyfive', 56: 'fiftysix', 57: 'fiftyseven', 58: 'fiftyeight', 59: 'fiftynine', 60: 'sixty', 61: 'sixtyone', 62: 'sixtytwo', 63: 'sixtythree', 64: 'sixtyfour', 65: 'sixtyfive', 66: 'sixtysix', 67: 'sixtyseven', 68: 'sixtyeight', 69: 'sixtynine', 70: 'seventy', 71: 'seventyone', 72: 'seventytwo', 73: 'seventythree', 74: 'seventyfour', 75: 'seventyfive', 76: 'seventysix', 77: 'seventyseven', 78: 'seventyeight', 79: 'seventynine', 80: 'eighty', 81: 'eightyone', 82: 'eightytwo', 83: 'eightythree', 84: 'eightyfour', 85: 'eightyfive', 86: 'eightysix', 87: 'eightyseven', 88: 'eightyeight', 89: 'eightynine', 90: 'ninety', 91: 'ninetyone', 92: 'ninetytwo', 93: 'ninetythree', 94: 'ninetyfour', 95: 'ninetyfive', 96: 'ninetysix', 97: 'ninetyseven', 98: 'ninetyeight', 99: 'ninetynine', 100: 'hundred'} # Map the string into list of integers nums = list(map(int, nums)) # Temporary lists to store list of count ls, ls1 = [], [] count, c = 0, 0 # Iterating through the numbers for i in nums: # Stores the textual form of i s = words[i] for a in range(len(s)): vo = ['a', 'e', 'i', 'o', 'u'] # If it is vowel if s[a] in vo: # Increment the count count += 1 # Append the count ls.append(count) count = 0 # D = sum(count of vowels) d = sum(ls) for i in nums: # To find the numbers less # that or equal to d, # so as to find the pair sum if i <= d: # Append the numbers # whose sum can be d ls1.append(i) # Stores all possible pairs in the # form of an object list of tuples comb = combinations(ls1, 2) # Traverse all the pairs for i in list(comb): # If sum is equal to d if sum(i) == d: # Increment count c += 1 # If count exceeds 100 if c <= 100: print(words) # Otherwise else: print("greater 100") # Driver Codeif __name__ == '__main__': # Given Length of string n = 5 # Given array arr = [1, 2, 3, 4, 5] # Function Call string_pair(n, arr)
one
Time Complexity: O(N2)Auxiliary Space: O(N2)
interview-preparation
TCS-coding-questions
vowel-consonant
Hash
Mathematical
Strings
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hash Functions and list/types of Hash functions
File Organization in DBMS | Set 2
Applications of Hashing
Find the length of largest subarray with 0 sum
What is Hashing | A Complete Tutorial
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
Operators in C / C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Jan, 2021"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "One person hands over the list of digits to Mr. String, But Mr. String understands only strings. Within strings also he understands only vowels. Mr. String needs your help to find the total number of pairs which add up to a certain digit D."
},
{
"code": null,
"e": 342,
"s": 295,
"text": "The rules to calculate digit D are as follows:"
},
{
"code": null,
"e": 410,
"s": 342,
"text": "Take all digits and convert them into their textual representation."
},
{
"code": null,
"e": 519,
"s": 410,
"text": "Next, sum up the number of vowels i.e. {a, e, i, o, u} from all textual representation. This sum is digit D."
},
{
"code": null,
"e": 621,
"s": 519,
"text": "Now, once digit D is known find out all unordered pairs of numbers in input whose sum is equal to D. "
},
{
"code": null,
"e": 1133,
"s": 621,
"text": "Problem Statement: Given an array arr[] consisting of N ( 1 ≤ N ≤ 100 ) integers, the task is to convert each array element ( 1 ≤ arr[i] ≤ 100 ) into their respective textual representations and print the lowercase representation of the count of all possible pairs from the array whose sum is equal to the total count of vowels present in their textual representation. If the count exceeds 100 print “greater 100”.Note: For the number 100, convert it to textual representation as hundred and not as one hundred."
},
{
"code": null,
"e": 1143,
"s": 1133,
"text": "Examples:"
},
{
"code": null,
"e": 1557,
"s": 1143,
"text": "Input: arr[] = {1, 2, 3, 4, 5}Output: oneExplanation:1 -> one -> o, e (2 vowels)2 -> two -> o (1 vowel)3 -> three -> e, e (2 vowels)4 -> four -> o, u (2 vowels)5 -> five – > i, e (2 vowels)The total count of vowels in their textual representations = {2 + 1 + 2 + 2 + 2} = 9.Now from the given array, only a single unordered pair {4, 5} sums up to 9. Therefore, the count is 1. Hence, the required output is “one“."
},
{
"code": null,
"e": 1857,
"s": 1557,
"text": "Input: arr[] = {7, 4, 2, }Output: zeroExplanation:7 -> seven -> e, e (2 vowels)4 -> four -> o, u (2 vowels)2 -> two -> o (1 vowel)The total count of vowels in their textual representation = {2 + 2 + 1} = 5.Now from the given array, no pair exists which adds up to 5. Therefore, the answer is “zero“."
},
{
"code": null,
"e": 1913,
"s": 1857,
"text": "Approach: Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 1981,
"s": 1913,
"text": "Store textual representation of each number from 0 to 100 in a Map."
},
{
"code": null,
"e": 2068,
"s": 1981,
"text": "Traverse the array and for each array element, convert each digit to its textual form."
},
{
"code": null,
"e": 2164,
"s": 2068,
"text": "Find the total number of vowels present in the textual forms and store it in a variable, say D."
},
{
"code": null,
"e": 2223,
"s": 2164,
"text": "Now, generate all the pairs possible from the given array."
},
{
"code": null,
"e": 2255,
"s": 2223,
"text": "Count all the pairs with sum D."
},
{
"code": null,
"e": 2331,
"s": 2255,
"text": "If the count exceeds 100, “greater 100”. Otherwise, print its textual form."
},
{
"code": null,
"e": 2382,
"s": 2331,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2390,
"s": 2382,
"text": "Python3"
},
{
"code": "# Python3 program for the above approach # Import combinationsfrom itertools import combinations # Function to check the string pairdef string_pair(n, nums): words = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 21: 'twentyone', 22: 'twentytwo', 23: 'twentythree', 24: 'twentyfour', 25: 'twentyfive', 26: 'twentysix', 27: 'twentyseven', 28: 'twentyeight', 29: 'twentynine', 30: 'thirty', 31: 'thirtyone', 32: 'thirtytwo', 33: 'thirtythree', 34: 'thirtyfour', 35: 'thirtyfive', 36: 'thirtysix', 37: 'thirtyseven', 38: 'thirtyeight', 39: 'thirtynine', 40: 'forty', 41: 'fortyone', 42: 'fortytwo', 43: 'fortythree', 44: 'fortyfour', 45: 'fortyfive', 46: 'fortysix', 47: 'fortyseven', 48: 'fortyeight', 49: 'fortynine', 50: 'fifty', 51: 'fiftyone', 52: 'fiftytwo', 53: 'fiftythree', 54: 'fiftyfour', 55: 'fiftyfive', 56: 'fiftysix', 57: 'fiftyseven', 58: 'fiftyeight', 59: 'fiftynine', 60: 'sixty', 61: 'sixtyone', 62: 'sixtytwo', 63: 'sixtythree', 64: 'sixtyfour', 65: 'sixtyfive', 66: 'sixtysix', 67: 'sixtyseven', 68: 'sixtyeight', 69: 'sixtynine', 70: 'seventy', 71: 'seventyone', 72: 'seventytwo', 73: 'seventythree', 74: 'seventyfour', 75: 'seventyfive', 76: 'seventysix', 77: 'seventyseven', 78: 'seventyeight', 79: 'seventynine', 80: 'eighty', 81: 'eightyone', 82: 'eightytwo', 83: 'eightythree', 84: 'eightyfour', 85: 'eightyfive', 86: 'eightysix', 87: 'eightyseven', 88: 'eightyeight', 89: 'eightynine', 90: 'ninety', 91: 'ninetyone', 92: 'ninetytwo', 93: 'ninetythree', 94: 'ninetyfour', 95: 'ninetyfive', 96: 'ninetysix', 97: 'ninetyseven', 98: 'ninetyeight', 99: 'ninetynine', 100: 'hundred'} # Map the string into list of integers nums = list(map(int, nums)) # Temporary lists to store list of count ls, ls1 = [], [] count, c = 0, 0 # Iterating through the numbers for i in nums: # Stores the textual form of i s = words[i] for a in range(len(s)): vo = ['a', 'e', 'i', 'o', 'u'] # If it is vowel if s[a] in vo: # Increment the count count += 1 # Append the count ls.append(count) count = 0 # D = sum(count of vowels) d = sum(ls) for i in nums: # To find the numbers less # that or equal to d, # so as to find the pair sum if i <= d: # Append the numbers # whose sum can be d ls1.append(i) # Stores all possible pairs in the # form of an object list of tuples comb = combinations(ls1, 2) # Traverse all the pairs for i in list(comb): # If sum is equal to d if sum(i) == d: # Increment count c += 1 # If count exceeds 100 if c <= 100: print(words) # Otherwise else: print(\"greater 100\") # Driver Codeif __name__ == '__main__': # Given Length of string n = 5 # Given array arr = [1, 2, 3, 4, 5] # Function Call string_pair(n, arr)",
"e": 5972,
"s": 2390,
"text": null
},
{
"code": null,
"e": 5977,
"s": 5972,
"text": "one\n"
},
{
"code": null,
"e": 6022,
"s": 5977,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 6044,
"s": 6022,
"text": "interview-preparation"
},
{
"code": null,
"e": 6065,
"s": 6044,
"text": "TCS-coding-questions"
},
{
"code": null,
"e": 6081,
"s": 6065,
"text": "vowel-consonant"
},
{
"code": null,
"e": 6086,
"s": 6081,
"text": "Hash"
},
{
"code": null,
"e": 6099,
"s": 6086,
"text": "Mathematical"
},
{
"code": null,
"e": 6107,
"s": 6099,
"text": "Strings"
},
{
"code": null,
"e": 6112,
"s": 6107,
"text": "Hash"
},
{
"code": null,
"e": 6120,
"s": 6112,
"text": "Strings"
},
{
"code": null,
"e": 6133,
"s": 6120,
"text": "Mathematical"
},
{
"code": null,
"e": 6231,
"s": 6133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6279,
"s": 6231,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 6313,
"s": 6279,
"text": "File Organization in DBMS | Set 2"
},
{
"code": null,
"e": 6337,
"s": 6313,
"text": "Applications of Hashing"
},
{
"code": null,
"e": 6384,
"s": 6337,
"text": "Find the length of largest subarray with 0 sum"
},
{
"code": null,
"e": 6422,
"s": 6384,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6452,
"s": 6422,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 6467,
"s": 6452,
"text": "C++ Data Types"
},
{
"code": null,
"e": 6510,
"s": 6467,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6570,
"s": 6510,
"text": "Write a program to print all permutations of a given string"
}
] |
Merging elements of two different arrays alternatively in third array
|
07 May, 2021
Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array.
Input : arr1[] = {1, 2, 3, 4, 5, 6}
arr2[] = {11, 22, 33, 44}
Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6}
Input : arr1[] = {1, 2, 3, 4, 5, 6, 7, 8}
arr2[] = {11, 22, 33, 44}
Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6, 7, 8}
We traverse both given arrays and one by one put their elements into combined array. After one of the arrays is exhausted, we put remaining elements of other array.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to merge two sorted arrays/#include<iostream>using namespace std; // Alternatively merge arr1[0..n1-1] and arr2[0..n2-1]// into arr3[0..n1+n2-1]void alternateMerge(int arr1[], int arr2[], int n1, int n2, int arr3[]){ int i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++];} // Driver codeint main(){ int arr1[] = {1, 3, 5, 7, 9, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 6, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int arr3[n1+n2]; alternateMerge(arr1, arr2, n1, n2, arr3); cout << "Array after merging" <<endl; for (int i=0; i < n1+n2; i++) cout << arr3[i] << " "; return 0;}
// Java program to merge two sorted arraysimport java.io.*; class GFG { // Alternatively merge arr1[0..n1-1] and // arr2[0..n2-1] into arr3[0..n1+n2-1] static void alternateMerge(int arr1[], int arr2[], int n1, int n2, int arr3[]) { int i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } // Driver code public static void main(String args[]) { int arr1[] = {1, 3, 5, 7, 9, 11}; int n1 = arr1.length; int arr2[] = {2, 4, 6, 8}; int n2 = arr2.length; int arr3[] = new int[n1+n2]; alternateMerge(arr1, arr2, n1, n2, arr3); System.out.println("Array after merging"); for (int i = 0; i < n1 + n2; i++) System.out.print( arr3[i] + " "); }} // This code is contributed// by Nikita Tiwari.
# Python3 program to merge two sorted arrays/ # Alternatively merge arr1[0..n1-1] and# arr2[0..n2-1] into arr3[0..n1 + n2-1]def alternateMerge(arr1, arr2, n1, n2, arr3) : i = 0; j = 0; k = 0 # Traverse both array while (i < n1 and j < n2) : arr3[k] = arr1[i] i += 1 k += 1 arr3[k] = arr2[j] j += 1 k += 1 # Store remaining elements of first array while (i < n1) : arr3[k] = arr1[i] i += 1 k += 1 # Store remaining elements of second array while (j < n2) : arr3[k] = arr2[j] k += 1 j += 1 # Driver codearr1 = [1, 3, 5, 7, 9, 11]n1 = len(arr1) arr2 = [2, 4, 6, 8]n2 = len(arr2) arr3= [0] *(n1 + n2)alternateMerge(arr1, arr2, n1, n2, arr3) print("Array after merging")for i in range(0, (n1 + n2)) : print(arr3[i] , end = " ") # This code is contributed by Nikita Tiwari.
// C# program to merge two sorted arraysusing System; class GFG { // Alternatively merge arr1[0..n1-1] // and arr2[0..n2-1] into arr3[0..n1+n2-1] static void alternateMerge(int []arr1, int []arr2, int n1, int n2, int []arr3) { int i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } // Driver code public static void Main() { int []arr1 = new int[]{1, 3, 5, 7, 9, 11}; int n1 = arr1.Length; int []arr2 = new int[]{2, 4, 6, 8}; int n2 = arr2.Length; int []arr3= new int[n1 + n2]; alternateMerge(arr1, arr2, n1, n2, arr3); Console.WriteLine("Array after merging"); for (int i = 0; i < n1+n2; i++) Console.Write(arr3[i] + " "); }} // This code is contributed by Sam007.
<?php// PHP program to merge two// sorted arrays // Alternatively merge arr1[0..n1-1]// and arr2[0..n2-1] into// arr3[0..n1+n2-1]function alternateMerge($arr1, $arr2, $n1, $n2){ $i = 0; $j = 0; $k = 0; $arr3 = array(); // Traverse both array while ($i < $n1 && $j < $n2) { $arr3[$k++] = $arr1[$i++]; $arr3[$k++] = $arr2[$j++]; } // Store remaining elements // of first array while ($i < $n1) $arr3[$k++] = $arr1[$i++]; // Store remaining elements // of second array while($j < $n2) $arr3[$k++] = $arr2[$j++]; echo "Array after merging"."\n"; for ($i = 0; $i < ($n1 + $n2); $i++) echo $arr3[$i] ." "; } // Driver Code $arr1 = array(1, 3, 5, 7, 9, 11); $n1 = count($arr1); $arr2 = array(2, 4, 6, 8); $n2 = count($arr2); alternateMerge($arr1, $arr2, $n1, $n2); // This code is contributed by Sam007?>
<script> // Javascript program to merge two sorted arrays/ // Alternatively merge arr1[0..n1-1] and arr2[0..n2-1]// into arr3[0..n1+n2-1]function alternateMerge(arr1, arr2, n1, n2, arr3){ let i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++];} // Driver code let arr1 = [1, 3, 5, 7, 9, 11]; let n1 = arr1.length; let arr2 = [2, 4, 6, 8]; let n2 = arr2.length; let arr3 = new Array(n1+n2); alternateMerge(arr1, arr2, n1, n2, arr3); document.write("Array after merging" + "<br>"); for (let i=0; i < n1+n2; i++) document.write(arr3[i] + " "); // This code is contributed by Mayank Tyagi </script>
Output:
Array after merging
1 2 3 4 5 6 7 8 9 11
Time Complexity : O(n1 + n2)
Sam007
mayanktyagi1709
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subarrays with average K
Introduction to Data Structures
Window Sliding Technique
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Next Greater Element
What is Data Structure: Types, Classifications and Applications
Merge Overlapping Intervals
Count of longest possible subarrays with sum not divisible by K
Find a triplet that sum to a given value
Remove duplicates from sorted array
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 289,
"s": 53,
"text": "Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array. "
},
{
"code": null,
"e": 528,
"s": 289,
"text": "Input : arr1[] = {1, 2, 3, 4, 5, 6}\n arr2[] = {11, 22, 33, 44}\nOutput: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6}\n\nInput : arr1[] = {1, 2, 3, 4, 5, 6, 7, 8}\n arr2[] = {11, 22, 33, 44}\nOutput: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6, 7, 8}"
},
{
"code": null,
"e": 697,
"s": 530,
"text": "We traverse both given arrays and one by one put their elements into combined array. After one of the arrays is exhausted, we put remaining elements of other array. "
},
{
"code": null,
"e": 701,
"s": 697,
"text": "C++"
},
{
"code": null,
"e": 706,
"s": 701,
"text": "Java"
},
{
"code": null,
"e": 714,
"s": 706,
"text": "Python3"
},
{
"code": null,
"e": 717,
"s": 714,
"text": "C#"
},
{
"code": null,
"e": 721,
"s": 717,
"text": "PHP"
},
{
"code": null,
"e": 732,
"s": 721,
"text": "Javascript"
},
{
"code": "// C++ program to merge two sorted arrays/#include<iostream>using namespace std; // Alternatively merge arr1[0..n1-1] and arr2[0..n2-1]// into arr3[0..n1+n2-1]void alternateMerge(int arr1[], int arr2[], int n1, int n2, int arr3[]){ int i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++];} // Driver codeint main(){ int arr1[] = {1, 3, 5, 7, 9, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 6, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int arr3[n1+n2]; alternateMerge(arr1, arr2, n1, n2, arr3); cout << \"Array after merging\" <<endl; for (int i=0; i < n1+n2; i++) cout << arr3[i] << \" \"; return 0;}",
"e": 1694,
"s": 732,
"text": null
},
{
"code": "// Java program to merge two sorted arraysimport java.io.*; class GFG { // Alternatively merge arr1[0..n1-1] and // arr2[0..n2-1] into arr3[0..n1+n2-1] static void alternateMerge(int arr1[], int arr2[], int n1, int n2, int arr3[]) { int i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } // Driver code public static void main(String args[]) { int arr1[] = {1, 3, 5, 7, 9, 11}; int n1 = arr1.length; int arr2[] = {2, 4, 6, 8}; int n2 = arr2.length; int arr3[] = new int[n1+n2]; alternateMerge(arr1, arr2, n1, n2, arr3); System.out.println(\"Array after merging\"); for (int i = 0; i < n1 + n2; i++) System.out.print( arr3[i] + \" \"); }} // This code is contributed// by Nikita Tiwari.",
"e": 2880,
"s": 1694,
"text": null
},
{
"code": "# Python3 program to merge two sorted arrays/ # Alternatively merge arr1[0..n1-1] and# arr2[0..n2-1] into arr3[0..n1 + n2-1]def alternateMerge(arr1, arr2, n1, n2, arr3) : i = 0; j = 0; k = 0 # Traverse both array while (i < n1 and j < n2) : arr3[k] = arr1[i] i += 1 k += 1 arr3[k] = arr2[j] j += 1 k += 1 # Store remaining elements of first array while (i < n1) : arr3[k] = arr1[i] i += 1 k += 1 # Store remaining elements of second array while (j < n2) : arr3[k] = arr2[j] k += 1 j += 1 # Driver codearr1 = [1, 3, 5, 7, 9, 11]n1 = len(arr1) arr2 = [2, 4, 6, 8]n2 = len(arr2) arr3= [0] *(n1 + n2)alternateMerge(arr1, arr2, n1, n2, arr3) print(\"Array after merging\")for i in range(0, (n1 + n2)) : print(arr3[i] , end = \" \") # This code is contributed by Nikita Tiwari.",
"e": 3790,
"s": 2880,
"text": null
},
{
"code": "// C# program to merge two sorted arraysusing System; class GFG { // Alternatively merge arr1[0..n1-1] // and arr2[0..n2-1] into arr3[0..n1+n2-1] static void alternateMerge(int []arr1, int []arr2, int n1, int n2, int []arr3) { int i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } // Driver code public static void Main() { int []arr1 = new int[]{1, 3, 5, 7, 9, 11}; int n1 = arr1.Length; int []arr2 = new int[]{2, 4, 6, 8}; int n2 = arr2.Length; int []arr3= new int[n1 + n2]; alternateMerge(arr1, arr2, n1, n2, arr3); Console.WriteLine(\"Array after merging\"); for (int i = 0; i < n1+n2; i++) Console.Write(arr3[i] + \" \"); }} // This code is contributed by Sam007.",
"e": 4944,
"s": 3790,
"text": null
},
{
"code": "<?php// PHP program to merge two// sorted arrays // Alternatively merge arr1[0..n1-1]// and arr2[0..n2-1] into// arr3[0..n1+n2-1]function alternateMerge($arr1, $arr2, $n1, $n2){ $i = 0; $j = 0; $k = 0; $arr3 = array(); // Traverse both array while ($i < $n1 && $j < $n2) { $arr3[$k++] = $arr1[$i++]; $arr3[$k++] = $arr2[$j++]; } // Store remaining elements // of first array while ($i < $n1) $arr3[$k++] = $arr1[$i++]; // Store remaining elements // of second array while($j < $n2) $arr3[$k++] = $arr2[$j++]; echo \"Array after merging\".\"\\n\"; for ($i = 0; $i < ($n1 + $n2); $i++) echo $arr3[$i] .\" \"; } // Driver Code $arr1 = array(1, 3, 5, 7, 9, 11); $n1 = count($arr1); $arr2 = array(2, 4, 6, 8); $n2 = count($arr2); alternateMerge($arr1, $arr2, $n1, $n2); // This code is contributed by Sam007?>",
"e": 5884,
"s": 4944,
"text": null
},
{
"code": "<script> // Javascript program to merge two sorted arrays/ // Alternatively merge arr1[0..n1-1] and arr2[0..n2-1]// into arr3[0..n1+n2-1]function alternateMerge(arr1, arr2, n1, n2, arr3){ let i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { arr3[k++] = arr1[i++]; arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++];} // Driver code let arr1 = [1, 3, 5, 7, 9, 11]; let n1 = arr1.length; let arr2 = [2, 4, 6, 8]; let n2 = arr2.length; let arr3 = new Array(n1+n2); alternateMerge(arr1, arr2, n1, n2, arr3); document.write(\"Array after merging\" + \"<br>\"); for (let i=0; i < n1+n2; i++) document.write(arr3[i] + \" \"); // This code is contributed by Mayank Tyagi </script>",
"e": 6818,
"s": 5884,
"text": null
},
{
"code": null,
"e": 6828,
"s": 6818,
"text": "Output: "
},
{
"code": null,
"e": 6870,
"s": 6828,
"text": "Array after merging\n1 2 3 4 5 6 7 8 9 11 "
},
{
"code": null,
"e": 6900,
"s": 6870,
"text": "Time Complexity : O(n1 + n2) "
},
{
"code": null,
"e": 6907,
"s": 6900,
"text": "Sam007"
},
{
"code": null,
"e": 6923,
"s": 6907,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 6930,
"s": 6923,
"text": "Arrays"
},
{
"code": null,
"e": 6937,
"s": 6930,
"text": "Arrays"
},
{
"code": null,
"e": 7035,
"s": 6937,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7069,
"s": 7035,
"text": "Count of subarrays with average K"
},
{
"code": null,
"e": 7101,
"s": 7069,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7126,
"s": 7101,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7185,
"s": 7126,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 7206,
"s": 7185,
"text": "Next Greater Element"
},
{
"code": null,
"e": 7270,
"s": 7206,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 7298,
"s": 7270,
"text": "Merge Overlapping Intervals"
},
{
"code": null,
"e": 7362,
"s": 7298,
"text": "Count of longest possible subarrays with sum not divisible by K"
},
{
"code": null,
"e": 7403,
"s": 7362,
"text": "Find a triplet that sum to a given value"
}
] |
Material Design Components Chips in Android with Example
|
25 Dec, 2020
Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, it’s been discussed how to implement the very basic selectable chips for the filtering of the options. Have a look at the following image to get an idea of what’s been discussed further. Note that we are going to implement this project using the Java language.
Step 1: Create an empty project
Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project.
Note that select Java as the programming language.
Step 2: Adding the dependency to the app-level gradle file
The current project needs Material Design Dependency.
Invoke the following dependency inside the app-level gradle file.
Make sure the system is connected to the network so that Android Studio can download the required files.
And click on the “Sync Now” button which appears on the top right corner.
implementation ‘com.google.android.material:material:1.3.0-alpha03’
Refer to the following image if unable to locate the app-level gradle file and invoke the dependency.
Step 3: Working with the activity_main.xml file
The tag required to implement the basic chip in Android is as follows:
com.google.android.material.chip.Chip
To implement the same in the layout invoke the following code. This layout includes a very basic chip from Material Design Dependency.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <com.google.android.material.chip.Chip android:id="@+id/chipCpp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="64dp" android:text="GEEKS FOR GEEKS" /> </RelativeLayout>
Output UI:
Step 4: Handling Chip in MainActivity.java file
The Material design chip button is handled using “OnClickListener”, as same as that of the normal Button.
Invoke the following code inside the MainaActivity.java file to handle the chip button, which shows the simple Toast message.
Java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Toast;import com.google.android.material.chip.Chip; public class MainActivity extends AppCompatActivity { Chip chip1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // chips is handled using the // normal OnClickListener callback chip1 = findViewById(R.id.chipGfg); chip1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Action Completed", Toast.LENGTH_SHORT).show(); } }); }}
To make the chip selectable in android the chip group needs to implement instead of a single chip.
This helps in filtering the selections of the user choices.
To implement the chip group in android invoke the following code inside the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--make sure to group the chips--> <!--style attribute is mandatory for each of the chips--> <com.google.android.material.chip.ChipGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"> <com.google.android.material.chip.Chip android:id="@+id/chipCpp" style="@style/Widget.MaterialComponents.Chip.Filter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C++" /> <com.google.android.material.chip.Chip android:id="@+id/chipJava" style="@style/Widget.MaterialComponents.Chip.Filter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="JAVA" /> <com.google.android.material.chip.Chip android:id="@+id/chipPython" style="@style/Widget.MaterialComponents.Chip.Filter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Python" /> </com.google.android.material.chip.ChipGroup> </RelativeLayout>
To handle the selection of the chips whether the chips are filtered by the user or not, invoke the following code inside the MainActivity.java file.
Java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Toast;import com.google.android.material.chip.Chip; public class MainActivity extends AppCompatActivity { Chip chipCpp, chipJava, chipPython; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chipCpp = findViewById(R.id.chipCpp); chipJava = findViewById(R.id.chipJava); chipPython = findViewById(R.id.chipPython); chipCpp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check whether the chips is filtered by user // or not and give the suitable Toast message if (chipCpp.isChecked()) { Toast.makeText(MainActivity.this, "C++ selected", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "C++ deselected", Toast.LENGTH_SHORT).show(); } } }); chipJava.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check whether the chips is filtered by user or // not and give the suitable Toast message if (chipJava.isChecked()) { Toast.makeText(MainActivity.this, "JAVA selected", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "JAVA deselected", Toast.LENGTH_SHORT).show(); } } }); chipPython.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check whether the chips is filtered by user or // not and give the suitable Toast message if (chipPython.isChecked()) { Toast.makeText(MainActivity.this, "Python selected", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Python deselected", Toast.LENGTH_SHORT).show(); } } }); }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 Dec, 2020"
},
{
"code": null,
"e": 505,
"s": 53,
"text": "Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, it’s been discussed how to implement the very basic selectable chips for the filtering of the options. Have a look at the following image to get an idea of what’s been discussed further. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 537,
"s": 505,
"text": "Step 1: Create an empty project"
},
{
"code": null,
"e": 722,
"s": 537,
"text": "Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project."
},
{
"code": null,
"e": 773,
"s": 722,
"text": "Note that select Java as the programming language."
},
{
"code": null,
"e": 832,
"s": 773,
"text": "Step 2: Adding the dependency to the app-level gradle file"
},
{
"code": null,
"e": 886,
"s": 832,
"text": "The current project needs Material Design Dependency."
},
{
"code": null,
"e": 952,
"s": 886,
"text": "Invoke the following dependency inside the app-level gradle file."
},
{
"code": null,
"e": 1057,
"s": 952,
"text": "Make sure the system is connected to the network so that Android Studio can download the required files."
},
{
"code": null,
"e": 1131,
"s": 1057,
"text": "And click on the “Sync Now” button which appears on the top right corner."
},
{
"code": null,
"e": 1199,
"s": 1131,
"text": "implementation ‘com.google.android.material:material:1.3.0-alpha03’"
},
{
"code": null,
"e": 1301,
"s": 1199,
"text": "Refer to the following image if unable to locate the app-level gradle file and invoke the dependency."
},
{
"code": null,
"e": 1349,
"s": 1301,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1420,
"s": 1349,
"text": "The tag required to implement the basic chip in Android is as follows:"
},
{
"code": null,
"e": 1458,
"s": 1420,
"text": "com.google.android.material.chip.Chip"
},
{
"code": null,
"e": 1593,
"s": 1458,
"text": "To implement the same in the layout invoke the following code. This layout includes a very basic chip from Material Design Dependency."
},
{
"code": null,
"e": 1597,
"s": 1593,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <com.google.android.material.chip.Chip android:id=\"@+id/chipCpp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"64dp\" android:text=\"GEEKS FOR GEEKS\" /> </RelativeLayout>",
"e": 2218,
"s": 1597,
"text": null
},
{
"code": null,
"e": 2229,
"s": 2218,
"text": "Output UI:"
},
{
"code": null,
"e": 2277,
"s": 2229,
"text": "Step 4: Handling Chip in MainActivity.java file"
},
{
"code": null,
"e": 2383,
"s": 2277,
"text": "The Material design chip button is handled using “OnClickListener”, as same as that of the normal Button."
},
{
"code": null,
"e": 2509,
"s": 2383,
"text": "Invoke the following code inside the MainaActivity.java file to handle the chip button, which shows the simple Toast message."
},
{
"code": null,
"e": 2514,
"s": 2509,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Toast;import com.google.android.material.chip.Chip; public class MainActivity extends AppCompatActivity { Chip chip1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // chips is handled using the // normal OnClickListener callback chip1 = findViewById(R.id.chipGfg); chip1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, \"Action Completed\", Toast.LENGTH_SHORT).show(); } }); }}",
"e": 3298,
"s": 2514,
"text": null
},
{
"code": null,
"e": 3397,
"s": 3298,
"text": "To make the chip selectable in android the chip group needs to implement instead of a single chip."
},
{
"code": null,
"e": 3457,
"s": 3397,
"text": "This helps in filtering the selections of the user choices."
},
{
"code": null,
"e": 3557,
"s": 3457,
"text": "To implement the chip group in android invoke the following code inside the activity_main.xml file."
},
{
"code": null,
"e": 3561,
"s": 3557,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--make sure to group the chips--> <!--style attribute is mandatory for each of the chips--> <com.google.android.material.chip.ChipGroup android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\"> <com.google.android.material.chip.Chip android:id=\"@+id/chipCpp\" style=\"@style/Widget.MaterialComponents.Chip.Filter\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"C++\" /> <com.google.android.material.chip.Chip android:id=\"@+id/chipJava\" style=\"@style/Widget.MaterialComponents.Chip.Filter\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"JAVA\" /> <com.google.android.material.chip.Chip android:id=\"@+id/chipPython\" style=\"@style/Widget.MaterialComponents.Chip.Filter\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Python\" /> </com.google.android.material.chip.ChipGroup> </RelativeLayout>",
"e": 5071,
"s": 3561,
"text": null
},
{
"code": null,
"e": 5220,
"s": 5071,
"text": "To handle the selection of the chips whether the chips are filtered by the user or not, invoke the following code inside the MainActivity.java file."
},
{
"code": null,
"e": 5225,
"s": 5220,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Toast;import com.google.android.material.chip.Chip; public class MainActivity extends AppCompatActivity { Chip chipCpp, chipJava, chipPython; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chipCpp = findViewById(R.id.chipCpp); chipJava = findViewById(R.id.chipJava); chipPython = findViewById(R.id.chipPython); chipCpp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check whether the chips is filtered by user // or not and give the suitable Toast message if (chipCpp.isChecked()) { Toast.makeText(MainActivity.this, \"C++ selected\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, \"C++ deselected\", Toast.LENGTH_SHORT).show(); } } }); chipJava.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check whether the chips is filtered by user or // not and give the suitable Toast message if (chipJava.isChecked()) { Toast.makeText(MainActivity.this, \"JAVA selected\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, \"JAVA deselected\", Toast.LENGTH_SHORT).show(); } } }); chipPython.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check whether the chips is filtered by user or // not and give the suitable Toast message if (chipPython.isChecked()) { Toast.makeText(MainActivity.this, \"Python selected\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, \"Python deselected\", Toast.LENGTH_SHORT).show(); } } }); }}",
"e": 7489,
"s": 5225,
"text": null
},
{
"code": null,
"e": 7497,
"s": 7489,
"text": "android"
},
{
"code": null,
"e": 7521,
"s": 7497,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 7529,
"s": 7521,
"text": "Android"
},
{
"code": null,
"e": 7534,
"s": 7529,
"text": "Java"
},
{
"code": null,
"e": 7553,
"s": 7534,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7558,
"s": 7553,
"text": "Java"
},
{
"code": null,
"e": 7566,
"s": 7558,
"text": "Android"
},
{
"code": null,
"e": 7664,
"s": 7566,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7696,
"s": 7664,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 7735,
"s": 7696,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 7777,
"s": 7735,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 7828,
"s": 7777,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 7851,
"s": 7828,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 7866,
"s": 7851,
"text": "Arrays in Java"
},
{
"code": null,
"e": 7910,
"s": 7866,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 7946,
"s": 7910,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 7997,
"s": 7946,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Replace all occurrences of pi with 3.14 in a given string
|
11 Jun, 2021
Given a string, the task is to replace all occurrences of pi with 3.14 in the given string.Examples:
Input : str = "2 * pi + 3 * pi = 5 * pi"
Output : 2 * 3.14 + 3 * 3.14 = 5 * 3.14
Input : str = "pippppiiiipi"
Output : 3.14ppp3.14iii3.14
Input : str = "xpix"
Output : x3.14x
Approach 1:
Create an empty output string.Traverse the string from the 0th index till second last index since length of pi is 2. If the alphabets at the current and (current+1)th index form the word “pi”, append “3.14” to the output string. Else append the alphabet at the current index.
Create an empty output string.
Traverse the string from the 0th index till second last index since length of pi is 2.
If the alphabets at the current and (current+1)th index form the word “pi”, append “3.14” to the output string.
Else append the alphabet at the current index.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to replace all// pi in a given string with 3.14 #include <bits/stdc++.h>using namespace std; // Function to replace all occurrences// of pi in a given with 3.14string replacePi(string input){ string output; int size = input.length(); // Iterate through second last // element of the string for (int i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size and input[i] == 'p' and input[i + 1] == 'i') { output += "3.14"; i++; } // Append the current letter else { output += input[i]; } } // Return the output string return output;} // Driver Codeint main(){ string input = "2 * pi + 3 * pi = 5 * pi"; cout << replacePi(input); return 0;}
// Java program to replace all// pi in a given String with 3.14 class GFG { // Function to replace all occurrences // of pi in a given with 3.14 public String replacePi(String input) { String output = ""; int size = input.length(); // Iterate through second last // element of the String for (int i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size && input.charAt(i) == 'p' && input.charAt(i + 1) == 'i') { output += "3.14"; i++; } // Append the current letter else { output += input.charAt(i); } } // Return the output String return output; } // Driver Code public static void main(String args[]) { GFG g = new GFG(); String input = "2 * pi + 3 * pi = 5 * pi"; System.out.println(g.replacePi(input)); }} // This code has been contributed by 29AjayKumar
# Python program to replace all# pi in a given string with 3.14 # Function to replace all occurrences# of pi in a given with 3.14def replacePi(input): output =""; size = len(input); # Iterate through second last # element of the string for i in range(size): # If current and current + 1 alphabets # form the word 'pi' # append 3.14 to output if (i + 1 < size and input[i] == 'p' and input[i + 1] == 'i'): output += "3.14"; i+= 1; # Append the current letter else: output += input[i]; # Return the output string return output; # Driver Codeinput = "2 * pi + 3 * pi = 5 * pi";print(replacePi(input)); # This code contributed by PrinciRaj1992
// C# program to replace all// pi in a given string with 3.14 using System;// Function to replace all occurrences// of pi in a given with 3.14class gfg { public string replacePi(string input) { string output = ""; int size = input.Length; // Iterate through second last // element of the string for (int i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size && input[i] == 'p' && input[i + 1] == 'i') { output += "3.14"; i++; } // Append the current letter else { output += input[i]; } } // Return the output string return output; }} // Driver Codeclass geek { public static int Main() { gfg g = new gfg(); string input = "2 * pi + 3 * pi = 5 * pi"; Console.WriteLine(g.replacePi(input)); return 0; }}// This code is contributed by Soumik
<script> // JavaScript program to replace all // pi in a given string with 3.14 // Function to replace all occurrences // of pi in a given with 3.14 function replacePi(input) { var output = ""; var size = input.length; // Iterate through second last // element of the string for (var i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size && input[i] === "p" && input[i + 1] === "i") { output += "3.14"; i++; } // Append the current letter else { output += input[i]; } } // Return the output string return output; } // Driver Code var input = "2 * pi + 3 * pi = 5 * pi"; document.write(replacePi(input)); </script>
2 * 3.14 + 3 * 3.14 = 5 * 3.14
Time Complexity: O(N), where N is the length of the given string.Approach 2: (In Java) To replace all the PI occurrences to 3.14, use replaceAll() method of Java String Class.
Java
public class ReplacePI { public static void main(String[] args) { // Declare a String String expression = "2 * pi + 3 * pi = 5 * pi"; // Call replaceAll() method to replace PI to 3.14 expression = expression.replaceAll("pi", "3.14"); // Print the result System.out.println(expression); }}
2 * 3.14 + 3 * 3.14 = 5 * 3.14
bilal-hungund
SoumikMondal
neverSettle
29AjayKumar
princiraj1992
rdtank
Technical Scripter 2018
Searching
Strings
Technical Scripter
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 157,
"s": 54,
"text": "Given a string, the task is to replace all occurrences of pi with 3.14 in the given string.Examples: "
},
{
"code": null,
"e": 334,
"s": 157,
"text": "Input : str = \"2 * pi + 3 * pi = 5 * pi\"\nOutput : 2 * 3.14 + 3 * 3.14 = 5 * 3.14\n\nInput : str = \"pippppiiiipi\"\nOutput : 3.14ppp3.14iii3.14\n\nInput : str = \"xpix\"\nOutput : x3.14x"
},
{
"code": null,
"e": 350,
"s": 336,
"text": "Approach 1: "
},
{
"code": null,
"e": 628,
"s": 350,
"text": "Create an empty output string.Traverse the string from the 0th index till second last index since length of pi is 2. If the alphabets at the current and (current+1)th index form the word “pi”, append “3.14” to the output string. Else append the alphabet at the current index. "
},
{
"code": null,
"e": 659,
"s": 628,
"text": "Create an empty output string."
},
{
"code": null,
"e": 747,
"s": 659,
"text": "Traverse the string from the 0th index till second last index since length of pi is 2. "
},
{
"code": null,
"e": 860,
"s": 747,
"text": "If the alphabets at the current and (current+1)th index form the word “pi”, append “3.14” to the output string. "
},
{
"code": null,
"e": 909,
"s": 860,
"text": "Else append the alphabet at the current index. "
},
{
"code": null,
"e": 962,
"s": 909,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 966,
"s": 962,
"text": "C++"
},
{
"code": null,
"e": 971,
"s": 966,
"text": "Java"
},
{
"code": null,
"e": 979,
"s": 971,
"text": "Python3"
},
{
"code": null,
"e": 982,
"s": 979,
"text": "C#"
},
{
"code": null,
"e": 993,
"s": 982,
"text": "Javascript"
},
{
"code": "// C++ program to replace all// pi in a given string with 3.14 #include <bits/stdc++.h>using namespace std; // Function to replace all occurrences// of pi in a given with 3.14string replacePi(string input){ string output; int size = input.length(); // Iterate through second last // element of the string for (int i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size and input[i] == 'p' and input[i + 1] == 'i') { output += \"3.14\"; i++; } // Append the current letter else { output += input[i]; } } // Return the output string return output;} // Driver Codeint main(){ string input = \"2 * pi + 3 * pi = 5 * pi\"; cout << replacePi(input); return 0;}",
"e": 1843,
"s": 993,
"text": null
},
{
"code": "// Java program to replace all// pi in a given String with 3.14 class GFG { // Function to replace all occurrences // of pi in a given with 3.14 public String replacePi(String input) { String output = \"\"; int size = input.length(); // Iterate through second last // element of the String for (int i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size && input.charAt(i) == 'p' && input.charAt(i + 1) == 'i') { output += \"3.14\"; i++; } // Append the current letter else { output += input.charAt(i); } } // Return the output String return output; } // Driver Code public static void main(String args[]) { GFG g = new GFG(); String input = \"2 * pi + 3 * pi = 5 * pi\"; System.out.println(g.replacePi(input)); }} // This code has been contributed by 29AjayKumar",
"e": 2916,
"s": 1843,
"text": null
},
{
"code": "# Python program to replace all# pi in a given string with 3.14 # Function to replace all occurrences# of pi in a given with 3.14def replacePi(input): output =\"\"; size = len(input); # Iterate through second last # element of the string for i in range(size): # If current and current + 1 alphabets # form the word 'pi' # append 3.14 to output if (i + 1 < size and input[i] == 'p' and input[i + 1] == 'i'): output += \"3.14\"; i+= 1; # Append the current letter else: output += input[i]; # Return the output string return output; # Driver Codeinput = \"2 * pi + 3 * pi = 5 * pi\";print(replacePi(input)); # This code contributed by PrinciRaj1992",
"e": 3683,
"s": 2916,
"text": null
},
{
"code": "// C# program to replace all// pi in a given string with 3.14 using System;// Function to replace all occurrences// of pi in a given with 3.14class gfg { public string replacePi(string input) { string output = \"\"; int size = input.Length; // Iterate through second last // element of the string for (int i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size && input[i] == 'p' && input[i + 1] == 'i') { output += \"3.14\"; i++; } // Append the current letter else { output += input[i]; } } // Return the output string return output; }} // Driver Codeclass geek { public static int Main() { gfg g = new gfg(); string input = \"2 * pi + 3 * pi = 5 * pi\"; Console.WriteLine(g.replacePi(input)); return 0; }}// This code is contributed by Soumik",
"e": 4734,
"s": 3683,
"text": null
},
{
"code": "<script> // JavaScript program to replace all // pi in a given string with 3.14 // Function to replace all occurrences // of pi in a given with 3.14 function replacePi(input) { var output = \"\"; var size = input.length; // Iterate through second last // element of the string for (var i = 0; i < size; ++i) { // If current and current +1 alphabets // form the word 'pi' // append 3.14 to output if (i + 1 < size && input[i] === \"p\" && input[i + 1] === \"i\") { output += \"3.14\"; i++; } // Append the current letter else { output += input[i]; } } // Return the output string return output; } // Driver Code var input = \"2 * pi + 3 * pi = 5 * pi\"; document.write(replacePi(input)); </script>",
"e": 5664,
"s": 4734,
"text": null
},
{
"code": null,
"e": 5695,
"s": 5664,
"text": "2 * 3.14 + 3 * 3.14 = 5 * 3.14"
},
{
"code": null,
"e": 5874,
"s": 5697,
"text": "Time Complexity: O(N), where N is the length of the given string.Approach 2: (In Java) To replace all the PI occurrences to 3.14, use replaceAll() method of Java String Class. "
},
{
"code": null,
"e": 5879,
"s": 5874,
"text": "Java"
},
{
"code": "public class ReplacePI { public static void main(String[] args) { // Declare a String String expression = \"2 * pi + 3 * pi = 5 * pi\"; // Call replaceAll() method to replace PI to 3.14 expression = expression.replaceAll(\"pi\", \"3.14\"); // Print the result System.out.println(expression); }}",
"e": 6221,
"s": 5879,
"text": null
},
{
"code": null,
"e": 6252,
"s": 6221,
"text": "2 * 3.14 + 3 * 3.14 = 5 * 3.14"
},
{
"code": null,
"e": 6268,
"s": 6254,
"text": "bilal-hungund"
},
{
"code": null,
"e": 6281,
"s": 6268,
"text": "SoumikMondal"
},
{
"code": null,
"e": 6293,
"s": 6281,
"text": "neverSettle"
},
{
"code": null,
"e": 6305,
"s": 6293,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6319,
"s": 6305,
"text": "princiraj1992"
},
{
"code": null,
"e": 6326,
"s": 6319,
"text": "rdtank"
},
{
"code": null,
"e": 6350,
"s": 6326,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 6360,
"s": 6350,
"text": "Searching"
},
{
"code": null,
"e": 6368,
"s": 6360,
"text": "Strings"
},
{
"code": null,
"e": 6387,
"s": 6368,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6397,
"s": 6387,
"text": "Searching"
},
{
"code": null,
"e": 6405,
"s": 6397,
"text": "Strings"
}
] |
Proof that Independent Set in Graph theory is NP Complete
|
26 Jun, 2020
Prerequisite: NP-Completeness, Independent set.
An Independent Set S of graph G = (V, E) is a set of vertices such that no two vertices in S are adjacent to each other. It consists of non- adjacent vertices.
Problem: Given a graph G(V, E) and an integer k, the problem is to determine if the graph contains an independent set of vertices of size >=k.Explanation:An instance of the problem is an input specified to the problem. An instance of the Independent Set problem is a graph G (V, E) and a positive integer k, and the problem is to check whether an independent set of size k exists in G. Since an NP-Complete problem, by definition, is a problem which is both in NP and NP-hard, the proof for the statement that a problem is NP-Complete consists of two parts:
The problem itself is in NP class.All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as )
The problem itself is in NP class.
All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as )
If the 2nd condition is only satisfied then the problem is called NP-Hard.
But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. That is why if we want to show a problem is NP-Complete we just show that the problem is in NP and any NP-Complete problem is reducible to that then we are done, i.e. if B is NP-Complete and for C in NP, then C is NP-Complete.
Independent Set is NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a subset V’ of the vertices, which comprises the vertices belonging to the independent set. We can validate this solution by checking that each pair of vertices belonging to the solution are non-adjacent, by simply verifying that they don’t share an edge with each other. This can be done in polynomial time, that is O(V +E) using the following strategy of graph G(V, E):flag=true
For every pair {u, v} in the subset V’:
Check that these two don’t
have an edge between them
If there is an edge,
set flag to false and break
If flag is true:
Solution is correct
Else:
Solution is incorrect
Independent Set is NP-Hard.In order to prove that the Independent Set problem is NP-Hard, we will perform a reduction from a known NP-Hard problem to this problem. We will carry out a reduction from which the Clique Problem can be reduced to the Independent Set problem.Every instance of the clique problem consisting of the graph G (V, E) and an integer k can be converted to the required graph G’ (V’, E’) and k’ of the Independent Set problem. We will construct the graph G’ in the following way:V’ = V i.e. all the vertices of graph G are a part of the graph G’E’ = complement of the edges E, i.e. the edges not present in the original graph G.The graph G’ is the complementary graph of G. The time required to compute the complementary graph G’ requires a traversal over all the vertices and edges. The time complexity of this is O (V+E).We will now prove that the problem of computing the independent set indeed boils down to the computation of the clique. The reduction can be proved by the following two propositions:Let us assume that the graph G contains a clique of size k. The presence of clique implies that there are k vertices in G, where each of the vertices is connected by an edge with the remaining vertices. This further shows that since these edges are contained in G, therefore they can’t be present in G’. As a result, these k vertices are not adjacent to each other in G’ and hence form an Independent Set of size k.We assume that the complementary graph G’ has an independent set of vertices of size k’. None of these vertices shares an edge with any other vertices. When we complement the graph to obtain G, these k vertices will share an edge and hence, become adjacent to each other. Therefore, the graph G will have a clique of size k.
Independent Set is NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a subset V’ of the vertices, which comprises the vertices belonging to the independent set. We can validate this solution by checking that each pair of vertices belonging to the solution are non-adjacent, by simply verifying that they don’t share an edge with each other. This can be done in polynomial time, that is O(V +E) using the following strategy of graph G(V, E):flag=true
For every pair {u, v} in the subset V’:
Check that these two don’t
have an edge between them
If there is an edge,
set flag to false and break
If flag is true:
Solution is correct
Else:
Solution is incorrect
flag=true
For every pair {u, v} in the subset V’:
Check that these two don’t
have an edge between them
If there is an edge,
set flag to false and break
If flag is true:
Solution is correct
Else:
Solution is incorrect
Independent Set is NP-Hard.In order to prove that the Independent Set problem is NP-Hard, we will perform a reduction from a known NP-Hard problem to this problem. We will carry out a reduction from which the Clique Problem can be reduced to the Independent Set problem.Every instance of the clique problem consisting of the graph G (V, E) and an integer k can be converted to the required graph G’ (V’, E’) and k’ of the Independent Set problem. We will construct the graph G’ in the following way:V’ = V i.e. all the vertices of graph G are a part of the graph G’E’ = complement of the edges E, i.e. the edges not present in the original graph G.The graph G’ is the complementary graph of G. The time required to compute the complementary graph G’ requires a traversal over all the vertices and edges. The time complexity of this is O (V+E).We will now prove that the problem of computing the independent set indeed boils down to the computation of the clique. The reduction can be proved by the following two propositions:Let us assume that the graph G contains a clique of size k. The presence of clique implies that there are k vertices in G, where each of the vertices is connected by an edge with the remaining vertices. This further shows that since these edges are contained in G, therefore they can’t be present in G’. As a result, these k vertices are not adjacent to each other in G’ and hence form an Independent Set of size k.We assume that the complementary graph G’ has an independent set of vertices of size k’. None of these vertices shares an edge with any other vertices. When we complement the graph to obtain G, these k vertices will share an edge and hence, become adjacent to each other. Therefore, the graph G will have a clique of size k.
V’ = V i.e. all the vertices of graph G are a part of the graph G’E’ = complement of the edges E, i.e. the edges not present in the original graph G.
The graph G’ is the complementary graph of G. The time required to compute the complementary graph G’ requires a traversal over all the vertices and edges. The time complexity of this is O (V+E).We will now prove that the problem of computing the independent set indeed boils down to the computation of the clique. The reduction can be proved by the following two propositions:
Let us assume that the graph G contains a clique of size k. The presence of clique implies that there are k vertices in G, where each of the vertices is connected by an edge with the remaining vertices. This further shows that since these edges are contained in G, therefore they can’t be present in G’. As a result, these k vertices are not adjacent to each other in G’ and hence form an Independent Set of size k.
We assume that the complementary graph G’ has an independent set of vertices of size k’. None of these vertices shares an edge with any other vertices. When we complement the graph to obtain G, these k vertices will share an edge and hence, become adjacent to each other. Therefore, the graph G will have a clique of size k.
Thus, we can say that there is an independent set of size k in graph G if there is a clique of size k in G’ (complement graph). Therefore, any instance of the independent set problem can be reduced to an instance of the clique problem. Thus, the independent set is NP-Hard.
Conclusion:Since the Independent Set problem is both NP and NP-Hard, therefore it is an NP-Complete problem.
Algorithms-NP Complete
NP Complete
NPHard
Algorithms
Analysis
Graph
Mathematical
Mathematical
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
CPU Scheduling in Operating Systems
Understanding Time Complexity with Simple Examples
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Practice Questions on Time Complexity Analysis
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Analysis of Algorithms | Set 3 (Asymptotic Notations)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 76,
"s": 28,
"text": "Prerequisite: NP-Completeness, Independent set."
},
{
"code": null,
"e": 236,
"s": 76,
"text": "An Independent Set S of graph G = (V, E) is a set of vertices such that no two vertices in S are adjacent to each other. It consists of non- adjacent vertices."
},
{
"code": null,
"e": 794,
"s": 236,
"text": "Problem: Given a graph G(V, E) and an integer k, the problem is to determine if the graph contains an independent set of vertices of size >=k.Explanation:An instance of the problem is an input specified to the problem. An instance of the Independent Set problem is a graph G (V, E) and a positive integer k, and the problem is to check whether an independent set of size k exists in G. Since an NP-Complete problem, by definition, is a problem which is both in NP and NP-hard, the proof for the statement that a problem is NP-Complete consists of two parts:"
},
{
"code": null,
"e": 953,
"s": 794,
"text": "The problem itself is in NP class.All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as )"
},
{
"code": null,
"e": 988,
"s": 953,
"text": "The problem itself is in NP class."
},
{
"code": null,
"e": 1113,
"s": 988,
"text": "All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as )"
},
{
"code": null,
"e": 1188,
"s": 1113,
"text": "If the 2nd condition is only satisfied then the problem is called NP-Hard."
},
{
"code": null,
"e": 1532,
"s": 1188,
"text": "But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. That is why if we want to show a problem is NP-Complete we just show that the problem is in NP and any NP-Complete problem is reducible to that then we are done, i.e. if B is NP-Complete and for C in NP, then C is NP-Complete."
},
{
"code": null,
"e": 4235,
"s": 1532,
"text": "Independent Set is NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a subset V’ of the vertices, which comprises the vertices belonging to the independent set. We can validate this solution by checking that each pair of vertices belonging to the solution are non-adjacent, by simply verifying that they don’t share an edge with each other. This can be done in polynomial time, that is O(V +E) using the following strategy of graph G(V, E):flag=true\nFor every pair {u, v} in the subset V’:\n Check that these two don’t\n have an edge between them\n If there is an edge,\n set flag to false and break\nIf flag is true:\n Solution is correct\nElse:\n Solution is incorrect\nIndependent Set is NP-Hard.In order to prove that the Independent Set problem is NP-Hard, we will perform a reduction from a known NP-Hard problem to this problem. We will carry out a reduction from which the Clique Problem can be reduced to the Independent Set problem.Every instance of the clique problem consisting of the graph G (V, E) and an integer k can be converted to the required graph G’ (V’, E’) and k’ of the Independent Set problem. We will construct the graph G’ in the following way:V’ = V i.e. all the vertices of graph G are a part of the graph G’E’ = complement of the edges E, i.e. the edges not present in the original graph G.The graph G’ is the complementary graph of G. The time required to compute the complementary graph G’ requires a traversal over all the vertices and edges. The time complexity of this is O (V+E).We will now prove that the problem of computing the independent set indeed boils down to the computation of the clique. The reduction can be proved by the following two propositions:Let us assume that the graph G contains a clique of size k. The presence of clique implies that there are k vertices in G, where each of the vertices is connected by an edge with the remaining vertices. This further shows that since these edges are contained in G, therefore they can’t be present in G’. As a result, these k vertices are not adjacent to each other in G’ and hence form an Independent Set of size k.We assume that the complementary graph G’ has an independent set of vertices of size k’. None of these vertices shares an edge with any other vertices. When we complement the graph to obtain G, these k vertices will share an edge and hence, become adjacent to each other. Therefore, the graph G will have a clique of size k."
},
{
"code": null,
"e": 5174,
"s": 4235,
"text": "Independent Set is NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a subset V’ of the vertices, which comprises the vertices belonging to the independent set. We can validate this solution by checking that each pair of vertices belonging to the solution are non-adjacent, by simply verifying that they don’t share an edge with each other. This can be done in polynomial time, that is O(V +E) using the following strategy of graph G(V, E):flag=true\nFor every pair {u, v} in the subset V’:\n Check that these two don’t\n have an edge between them\n If there is an edge,\n set flag to false and break\nIf flag is true:\n Solution is correct\nElse:\n Solution is incorrect\n"
},
{
"code": null,
"e": 5416,
"s": 5174,
"text": "flag=true\nFor every pair {u, v} in the subset V’:\n Check that these two don’t\n have an edge between them\n If there is an edge,\n set flag to false and break\nIf flag is true:\n Solution is correct\nElse:\n Solution is incorrect\n"
},
{
"code": null,
"e": 7181,
"s": 5416,
"text": "Independent Set is NP-Hard.In order to prove that the Independent Set problem is NP-Hard, we will perform a reduction from a known NP-Hard problem to this problem. We will carry out a reduction from which the Clique Problem can be reduced to the Independent Set problem.Every instance of the clique problem consisting of the graph G (V, E) and an integer k can be converted to the required graph G’ (V’, E’) and k’ of the Independent Set problem. We will construct the graph G’ in the following way:V’ = V i.e. all the vertices of graph G are a part of the graph G’E’ = complement of the edges E, i.e. the edges not present in the original graph G.The graph G’ is the complementary graph of G. The time required to compute the complementary graph G’ requires a traversal over all the vertices and edges. The time complexity of this is O (V+E).We will now prove that the problem of computing the independent set indeed boils down to the computation of the clique. The reduction can be proved by the following two propositions:Let us assume that the graph G contains a clique of size k. The presence of clique implies that there are k vertices in G, where each of the vertices is connected by an edge with the remaining vertices. This further shows that since these edges are contained in G, therefore they can’t be present in G’. As a result, these k vertices are not adjacent to each other in G’ and hence form an Independent Set of size k.We assume that the complementary graph G’ has an independent set of vertices of size k’. None of these vertices shares an edge with any other vertices. When we complement the graph to obtain G, these k vertices will share an edge and hence, become adjacent to each other. Therefore, the graph G will have a clique of size k."
},
{
"code": null,
"e": 7331,
"s": 7181,
"text": "V’ = V i.e. all the vertices of graph G are a part of the graph G’E’ = complement of the edges E, i.e. the edges not present in the original graph G."
},
{
"code": null,
"e": 7709,
"s": 7331,
"text": "The graph G’ is the complementary graph of G. The time required to compute the complementary graph G’ requires a traversal over all the vertices and edges. The time complexity of this is O (V+E).We will now prove that the problem of computing the independent set indeed boils down to the computation of the clique. The reduction can be proved by the following two propositions:"
},
{
"code": null,
"e": 8125,
"s": 7709,
"text": "Let us assume that the graph G contains a clique of size k. The presence of clique implies that there are k vertices in G, where each of the vertices is connected by an edge with the remaining vertices. This further shows that since these edges are contained in G, therefore they can’t be present in G’. As a result, these k vertices are not adjacent to each other in G’ and hence form an Independent Set of size k."
},
{
"code": null,
"e": 8450,
"s": 8125,
"text": "We assume that the complementary graph G’ has an independent set of vertices of size k’. None of these vertices shares an edge with any other vertices. When we complement the graph to obtain G, these k vertices will share an edge and hence, become adjacent to each other. Therefore, the graph G will have a clique of size k."
},
{
"code": null,
"e": 8724,
"s": 8450,
"text": "Thus, we can say that there is an independent set of size k in graph G if there is a clique of size k in G’ (complement graph). Therefore, any instance of the independent set problem can be reduced to an instance of the clique problem. Thus, the independent set is NP-Hard."
},
{
"code": null,
"e": 8833,
"s": 8724,
"text": "Conclusion:Since the Independent Set problem is both NP and NP-Hard, therefore it is an NP-Complete problem."
},
{
"code": null,
"e": 8856,
"s": 8833,
"text": "Algorithms-NP Complete"
},
{
"code": null,
"e": 8868,
"s": 8856,
"text": "NP Complete"
},
{
"code": null,
"e": 8875,
"s": 8868,
"text": "NPHard"
},
{
"code": null,
"e": 8886,
"s": 8875,
"text": "Algorithms"
},
{
"code": null,
"e": 8895,
"s": 8886,
"text": "Analysis"
},
{
"code": null,
"e": 8901,
"s": 8895,
"text": "Graph"
},
{
"code": null,
"e": 8914,
"s": 8901,
"text": "Mathematical"
},
{
"code": null,
"e": 8927,
"s": 8914,
"text": "Mathematical"
},
{
"code": null,
"e": 8933,
"s": 8927,
"text": "Graph"
},
{
"code": null,
"e": 8944,
"s": 8933,
"text": "Algorithms"
},
{
"code": null,
"e": 9042,
"s": 8944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9067,
"s": 9042,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 9116,
"s": 9067,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 9154,
"s": 9116,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 9190,
"s": 9154,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 9241,
"s": 9190,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 9292,
"s": 9241,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 9329,
"s": 9292,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 9376,
"s": 9329,
"text": "Practice Questions on Time Complexity Analysis"
},
{
"code": null,
"e": 9439,
"s": 9376,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
}
] |
Return a Matrix with Upper Triangle as TRUE values in R Programming – upper.tri() Function
|
16 Jun, 2020
upper.tri() function in R Language is used to return a matrix of logical values with upper triangle as TRUE.
Syntax: upper.tri(x, diag)
Parameters:x: Matrix objectdiag: Boolean value to include diagonal
Example 1:
# R program to print the # upper triangle of a matrix # Creating a matrixmat <- matrix(c(1:9), 3, 3, byrow = T) # Calling upper.tri() Function# Excluding diagonal elementsupper.tri(mat, diag = F)
Output:
[, 1] [, 2] [, 3]
[1, ] FALSE TRUE TRUE
[2, ] FALSE FALSE TRUE
[3, ] FALSE FALSE FALSE
Example 2:
# R program to print the # upper triangle of a matrix # Creating a matrixmat <- matrix(c(1:9), 3, 3, byrow = T) # Calling upper.tri() Function# including diagonal elementsupper.tri(mat, diag = T)
Output:
[, 1] [, 2] [, 3]
[1, ] TRUE TRUE TRUE
[2, ] FALSE TRUE TRUE
[3, ] FALSE FALSE TRUE
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2020"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "upper.tri() function in R Language is used to return a matrix of logical values with upper triangle as TRUE."
},
{
"code": null,
"e": 164,
"s": 137,
"text": "Syntax: upper.tri(x, diag)"
},
{
"code": null,
"e": 231,
"s": 164,
"text": "Parameters:x: Matrix objectdiag: Boolean value to include diagonal"
},
{
"code": null,
"e": 242,
"s": 231,
"text": "Example 1:"
},
{
"code": "# R program to print the # upper triangle of a matrix # Creating a matrixmat <- matrix(c(1:9), 3, 3, byrow = T) # Calling upper.tri() Function# Excluding diagonal elementsupper.tri(mat, diag = F)",
"e": 440,
"s": 242,
"text": null
},
{
"code": null,
"e": 448,
"s": 440,
"text": "Output:"
},
{
"code": null,
"e": 547,
"s": 448,
"text": " [, 1] [, 2] [, 3]\n[1, ] FALSE TRUE TRUE\n[2, ] FALSE FALSE TRUE\n[3, ] FALSE FALSE FALSE\n"
},
{
"code": null,
"e": 558,
"s": 547,
"text": "Example 2:"
},
{
"code": "# R program to print the # upper triangle of a matrix # Creating a matrixmat <- matrix(c(1:9), 3, 3, byrow = T) # Calling upper.tri() Function# including diagonal elementsupper.tri(mat, diag = T)",
"e": 756,
"s": 558,
"text": null
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Output:"
},
{
"code": null,
"e": 859,
"s": 764,
"text": " [, 1] [, 2] [, 3]\n[1, ] TRUE TRUE TRUE\n[2, ] FALSE TRUE TRUE\n[3, ] FALSE FALSE TRUE\n"
},
{
"code": null,
"e": 877,
"s": 859,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 888,
"s": 877,
"text": "R Language"
},
{
"code": null,
"e": 986,
"s": 888,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1038,
"s": 986,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1096,
"s": 1038,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1131,
"s": 1096,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 1169,
"s": 1131,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 1218,
"s": 1169,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 1235,
"s": 1218,
"text": "R - if statement"
},
{
"code": null,
"e": 1272,
"s": 1235,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 1315,
"s": 1272,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 1352,
"s": 1315,
"text": "How to import an Excel File into R ?"
}
] |
When do we pass arguments by reference or pointer?
|
04 Jan, 2022
In C++, variables are passed by reference due to following reasons:1) To modify local variables of the caller function: A reference (or pointer) allows called function to modify a local variable of the caller function. For example, consider the following example program where fun() is able to modify local variable x of main().
CPP
#include <bits/stdc++.h>using namespace std; void fun(int& x) { x = 20; } int main(){ int x = 10; fun(x); cout << "New value of x is " << x; return 0;}
Output: New value of x is 202) For passing large sized arguments: If an argument is large, passing by reference (or pointer) is more efficient because only an address is really passed, not the entire object. For example, let us consider the following Employee class and a function printEmpDetails() that prints Employee details.
C
class Employee {private: string name; string desig; // More attributes and operations}; void printEmpDetails(Employee emp){ cout << emp.getName(); cout << emp.getDesig(); // Print more attributes}
The problem with above code is: every time printEmpDetails() is called, a new Employee object is constructed that involves creating a copy of all data members. So a better implementation would be to pass Employee as a reference.
C
void printEmpDetails(const Employee& emp){ cout << emp.getName(); cout << emp.getDesig(); // Print more attributes}
This point is valid only for struct and class variables as we don’t get any efficiency advantage for basic types like int, char, etc. 3) To avoid Object Slicing: If we pass an object of subclass to a function that expects an object of superclass then the passed object is sliced if it is pass by value. For example, consider the following program, it prints “This is Pet Class”.
C
#include <iostream> using namespace std; class Pet {public: virtual string getDescription() const { return "This is Pet class"; }}; class Dog : public Pet {public: virtual string getDescription() const { return "This is Dog class"; }}; void describe(Pet p){ // Slices the derived class object cout << p.getDescription() << '\n';} int main(){ Dog d; describe(d); return 0;}
Output: This is Pet ClassIf we use pass by reference in the above program then it correctly prints “This is Dog Class”. See the following modified program.
C++
#include <iostream> using namespace std; class Pet {public: virtual string getDescription() const { return "This is Pet class"; }}; class Dog : public Pet {public: virtual string getDescription() const { return "This is Dog class"; }}; void describe(const Pet& p){ // Doesn't slice the derived class object. cout << p.getDescription() << '\n';} int main(){ Dog d; describe(d); return 0;}
Output: This is Dog ClassThis point is also not valid for basic data types like int, char, etc.4) To achieve Run Time Polymorphism in a function We can make a function polymorphic by passing objects as reference (or pointer) to it. For example, in the following program, print() receives a reference to the base class object. Function print() calls the base class function show() if base class object is passed, and derived class function show() if derived class object is passed.
C++
#include <iostream>using namespace std; class base {public: virtual void show() { // Note the virtual keyword here cout << "In base\n"; }}; class derived : public base {public: void show() { cout << "In derived\n"; }}; // Since we pass b as reference, we achieve run time// polymorphism here.void print(base& b) { b.show(); } int main(void){ base b; derived d; print(b); print(d); return 0;}
Output: In base In derived Thanks to Venki for adding this point. As a side note, it is a recommended practice to make reference arguments const if they are being passed by reference only due to reason no. 2 or 3 mentioned above. This is recommended to avoid unexpected modifications to the objects.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sunnychaudharyvlsi
kziemianfvt
pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Inheritance in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 384,
"s": 54,
"text": "In C++, variables are passed by reference due to following reasons:1) To modify local variables of the caller function: A reference (or pointer) allows called function to modify a local variable of the caller function. For example, consider the following example program where fun() is able to modify local variable x of main(). "
},
{
"code": null,
"e": 388,
"s": 384,
"text": "CPP"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void fun(int& x) { x = 20; } int main(){ int x = 10; fun(x); cout << \"New value of x is \" << x; return 0;}",
"e": 552,
"s": 388,
"text": null
},
{
"code": null,
"e": 882,
"s": 552,
"text": "Output: New value of x is 202) For passing large sized arguments: If an argument is large, passing by reference (or pointer) is more efficient because only an address is really passed, not the entire object. For example, let us consider the following Employee class and a function printEmpDetails() that prints Employee details. "
},
{
"code": null,
"e": 884,
"s": 882,
"text": "C"
},
{
"code": "class Employee {private: string name; string desig; // More attributes and operations}; void printEmpDetails(Employee emp){ cout << emp.getName(); cout << emp.getDesig(); // Print more attributes}",
"e": 1101,
"s": 884,
"text": null
},
{
"code": null,
"e": 1331,
"s": 1101,
"text": "The problem with above code is: every time printEmpDetails() is called, a new Employee object is constructed that involves creating a copy of all data members. So a better implementation would be to pass Employee as a reference. "
},
{
"code": null,
"e": 1333,
"s": 1331,
"text": "C"
},
{
"code": "void printEmpDetails(const Employee& emp){ cout << emp.getName(); cout << emp.getDesig(); // Print more attributes}",
"e": 1459,
"s": 1333,
"text": null
},
{
"code": null,
"e": 1840,
"s": 1459,
"text": "This point is valid only for struct and class variables as we don’t get any efficiency advantage for basic types like int, char, etc. 3) To avoid Object Slicing: If we pass an object of subclass to a function that expects an object of superclass then the passed object is sliced if it is pass by value. For example, consider the following program, it prints “This is Pet Class”. "
},
{
"code": null,
"e": 1842,
"s": 1840,
"text": "C"
},
{
"code": "#include <iostream> using namespace std; class Pet {public: virtual string getDescription() const { return \"This is Pet class\"; }}; class Dog : public Pet {public: virtual string getDescription() const { return \"This is Dog class\"; }}; void describe(Pet p){ // Slices the derived class object cout << p.getDescription() << '\\n';} int main(){ Dog d; describe(d); return 0;}",
"e": 2259,
"s": 1842,
"text": null
},
{
"code": null,
"e": 2416,
"s": 2259,
"text": "Output: This is Pet ClassIf we use pass by reference in the above program then it correctly prints “This is Dog Class”. See the following modified program. "
},
{
"code": null,
"e": 2420,
"s": 2416,
"text": "C++"
},
{
"code": "#include <iostream> using namespace std; class Pet {public: virtual string getDescription() const { return \"This is Pet class\"; }}; class Dog : public Pet {public: virtual string getDescription() const { return \"This is Dog class\"; }}; void describe(const Pet& p){ // Doesn't slice the derived class object. cout << p.getDescription() << '\\n';} int main(){ Dog d; describe(d); return 0;}",
"e": 2852,
"s": 2420,
"text": null
},
{
"code": null,
"e": 3335,
"s": 2852,
"text": "Output: This is Dog ClassThis point is also not valid for basic data types like int, char, etc.4) To achieve Run Time Polymorphism in a function We can make a function polymorphic by passing objects as reference (or pointer) to it. For example, in the following program, print() receives a reference to the base class object. Function print() calls the base class function show() if base class object is passed, and derived class function show() if derived class object is passed. "
},
{
"code": null,
"e": 3339,
"s": 3335,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class base {public: virtual void show() { // Note the virtual keyword here cout << \"In base\\n\"; }}; class derived : public base {public: void show() { cout << \"In derived\\n\"; }}; // Since we pass b as reference, we achieve run time// polymorphism here.void print(base& b) { b.show(); } int main(void){ base b; derived d; print(b); print(d); return 0;}",
"e": 3765,
"s": 3339,
"text": null
},
{
"code": null,
"e": 4190,
"s": 3765,
"text": "Output: In base In derived Thanks to Venki for adding this point. As a side note, it is a recommended practice to make reference arguments const if they are being passed by reference only due to reason no. 2 or 3 mentioned above. This is recommended to avoid unexpected modifications to the objects.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4209,
"s": 4190,
"text": "sunnychaudharyvlsi"
},
{
"code": null,
"e": 4221,
"s": 4209,
"text": "kziemianfvt"
},
{
"code": null,
"e": 4229,
"s": 4221,
"text": "pointer"
},
{
"code": null,
"e": 4240,
"s": 4229,
"text": "C Language"
},
{
"code": null,
"e": 4244,
"s": 4240,
"text": "C++"
},
{
"code": null,
"e": 4248,
"s": 4244,
"text": "CPP"
},
{
"code": null,
"e": 4346,
"s": 4248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4363,
"s": 4346,
"text": "Substring in C++"
},
{
"code": null,
"e": 4398,
"s": 4363,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 4444,
"s": 4398,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 4489,
"s": 4444,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4514,
"s": 4489,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4532,
"s": 4514,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 4575,
"s": 4532,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4621,
"s": 4575,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4664,
"s": 4621,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Bool data type in C++
|
05 Jun, 2017
The ISO/ANSI C++ Standard has added certain new data types to the original C++ specifications.They are provided to provide better control in certain situations as well as for providing conveniences to C++ programmers.One of the new data type is: boolSyntax:
bool b1 = true; // declaring a boolean variable with true value
In C++, the data type bool has been introduced to hold a boolean value, true or false.The values true or false have been added as keywords in the C++ language.Important Points:
The default numeric value of true is 1 and false is 0.
We can use bool type variables or values true and false in mathematical expressions also.For instance,int x = false + true + 6;is valid and the expression on right will evaluate to 7 as false has value 0 and true will have value 1.
int x = false + true + 6;
is valid and the expression on right will evaluate to 7 as false has value 0 and true will have value 1.
It is also possible to convert implicitly the data type integers or floating point values to bool type. For example, the statements-bool x = 0; // falsebool y = 100; // truebool z = 15.75; // true
bool x = 0; // falsebool y = 100; // truebool z = 15.75; // true
// CPP program to illustrate bool // data type in C++#include<iostream>using namespace std;int main(){ int x1 = 10, x2 = 20, m = 2; bool b1, b2; b1 = x1 == x2; // false b2 = x1 < x2; // true cout << "b1 is = " << b1 << "\n"; cout << "b2 is = " << b2 << "\n"; bool b3 = true; if (b3) cout << "Yes" << "\n"; else cout << "No" << "\n"; int x3 = false + 5 * m - b3; cout << x3; return 0; }
Output:
b1 is = 0
b2 is = 1
Yes
9
Related article: How to use Bool in C?
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-data-types
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
Virtual Function in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jun, 2017"
},
{
"code": null,
"e": 310,
"s": 52,
"text": "The ISO/ANSI C++ Standard has added certain new data types to the original C++ specifications.They are provided to provide better control in certain situations as well as for providing conveniences to C++ programmers.One of the new data type is: boolSyntax:"
},
{
"code": null,
"e": 382,
"s": 310,
"text": "bool b1 = true; // declaring a boolean variable with true value "
},
{
"code": null,
"e": 559,
"s": 382,
"text": "In C++, the data type bool has been introduced to hold a boolean value, true or false.The values true or false have been added as keywords in the C++ language.Important Points:"
},
{
"code": null,
"e": 614,
"s": 559,
"text": "The default numeric value of true is 1 and false is 0."
},
{
"code": null,
"e": 846,
"s": 614,
"text": "We can use bool type variables or values true and false in mathematical expressions also.For instance,int x = false + true + 6;is valid and the expression on right will evaluate to 7 as false has value 0 and true will have value 1."
},
{
"code": null,
"e": 872,
"s": 846,
"text": "int x = false + true + 6;"
},
{
"code": null,
"e": 977,
"s": 872,
"text": "is valid and the expression on right will evaluate to 7 as false has value 0 and true will have value 1."
},
{
"code": null,
"e": 1177,
"s": 977,
"text": "It is also possible to convert implicitly the data type integers or floating point values to bool type. For example, the statements-bool x = 0; // falsebool y = 100; // truebool z = 15.75; // true"
},
{
"code": "bool x = 0; // falsebool y = 100; // truebool z = 15.75; // true",
"e": 1245,
"s": 1177,
"text": null
},
{
"code": "// CPP program to illustrate bool // data type in C++#include<iostream>using namespace std;int main(){ int x1 = 10, x2 = 20, m = 2; bool b1, b2; b1 = x1 == x2; // false b2 = x1 < x2; // true cout << \"b1 is = \" << b1 << \"\\n\"; cout << \"b2 is = \" << b2 << \"\\n\"; bool b3 = true; if (b3) cout << \"Yes\" << \"\\n\"; else cout << \"No\" << \"\\n\"; int x3 = false + 5 * m - b3; cout << x3; return 0; }",
"e": 1716,
"s": 1245,
"text": null
},
{
"code": null,
"e": 1724,
"s": 1716,
"text": "Output:"
},
{
"code": null,
"e": 1751,
"s": 1724,
"text": "b1 is = 0\nb2 is = 1\nYes\n9\n"
},
{
"code": null,
"e": 1791,
"s": 1751,
"text": "Related article: How to use Bool in C? "
},
{
"code": null,
"e": 2094,
"s": 1791,
"text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2219,
"s": 2094,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2234,
"s": 2219,
"text": "cpp-data-types"
},
{
"code": null,
"e": 2238,
"s": 2234,
"text": "C++"
},
{
"code": null,
"e": 2242,
"s": 2238,
"text": "CPP"
},
{
"code": null,
"e": 2340,
"s": 2242,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2394,
"s": 2340,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2437,
"s": 2394,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2471,
"s": 2437,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2488,
"s": 2471,
"text": "Substring in C++"
},
{
"code": null,
"e": 2513,
"s": 2488,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 2537,
"s": 2513,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 2561,
"s": 2537,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2601,
"s": 2561,
"text": "2D Vector In C++ With User Defined Size"
},
{
"code": null,
"e": 2616,
"s": 2601,
"text": "C++ Data Types"
}
] |
How to Install FFmpeg on Windows?
|
05 Oct, 2021
The ffmpeg is a cross-platform & open-source software utility to record, convert and stream video/audio files. It can be used to:
Change the format of a video/audio file
Extract audio from video file
Merge audio and video streams
Change the bitrate of a video/audio file
Create GIF from a video file
Extract still images from a video file
To embed subtitles into a video file
To compress or resize a video/audio file
Record a live stream
In this article, we will show you how to install ffmpeg in Windows.
Follow the below steps to install FFmpeg on windows:
Step 1: Click here to download the zip file of the latest version. (As of September 2021, version 4.4 is the latest)
Step 2: Unzip this file by using any file archiver such as Winrar or 7z.
Step 3: Rename the extracted folder to ffmpeg and move it into the root of C: drive.
Step 4: Now, run cmd as an administrator and set the environment path variable for ffmpeg by running the following command:
setx /m PATH "C:\ffmpeg\bin;%PATH%"
Step 5: Restart your computer and verify the installation by running:
ffmpeg -version
how-to-install
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 185,
"s": 54,
"text": "The ffmpeg is a cross-platform & open-source software utility to record, convert and stream video/audio files. It can be used to:"
},
{
"code": null,
"e": 226,
"s": 185,
"text": "Change the format of a video/audio file"
},
{
"code": null,
"e": 256,
"s": 226,
"text": "Extract audio from video file"
},
{
"code": null,
"e": 286,
"s": 256,
"text": "Merge audio and video streams"
},
{
"code": null,
"e": 327,
"s": 286,
"text": "Change the bitrate of a video/audio file"
},
{
"code": null,
"e": 356,
"s": 327,
"text": "Create GIF from a video file"
},
{
"code": null,
"e": 395,
"s": 356,
"text": "Extract still images from a video file"
},
{
"code": null,
"e": 432,
"s": 395,
"text": "To embed subtitles into a video file"
},
{
"code": null,
"e": 473,
"s": 432,
"text": "To compress or resize a video/audio file"
},
{
"code": null,
"e": 494,
"s": 473,
"text": "Record a live stream"
},
{
"code": null,
"e": 562,
"s": 494,
"text": "In this article, we will show you how to install ffmpeg in Windows."
},
{
"code": null,
"e": 615,
"s": 562,
"text": "Follow the below steps to install FFmpeg on windows:"
},
{
"code": null,
"e": 732,
"s": 615,
"text": "Step 1: Click here to download the zip file of the latest version. (As of September 2021, version 4.4 is the latest)"
},
{
"code": null,
"e": 805,
"s": 732,
"text": "Step 2: Unzip this file by using any file archiver such as Winrar or 7z."
},
{
"code": null,
"e": 890,
"s": 805,
"text": "Step 3: Rename the extracted folder to ffmpeg and move it into the root of C: drive."
},
{
"code": null,
"e": 1014,
"s": 890,
"text": "Step 4: Now, run cmd as an administrator and set the environment path variable for ffmpeg by running the following command:"
},
{
"code": null,
"e": 1050,
"s": 1014,
"text": "setx /m PATH \"C:\\ffmpeg\\bin;%PATH%\""
},
{
"code": null,
"e": 1120,
"s": 1050,
"text": "Step 5: Restart your computer and verify the installation by running:"
},
{
"code": null,
"e": 1136,
"s": 1120,
"text": "ffmpeg -version"
},
{
"code": null,
"e": 1151,
"s": 1136,
"text": "how-to-install"
},
{
"code": null,
"e": 1158,
"s": 1151,
"text": "How To"
},
{
"code": null,
"e": 1177,
"s": 1158,
"text": "Installation Guide"
}
] |
Angular Material 7 - Slide Toggle
|
The <mat-slide-toggle>, an Angular Directive, is used as a on/off switch with material design styling and animation capabilities.
In this chapter, we will showcase the configuration required to draw a slide toggle 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 {MatSlideToggleModule, MatCheckboxModule} from '@angular/material'
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatSlideToggleModule, MatCheckboxModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<mat-slide-toggle
class = "tp-margin"
[checked] = "checked"
[disabled] = "disabled">
Slide!
</mat-slide-toggle>
<section class = "tp-section">
<mat-checkbox class = "tp-margin" [(ngModel)] = "checked">Checked</mat-checkbox>
<mat-checkbox class = "tp-margin" [(ngModel)] = "disabled">Disabled</mat-checkbox>
</section>
Following is the content of the modified CSS file app.component.css.
.tp-section {
display: flex;
align-content: center;
align-items: center;
height: 60px;
}
.tp-margin {
margin: 30px;
}
Following is the content of the modified ts file app.component.ts.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
disabled = false;
checked = false;
}
Verify the result.
As first, we've created two check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to handle the slide toggle.
As first, we've created two check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to handle the slide toggle.
Then, we've created the slide toggle and showcased its various attributes bound with variables in .ts file.
Then, we've created the slide toggle and showcased its various attributes bound with variables in .ts file.
|
[
{
"code": null,
"e": 3019,
"s": 2889,
"text": "The <mat-slide-toggle>, an Angular Directive, is used as a on/off switch with material design styling and animation capabilities."
},
{
"code": null,
"e": 3135,
"s": 3019,
"text": "In this chapter, we will showcase the configuration required to draw a slide toggle control using Angular Material."
},
{
"code": null,
"e": 3246,
"s": 3135,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −"
},
{
"code": null,
"e": 3320,
"s": 3246,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3918,
"s": 3320,
"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 {MatSlideToggleModule, MatCheckboxModule} from '@angular/material'\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatSlideToggleModule, MatCheckboxModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3994,
"s": 3918,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4339,
"s": 3994,
"text": "<mat-slide-toggle\n class = \"tp-margin\" \n [checked] = \"checked\"\n [disabled] = \"disabled\">\n Slide!\n</mat-slide-toggle>\n<section class = \"tp-section\">\n <mat-checkbox class = \"tp-margin\" [(ngModel)] = \"checked\">Checked</mat-checkbox>\n <mat-checkbox class = \"tp-margin\" [(ngModel)] = \"disabled\">Disabled</mat-checkbox>\n</section>"
},
{
"code": null,
"e": 4408,
"s": 4339,
"text": "Following is the content of the modified CSS file app.component.css."
},
{
"code": null,
"e": 4541,
"s": 4408,
"text": ".tp-section {\n display: flex;\n align-content: center;\n align-items: center;\n height: 60px;\n}\n.tp-margin {\n margin: 30px;\n}"
},
{
"code": null,
"e": 4608,
"s": 4541,
"text": "Following is the content of the modified ts file app.component.ts."
},
{
"code": null,
"e": 4869,
"s": 4608,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'materialApp'; \n disabled = false;\n checked = false; \n}"
},
{
"code": null,
"e": 4888,
"s": 4869,
"text": "Verify the result."
},
{
"code": null,
"e": 5049,
"s": 4888,
"text": "As first, we've created two check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to handle the slide toggle."
},
{
"code": null,
"e": 5210,
"s": 5049,
"text": "As first, we've created two check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to handle the slide toggle."
},
{
"code": null,
"e": 5318,
"s": 5210,
"text": "Then, we've created the slide toggle and showcased its various attributes bound with variables in .ts file."
}
] |
Find an N x N grid whose xor of every row and column is equal
|
17 Nov, 2021
Given an integer N which is a multiple of 4, the task is to find an N x N grid for which the bitwise xor of every row and column is the same.Examples:
Input: N = 4 Output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Input: N = 8 Output: 0 1 2 3 16 17 18 19 4 5 6 7 20 21 22 23 8 9 10 11 24 25 26 27 12 13 14 15 28 29 30 31 32 33 34 35 48 49 50 51 36 37 38 39 52 53 54 55 40 41 42 43 56 57 58 59 44 45 46 47 60 61 62 63
Approach: To solve this problem let’s fix the xor of every row and column to 0 since xor of 4 consecutive numbers starting from 0 is 0. Here is an example of a 4 x 4 matrix:
0 ^ 1 ^ 2 ^ 3 = 0 4 ^ 5 ^ 6 ^ 7 = 0 8 ^ 9 ^ 10 ^ 11 = 0 12 ^ 13 ^ 14 ^ 15 = 0 and so on.
If you notice in the above example, the xor of every row and column is 0. Now we need to place the numbers in such a way that the xor of each row and column is 0. So we can divide our N x N matrix into smaller 4 x 4 matrices with N / 4 rows and columns and fill the cells in a way that the xor of every row and column is 0.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; // Function to find the n x n matrix// that satisfies the given conditionvoid findGrid(int n){ int arr[n][n]; // Initialize x to 0 int x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (int i = 0; i < n / 4; i++) { for (int j = 0; j < n / 4; j++) { for (int k = 0; k < 4; k++) { for (int l = 0; l < 4; l++) { arr[i * 4 + k][j * 4 + l] = x; x++; } } } } // Print the generated matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << " "; } cout << "\n"; }} // Driver codeint main(){ int n = 4; findGrid(n); return 0;}
// Java implementation of the approachimport java.io.*; class GFG{ // Function to find the n x n matrix// that satisfies the given conditionstatic void findGrid(int n){ int [][]arr = new int[n][n]; // Initialize x to 0 int x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (int i = 0; i < n / 4; i++) { for (int j = 0; j < n / 4; j++) { for (int k = 0; k < 4; k++) { for (int l = 0; l < 4; l++) { arr[i * 4 + k][j * 4 + l] = x; x++; } } } } // Print the generated matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(arr[i][j] + " "); } System.out.println(" "); }} // Driver codepublic static void main (String[] args){ int n = 4; findGrid(n);}} // This code is contributed by ajit.
# Python3 implementation of the approach # Function to find the n x n matrix# that satisfies the given conditiondef findGrid(n): arr = [[0 for k in range(n)] for l in range(n)] # Initialize x to 0 x = 0 # Divide the n x n matrix into n / 4 matrices # for each of the n / 4 rows where # each matrix is of size 4 x 4 for i in range(n // 4): for j in range(n // 4): for k in range(4): for l in range(4): arr[i * 4 + k][j * 4 + l] = x x += 1 # Print the generated matrix for i in range(n): for j in range(n): print(arr[i][j], end = " ") print() # Driver coden = 4findGrid(n) # This code is contributed by divyamohan123
// C# implementation of the approachusing System; class GFG{ // Function to find the n x n matrix// that satisfies the given conditionstatic void findGrid(int n){ int [,]arr = new int[n, n]; // Initialize x to 0 int x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (int i = 0; i < n / 4; i++) { for (int j = 0; j < n / 4; j++) { for (int k = 0; k < 4; k++) { for (int l = 0; l < 4; l++) { arr[i * 4 + k, j * 4 + l] = x; x++; } } } } // Print the generated matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(arr[i, j] + " "); } Console.WriteLine(" "); }} // Driver codepublic static void Main (String[] args){ int n = 4; findGrid(n);}} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of the approach // Function to find the n x n matrix// that satisfies the given conditionfunction findGrid(n){ let arr = new Array(n); for (let i = 0; i < n; i++) arr[i] = new Array(n); // Initialize x to 0 let x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (let i = 0; i < parseInt(n / 4); i++) { for (let j = 0; j < parseInt(n / 4); j++) { for (let k = 0; k < 4; k++) { for (let l = 0; l < 4; l++) { arr[i * 4 + k][j * 4 + l] = x; x++; } } } } // Print the generated matrix for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { document.write(arr[i][j] + " "); } document.write("<br>"); }} // Driver code let n = 4; findGrid(n); </script>
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Time Complexity: O(N2)
Auxiliary Space: O(N2)
divyamohan123
jit_t
princiraj1992
subham348
subhammahato348
Bitwise-XOR
Bit Magic
Divide and Conquer
Mathematical
Matrix
Mathematical
Divide and Conquer
Bit Magic
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 207,
"s": 54,
"text": "Given an integer N which is a multiple of 4, the task is to find an N x N grid for which the bitwise xor of every row and column is the same.Examples: "
},
{
"code": null,
"e": 471,
"s": 207,
"text": "Input: N = 4 Output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Input: N = 8 Output: 0 1 2 3 16 17 18 19 4 5 6 7 20 21 22 23 8 9 10 11 24 25 26 27 12 13 14 15 28 29 30 31 32 33 34 35 48 49 50 51 36 37 38 39 52 53 54 55 40 41 42 43 56 57 58 59 44 45 46 47 60 61 62 63 "
},
{
"code": null,
"e": 649,
"s": 473,
"text": "Approach: To solve this problem let’s fix the xor of every row and column to 0 since xor of 4 consecutive numbers starting from 0 is 0. Here is an example of a 4 x 4 matrix: "
},
{
"code": null,
"e": 740,
"s": 649,
"text": "0 ^ 1 ^ 2 ^ 3 = 0 4 ^ 5 ^ 6 ^ 7 = 0 8 ^ 9 ^ 10 ^ 11 = 0 12 ^ 13 ^ 14 ^ 15 = 0 and so on. "
},
{
"code": null,
"e": 1116,
"s": 740,
"text": "If you notice in the above example, the xor of every row and column is 0. Now we need to place the numbers in such a way that the xor of each row and column is 0. So we can divide our N x N matrix into smaller 4 x 4 matrices with N / 4 rows and columns and fill the cells in a way that the xor of every row and column is 0.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1120,
"s": 1116,
"text": "C++"
},
{
"code": null,
"e": 1125,
"s": 1120,
"text": "Java"
},
{
"code": null,
"e": 1133,
"s": 1125,
"text": "Python3"
},
{
"code": null,
"e": 1136,
"s": 1133,
"text": "C#"
},
{
"code": null,
"e": 1147,
"s": 1136,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the n x n matrix// that satisfies the given conditionvoid findGrid(int n){ int arr[n][n]; // Initialize x to 0 int x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (int i = 0; i < n / 4; i++) { for (int j = 0; j < n / 4; j++) { for (int k = 0; k < 4; k++) { for (int l = 0; l < 4; l++) { arr[i * 4 + k][j * 4 + l] = x; x++; } } } } // Print the generated matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << \" \"; } cout << \"\\n\"; }} // Driver codeint main(){ int n = 4; findGrid(n); return 0;}",
"e": 2037,
"s": 1147,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function to find the n x n matrix// that satisfies the given conditionstatic void findGrid(int n){ int [][]arr = new int[n][n]; // Initialize x to 0 int x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (int i = 0; i < n / 4; i++) { for (int j = 0; j < n / 4; j++) { for (int k = 0; k < 4; k++) { for (int l = 0; l < 4; l++) { arr[i * 4 + k][j * 4 + l] = x; x++; } } } } // Print the generated matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(arr[i][j] + \" \"); } System.out.println(\" \"); }} // Driver codepublic static void main (String[] args){ int n = 4; findGrid(n);}} // This code is contributed by ajit.",
"e": 3060,
"s": 2037,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to find the n x n matrix# that satisfies the given conditiondef findGrid(n): arr = [[0 for k in range(n)] for l in range(n)] # Initialize x to 0 x = 0 # Divide the n x n matrix into n / 4 matrices # for each of the n / 4 rows where # each matrix is of size 4 x 4 for i in range(n // 4): for j in range(n // 4): for k in range(4): for l in range(4): arr[i * 4 + k][j * 4 + l] = x x += 1 # Print the generated matrix for i in range(n): for j in range(n): print(arr[i][j], end = \" \") print() # Driver coden = 4findGrid(n) # This code is contributed by divyamohan123",
"e": 3815,
"s": 3060,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to find the n x n matrix// that satisfies the given conditionstatic void findGrid(int n){ int [,]arr = new int[n, n]; // Initialize x to 0 int x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (int i = 0; i < n / 4; i++) { for (int j = 0; j < n / 4; j++) { for (int k = 0; k < 4; k++) { for (int l = 0; l < 4; l++) { arr[i * 4 + k, j * 4 + l] = x; x++; } } } } // Print the generated matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(arr[i, j] + \" \"); } Console.WriteLine(\" \"); }} // Driver codepublic static void Main (String[] args){ int n = 4; findGrid(n);}} // This code is contributed by PrinciRaj1992",
"e": 4839,
"s": 3815,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to find the n x n matrix// that satisfies the given conditionfunction findGrid(n){ let arr = new Array(n); for (let i = 0; i < n; i++) arr[i] = new Array(n); // Initialize x to 0 let x = 0; // Divide the n x n matrix into n / 4 matrices // for each of the n / 4 rows where // each matrix is of size 4 x 4 for (let i = 0; i < parseInt(n / 4); i++) { for (let j = 0; j < parseInt(n / 4); j++) { for (let k = 0; k < 4; k++) { for (let l = 0; l < 4; l++) { arr[i * 4 + k][j * 4 + l] = x; x++; } } } } // Print the generated matrix for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { document.write(arr[i][j] + \" \"); } document.write(\"<br>\"); }} // Driver code let n = 4; findGrid(n); </script>",
"e": 5792,
"s": 4839,
"text": null
},
{
"code": null,
"e": 5833,
"s": 5792,
"text": "0 1 2 3 \n4 5 6 7 \n8 9 10 11 \n12 13 14 15"
},
{
"code": null,
"e": 5858,
"s": 5835,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 5882,
"s": 5858,
"text": "Auxiliary Space: O(N2) "
},
{
"code": null,
"e": 5896,
"s": 5882,
"text": "divyamohan123"
},
{
"code": null,
"e": 5902,
"s": 5896,
"text": "jit_t"
},
{
"code": null,
"e": 5916,
"s": 5902,
"text": "princiraj1992"
},
{
"code": null,
"e": 5926,
"s": 5916,
"text": "subham348"
},
{
"code": null,
"e": 5942,
"s": 5926,
"text": "subhammahato348"
},
{
"code": null,
"e": 5954,
"s": 5942,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 5964,
"s": 5954,
"text": "Bit Magic"
},
{
"code": null,
"e": 5983,
"s": 5964,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5996,
"s": 5983,
"text": "Mathematical"
},
{
"code": null,
"e": 6003,
"s": 5996,
"text": "Matrix"
},
{
"code": null,
"e": 6016,
"s": 6003,
"text": "Mathematical"
},
{
"code": null,
"e": 6035,
"s": 6016,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 6045,
"s": 6035,
"text": "Bit Magic"
},
{
"code": null,
"e": 6052,
"s": 6045,
"text": "Matrix"
}
] |
Number of ways to place two queens on a N*N chess-board
|
23 Jun, 2022
Given an integer N denoting a N * N chess-board, the task is to count the number of ways to place two queens on the board such that, they do no attack each other.Examples:
Input: N = 9 Output: 2184 Explanation: There are 2184 ways to place two queens on 9 * 9 chess-board.Input: N = 3 Output: 8 Explanation: There are 8 ways to place two queens on 3 * 3 chess-board.
Naive Approach: A simple solution will be to choose two every possible position for the two queens on the N * N matrix and check that they are not in horizontal, vertical, positive diagonal or negative diagonal. If yes then increment the count by 1. Time Complexity: O(N4)Efficient Approach: The idea is to use combinations to compute the possible positions of the queens such that they do not attack each other. A useful observation is that it is quite easy to calculate the number of positions that a single queen attacks. That is –
Number of positions a queen attack =
(N - 1) + (N - 1) + (D - 1)
Here,
// First N-1 denotes positions in horizontal direction
// Second N-1 denotes positions in vertical direction
// D = Number of positions in
positive and negative diagonal
If we do not place the queen on the last row and the last column then the answer will simply be the number of positions to place in a chessboard of whereas if we place in the last column and last row then possible positions for queens will be and attacking at positions. Therefore, the possible positions for the other queen for each position of the queen will be . Finally, there are combinations where both queens are on the last row and last column. Therefore, the recurrence relation will be:
// By Induction
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// number of ways to place two// queens on the N * N chess board #include <bits/stdc++.h> #define ll long longusing namespace std; // Function to find number of valid// positions for two queens in the// N * N chess boardll possiblePositions(ll n){ ll term1 = pow(n, 4); ll term2 = pow(n, 3); ll term3 = pow(n, 2); ll term4 = n / 3; ll ans = (ceil)(term1) / 2 - (ceil)(5 * term2) / 3 + (ceil)(3 * term3) / 2 - term4; return ans;} // Driver Codeint main(){ ll n; n = 3; // Function Call ll ans = possiblePositions(n); cout << ans << endl; return 0;}
// Java implementation to find the// number of ways to place two// queens on the N * N chess boardclass GFG{ // Function to find number of valid// positions for two queens in the// N * N chess boardstatic double possiblePositions(double n){ double term1 = Math.pow(n, 4); double term2 = Math.pow(n, 3); double term3 = Math.pow(n, 2); double term4 = n / 3; double ans = (Math.ceil(term1 / 2)) - (Math.ceil(5 * term2) / 3) + (Math.ceil(3 * term3) / 2) - term4; return (long)ans;} // Driver Codepublic static void main(String[] args){ double n; n = 3; // Function Call double ans = possiblePositions(n); System.out.print(ans + "\n");}} // This code is contributed by sapnasingh4991
# Python3 implementation to find the# number of ways to place two# queens on the N * N chess boardimport math # Function to find number of valid# positions for two queens in the# N * N chess boarddef possiblePositions(n): term1 = pow(n, 4); term2 = pow(n, 3); term3 = pow(n, 2); term4 = n / 3; ans = ((math.ceil(term1)) / 2 - (math.ceil(5 * term2)) / 3 + (math.ceil(3 * term3)) / 2 - term4); return ans; # Driver codeif __name__ == '__main__': n = 3 # Function call ans = possiblePositions(n) print(int(ans)) # This code is contributed by jana_sayantan
// C# implementation to find the// number of ways to place two// queens on the N * N chess boardusing System; class GFG{ // Function to find number of valid// positions for two queens in the// N * N chess boardstatic double possiblePositions(double n){ double term1 = Math.Pow(n, 4); double term2 = Math.Pow(n, 3); double term3 = Math.Pow(n, 2); double term4 = n / 3; double ans = (Math.Ceiling(term1 / 2)) - (Math.Ceiling(5 * term2) / 3) + (Math.Ceiling(3 * term3) / 2) - term4; return (long)ans;} // Driver Codepublic static void Main(String[] args){ double n; n = 3; // Function Call double ans = possiblePositions(n); Console.Write(ans + "\n");}} // This code is contributed by Amit Katiyar
<script> // Javascript implementation to find the// number of ways to place two// queens on the N * N chess board // Function to find number of valid// positions for two queens in the// N * N chess boardfunction possiblePositions(n){ let term1 = Math.pow(n, 4); let term2 = Math.pow(n, 3); let term3 = Math.pow(n, 2); let term4 = n / 3; let ans = (Math.ceil(term1 / 2)) - (Math.ceil(5 * term2) / 3) + (Math.ceil(3 * term3) / 2) - term4; return ans;} // Driver Code let n; n = 3; // Function Call let ans = possiblePositions(n); document.write(Math.floor(ans)); // This code is contributed by souravghosh0416.</script>
8
Time Complexity: O(1)
sapnasingh4991
amit143katiyar
jana_sayantan
souravghosh0416
nthung
chessboard-problems
Analysis
Combinatorial
Mathematical
Pattern Searching
Mathematical
Combinatorial
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between Deterministic and Non-deterministic Algorithms
What is algorithm and why analysis of it is important?
Time-Space Trade-Off in Algorithms
Complexity analysis of various operations of Binary Min Heap
Write a program to print all permutations of a given string
Permutation and Combination in Python
Count of subsets with sum equal to X
Factorial of a large number
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "Given an integer N denoting a N * N chess-board, the task is to count the number of ways to place two queens on the board such that, they do no attack each other.Examples:"
},
{
"code": null,
"e": 395,
"s": 200,
"text": "Input: N = 9 Output: 2184 Explanation: There are 2184 ways to place two queens on 9 * 9 chess-board.Input: N = 3 Output: 8 Explanation: There are 8 ways to place two queens on 3 * 3 chess-board."
},
{
"code": null,
"e": 930,
"s": 395,
"text": "Naive Approach: A simple solution will be to choose two every possible position for the two queens on the N * N matrix and check that they are not in horizontal, vertical, positive diagonal or negative diagonal. If yes then increment the count by 1. Time Complexity: O(N4)Efficient Approach: The idea is to use combinations to compute the possible positions of the queens such that they do not attack each other. A useful observation is that it is quite easy to calculate the number of positions that a single queen attacks. That is –"
},
{
"code": null,
"e": 1183,
"s": 930,
"text": "Number of positions a queen attack = \n (N - 1) + (N - 1) + (D - 1)\n\nHere, \n// First N-1 denotes positions in horizontal direction\n// Second N-1 denotes positions in vertical direction\n// D = Number of positions in \n positive and negative diagonal"
},
{
"code": null,
"e": 1683,
"s": 1183,
"text": "If we do not place the queen on the last row and the last column then the answer will simply be the number of positions to place in a chessboard of whereas if we place in the last column and last row then possible positions for queens will be and attacking at positions. Therefore, the possible positions for the other queen for each position of the queen will be . Finally, there are combinations where both queens are on the last row and last column. Therefore, the recurrence relation will be:"
},
{
"code": null,
"e": 1699,
"s": 1683,
"text": "// By Induction"
},
{
"code": null,
"e": 1750,
"s": 1699,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1754,
"s": 1750,
"text": "C++"
},
{
"code": null,
"e": 1759,
"s": 1754,
"text": "Java"
},
{
"code": null,
"e": 1767,
"s": 1759,
"text": "Python3"
},
{
"code": null,
"e": 1770,
"s": 1767,
"text": "C#"
},
{
"code": null,
"e": 1781,
"s": 1770,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// number of ways to place two// queens on the N * N chess board #include <bits/stdc++.h> #define ll long longusing namespace std; // Function to find number of valid// positions for two queens in the// N * N chess boardll possiblePositions(ll n){ ll term1 = pow(n, 4); ll term2 = pow(n, 3); ll term3 = pow(n, 2); ll term4 = n / 3; ll ans = (ceil)(term1) / 2 - (ceil)(5 * term2) / 3 + (ceil)(3 * term3) / 2 - term4; return ans;} // Driver Codeint main(){ ll n; n = 3; // Function Call ll ans = possiblePositions(n); cout << ans << endl; return 0;}",
"e": 2427,
"s": 1781,
"text": null
},
{
"code": "// Java implementation to find the// number of ways to place two// queens on the N * N chess boardclass GFG{ // Function to find number of valid// positions for two queens in the// N * N chess boardstatic double possiblePositions(double n){ double term1 = Math.pow(n, 4); double term2 = Math.pow(n, 3); double term3 = Math.pow(n, 2); double term4 = n / 3; double ans = (Math.ceil(term1 / 2)) - (Math.ceil(5 * term2) / 3) + (Math.ceil(3 * term3) / 2) - term4; return (long)ans;} // Driver Codepublic static void main(String[] args){ double n; n = 3; // Function Call double ans = possiblePositions(n); System.out.print(ans + \"\\n\");}} // This code is contributed by sapnasingh4991",
"e": 3177,
"s": 2427,
"text": null
},
{
"code": "# Python3 implementation to find the# number of ways to place two# queens on the N * N chess boardimport math # Function to find number of valid# positions for two queens in the# N * N chess boarddef possiblePositions(n): term1 = pow(n, 4); term2 = pow(n, 3); term3 = pow(n, 2); term4 = n / 3; ans = ((math.ceil(term1)) / 2 - (math.ceil(5 * term2)) / 3 + (math.ceil(3 * term3)) / 2 - term4); return ans; # Driver codeif __name__ == '__main__': n = 3 # Function call ans = possiblePositions(n) print(int(ans)) # This code is contributed by jana_sayantan",
"e": 3813,
"s": 3177,
"text": null
},
{
"code": "// C# implementation to find the// number of ways to place two// queens on the N * N chess boardusing System; class GFG{ // Function to find number of valid// positions for two queens in the// N * N chess boardstatic double possiblePositions(double n){ double term1 = Math.Pow(n, 4); double term2 = Math.Pow(n, 3); double term3 = Math.Pow(n, 2); double term4 = n / 3; double ans = (Math.Ceiling(term1 / 2)) - (Math.Ceiling(5 * term2) / 3) + (Math.Ceiling(3 * term3) / 2) - term4; return (long)ans;} // Driver Codepublic static void Main(String[] args){ double n; n = 3; // Function Call double ans = possiblePositions(n); Console.Write(ans + \"\\n\");}} // This code is contributed by Amit Katiyar",
"e": 4579,
"s": 3813,
"text": null
},
{
"code": "<script> // Javascript implementation to find the// number of ways to place two// queens on the N * N chess board // Function to find number of valid// positions for two queens in the// N * N chess boardfunction possiblePositions(n){ let term1 = Math.pow(n, 4); let term2 = Math.pow(n, 3); let term3 = Math.pow(n, 2); let term4 = n / 3; let ans = (Math.ceil(term1 / 2)) - (Math.ceil(5 * term2) / 3) + (Math.ceil(3 * term3) / 2) - term4; return ans;} // Driver Code let n; n = 3; // Function Call let ans = possiblePositions(n); document.write(Math.floor(ans)); // This code is contributed by souravghosh0416.</script>",
"e": 5276,
"s": 4579,
"text": null
},
{
"code": null,
"e": 5278,
"s": 5276,
"text": "8"
},
{
"code": null,
"e": 5301,
"s": 5278,
"text": "Time Complexity: O(1) "
},
{
"code": null,
"e": 5316,
"s": 5301,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 5331,
"s": 5316,
"text": "amit143katiyar"
},
{
"code": null,
"e": 5345,
"s": 5331,
"text": "jana_sayantan"
},
{
"code": null,
"e": 5361,
"s": 5345,
"text": "souravghosh0416"
},
{
"code": null,
"e": 5368,
"s": 5361,
"text": "nthung"
},
{
"code": null,
"e": 5388,
"s": 5368,
"text": "chessboard-problems"
},
{
"code": null,
"e": 5397,
"s": 5388,
"text": "Analysis"
},
{
"code": null,
"e": 5411,
"s": 5397,
"text": "Combinatorial"
},
{
"code": null,
"e": 5424,
"s": 5411,
"text": "Mathematical"
},
{
"code": null,
"e": 5442,
"s": 5424,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5455,
"s": 5442,
"text": "Mathematical"
},
{
"code": null,
"e": 5469,
"s": 5455,
"text": "Combinatorial"
},
{
"code": null,
"e": 5487,
"s": 5469,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5585,
"s": 5487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5652,
"s": 5585,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 5718,
"s": 5652,
"text": "Difference between Deterministic and Non-deterministic Algorithms"
},
{
"code": null,
"e": 5773,
"s": 5718,
"text": "What is algorithm and why analysis of it is important?"
},
{
"code": null,
"e": 5808,
"s": 5773,
"text": "Time-Space Trade-Off in Algorithms"
},
{
"code": null,
"e": 5869,
"s": 5808,
"text": "Complexity analysis of various operations of Binary Min Heap"
},
{
"code": null,
"e": 5929,
"s": 5869,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5967,
"s": 5929,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 6004,
"s": 5967,
"text": "Count of subsets with sum equal to X"
}
] |
MariaDB - Useful Functions
|
This chapter contains a list of the most frequently used functions, offering definitions, explanations, and examples.
Most frequently used aggregate functions are given below −
COUNT
It counts the number of records.
Example − SELECT COUNT(*) FROM customer_table;
MIN
It reveals the minimum value of a set of records.
Example − SELECT organization, MIN(account) FROM contracts GROUP BY organization;
MAX
It reveals the maximum value of a set of records.
Example − SELECT organization, MAX(account_size) FROM contracts GROUP BY organization;
AVG
It calculates the average value of a set of records.
Example − SELECT AVG(account_size) FROM contracts;
SUM
It calculates the sum of a set of records.
Example − SELECT SUM(account_size) FROM contracts;
The TIMESTAMPDIFF function provides a way to calculate age −
SELECT CURDATE() AS today;
SELECT ID, DOB, TIMESTAMPDIFF(YEAR,DOB,'2015-07-01') AS age FROM officer_info;
The CONCAT function returns the resulting string after a concatenation operation. You can utilize one or more arguments. Review its syntax given below −
SELECT CONCAT(item, item,...);
Review the following example −
SELECT CONCAT('Ram', 'bu', 'tan');
Output:Rambutan
Given below are important date functions −
CURDATE()
It returns the date in yyyy-mm-dd or yyyymmdd format.
Example − SELECT CURDATE();
DATE()
It returns the date in multiple formats.
Example −CREATE TABLE product_release_tbl (x DATE);
CURTIME()
It returns the time in HH:MM:SS or HHMMSS.uuuuuu format.
Example − SELECT CURTIME();
DATE_SUB()
It adds or subtracts a number of days from the specified date.
Example − SELECT DATE_SUB('2016-02-08', INTERVAL 60 DAY);
DATEDIFF()
It determines the days between two dates.
Example − SELECT DATEDIFF('2016-01-01 23:59:59','2016-01-03');
DATE ADD()
It adds or subtracts any unit of time to/from the date and time.
Example − SELECT DATE_ADD('2016-01-04 23:59:59', INTERVAL 22 SECOND);
EXTRACT()
It extracts a unit from the date.
Example − SELECT EXTRACT(YEAR FROM '2016-01-08');
NOW()
It returns the current date and time in either yyyy-mm-dd hh:mm:ss or yyyymmddhhmmss.uuuuuu format.
Example − SELECT NOW();
DATE FORMAT()
It formats the date in accordance with the specified format string.
Example − SELECT DATE_FORMAT('2016-01-09 20:20:00', '%W %M %Y');
Following are some important time functions −
HOUR()
It returns the hour of the time, or the hours elapsed.
Example − SELECT HOUR('19:17:09');
LOCALTIME()
It functions exactly like NOW().
MICROSECOND()
It returns the microseconds of the time.
Example − SELECT MICROSECOND('16:30:00.543876');
MINUTE()
It returns the minutes of the time.
Example − SELECT MINUTE('2016-05-22 17:22:01');
SECOND()
It returns the seconds of the date.
Example − SELECT SECOND('2016-03-12 16:30:04.000001');
TIME_FORMAT()
It formats the time in accordance with the specified format string.
Example − SELECT TIME_FORMAT('22:02:20', '%H %k %h %I %l');
TIMESTAMP()
It provides a timestamp for an activity in the format yyyy-mm-dd hh:mm:dd.
Example − CREATE TABLE orders_ (ID INT, tmst TIMESTAMP);
Given below are some important numeric functions in MariaDB −
TRUNCATE()
It returns a truncated number to decimal place specification.
Example − SELECT TRUNCATE(101.222, 1);
COS()
It returns the cosine of x radians.
Example − SELECT COS(PI());
CEILING()
It returns the smallest integer not below x.
Example − SELECT CEILING(2.11);
DEGREES()
It converts radians to degrees.
Example − SELECT DEGREES(PI());
DIV()
It performs integer division.
Example − SELECT 100 DIV 4;
EXP()
It returns e to the power of x.
Example − SELECT EXP(2);
FLOOR()
It returns the largest integer not above x.
Example − SELECT FLOOR(2.01);
LN()
It returns the natural logarithm of x.
Example − SELECT LN(3);
LOG()
It returns the natural logarithm or the logarithm to a given base.
Example − SELECT LOG(3);
SQRT()
It returns the square root.
Example − SELECT SQRT(16);
Important string functions are given below −
INSTR()
It returns the position of the first instance of a substring.
Example − SELECT INSTR('rambutan', 'tan');
RIGHT()
It returns the rightmost string characters.
Example − SELECT RIGHT('rambutan', 3);
LENGTH()
It returns the byte length of a string.
Example − SELECT LENGTH('rambutan');
LOCATE()
It returns the position of the first instance of a substring.
Example − SELECT LOCATE('tan', 'rambutan');
INSERT()
It returns a string, with a specified substring at a certain position, that was modified.
Example − SELECT INSERT('ramputan', 4, 1, 'b');
LEFT()
It returns the leftmost characters.
Example − SELECT LEFT('rambutan', 3);
UPPER()
It changes characters to uppercase.
Example − SELECT UPPER(lastname);
LOWER()
It changes characters to lowercase.
Example − SELECT LOWER(lastname);
STRCMP()
It compares strings and returns 0 when they are equal.
Example − SELECT STRCMP('egg', 'cheese');
REPLACE()
It returns a string after replacing characters.
Example − SELECT REPLACE('sully', 'l', 'n');
REVERSE()
It reverses characters in a string.
Example − SELECT REVERSE('racecar');
REPEAT()
It returns a string repeating given characters x times.
Example − SELECT REPEAT('ha ', 10);
SUBSTRING()
It returns a substring from a string, starting at position x.
Example − SELECT SUBSTRING('rambutan',3);
TRIM()
It removes trailing/leading characters from a string.
Example − SELECT TRIM(LEADING '_' FROM '_rambutan');
|
[
{
"code": null,
"e": 2614,
"s": 2496,
"text": "This chapter contains a list of the most frequently used functions, offering definitions, explanations, and examples."
},
{
"code": null,
"e": 2673,
"s": 2614,
"text": "Most frequently used aggregate functions are given below −"
},
{
"code": null,
"e": 2679,
"s": 2673,
"text": "COUNT"
},
{
"code": null,
"e": 2712,
"s": 2679,
"text": "It counts the number of records."
},
{
"code": null,
"e": 2759,
"s": 2712,
"text": "Example − SELECT COUNT(*) FROM customer_table;"
},
{
"code": null,
"e": 2763,
"s": 2759,
"text": "MIN"
},
{
"code": null,
"e": 2813,
"s": 2763,
"text": "It reveals the minimum value of a set of records."
},
{
"code": null,
"e": 2895,
"s": 2813,
"text": "Example − SELECT organization, MIN(account) FROM contracts GROUP BY organization;"
},
{
"code": null,
"e": 2899,
"s": 2895,
"text": "MAX"
},
{
"code": null,
"e": 2949,
"s": 2899,
"text": "It reveals the maximum value of a set of records."
},
{
"code": null,
"e": 3036,
"s": 2949,
"text": "Example − SELECT organization, MAX(account_size) FROM contracts GROUP BY organization;"
},
{
"code": null,
"e": 3040,
"s": 3036,
"text": "AVG"
},
{
"code": null,
"e": 3093,
"s": 3040,
"text": "It calculates the average value of a set of records."
},
{
"code": null,
"e": 3144,
"s": 3093,
"text": "Example − SELECT AVG(account_size) FROM contracts;"
},
{
"code": null,
"e": 3148,
"s": 3144,
"text": "SUM"
},
{
"code": null,
"e": 3191,
"s": 3148,
"text": "It calculates the sum of a set of records."
},
{
"code": null,
"e": 3242,
"s": 3191,
"text": "Example − SELECT SUM(account_size) FROM contracts;"
},
{
"code": null,
"e": 3303,
"s": 3242,
"text": "The TIMESTAMPDIFF function provides a way to calculate age −"
},
{
"code": null,
"e": 3410,
"s": 3303,
"text": "SELECT CURDATE() AS today;\nSELECT ID, DOB, TIMESTAMPDIFF(YEAR,DOB,'2015-07-01') AS age FROM officer_info;\n"
},
{
"code": null,
"e": 3563,
"s": 3410,
"text": "The CONCAT function returns the resulting string after a concatenation operation. You can utilize one or more arguments. Review its syntax given below −"
},
{
"code": null,
"e": 3595,
"s": 3563,
"text": "SELECT CONCAT(item, item,...);\n"
},
{
"code": null,
"e": 3626,
"s": 3595,
"text": "Review the following example −"
},
{
"code": null,
"e": 3678,
"s": 3626,
"text": "SELECT CONCAT('Ram', 'bu', 'tan');\nOutput:Rambutan\n"
},
{
"code": null,
"e": 3721,
"s": 3678,
"text": "Given below are important date functions −"
},
{
"code": null,
"e": 3731,
"s": 3721,
"text": "CURDATE()"
},
{
"code": null,
"e": 3785,
"s": 3731,
"text": "It returns the date in yyyy-mm-dd or yyyymmdd format."
},
{
"code": null,
"e": 3813,
"s": 3785,
"text": "Example − SELECT CURDATE();"
},
{
"code": null,
"e": 3820,
"s": 3813,
"text": "DATE()"
},
{
"code": null,
"e": 3861,
"s": 3820,
"text": "It returns the date in multiple formats."
},
{
"code": null,
"e": 3913,
"s": 3861,
"text": "Example −CREATE TABLE product_release_tbl (x DATE);"
},
{
"code": null,
"e": 3923,
"s": 3913,
"text": "CURTIME()"
},
{
"code": null,
"e": 3980,
"s": 3923,
"text": "It returns the time in HH:MM:SS or HHMMSS.uuuuuu format."
},
{
"code": null,
"e": 4008,
"s": 3980,
"text": "Example − SELECT CURTIME();"
},
{
"code": null,
"e": 4019,
"s": 4008,
"text": "DATE_SUB()"
},
{
"code": null,
"e": 4082,
"s": 4019,
"text": "It adds or subtracts a number of days from the specified date."
},
{
"code": null,
"e": 4140,
"s": 4082,
"text": "Example − SELECT DATE_SUB('2016-02-08', INTERVAL 60 DAY);"
},
{
"code": null,
"e": 4151,
"s": 4140,
"text": "DATEDIFF()"
},
{
"code": null,
"e": 4193,
"s": 4151,
"text": "It determines the days between two dates."
},
{
"code": null,
"e": 4256,
"s": 4193,
"text": "Example − SELECT DATEDIFF('2016-01-01 23:59:59','2016-01-03');"
},
{
"code": null,
"e": 4267,
"s": 4256,
"text": "DATE ADD()"
},
{
"code": null,
"e": 4332,
"s": 4267,
"text": "It adds or subtracts any unit of time to/from the date and time."
},
{
"code": null,
"e": 4402,
"s": 4332,
"text": "Example − SELECT DATE_ADD('2016-01-04 23:59:59', INTERVAL 22 SECOND);"
},
{
"code": null,
"e": 4412,
"s": 4402,
"text": "EXTRACT()"
},
{
"code": null,
"e": 4446,
"s": 4412,
"text": "It extracts a unit from the date."
},
{
"code": null,
"e": 4496,
"s": 4446,
"text": "Example − SELECT EXTRACT(YEAR FROM '2016-01-08');"
},
{
"code": null,
"e": 4502,
"s": 4496,
"text": "NOW()"
},
{
"code": null,
"e": 4602,
"s": 4502,
"text": "It returns the current date and time in either yyyy-mm-dd hh:mm:ss or yyyymmddhhmmss.uuuuuu format."
},
{
"code": null,
"e": 4626,
"s": 4602,
"text": "Example − SELECT NOW();"
},
{
"code": null,
"e": 4640,
"s": 4626,
"text": "DATE FORMAT()"
},
{
"code": null,
"e": 4708,
"s": 4640,
"text": "It formats the date in accordance with the specified format string."
},
{
"code": null,
"e": 4773,
"s": 4708,
"text": "Example − SELECT DATE_FORMAT('2016-01-09 20:20:00', '%W %M %Y');"
},
{
"code": null,
"e": 4819,
"s": 4773,
"text": "Following are some important time functions −"
},
{
"code": null,
"e": 4826,
"s": 4819,
"text": "HOUR()"
},
{
"code": null,
"e": 4881,
"s": 4826,
"text": "It returns the hour of the time, or the hours elapsed."
},
{
"code": null,
"e": 4916,
"s": 4881,
"text": "Example − SELECT HOUR('19:17:09');"
},
{
"code": null,
"e": 4928,
"s": 4916,
"text": "LOCALTIME()"
},
{
"code": null,
"e": 4961,
"s": 4928,
"text": "It functions exactly like NOW()."
},
{
"code": null,
"e": 4975,
"s": 4961,
"text": "MICROSECOND()"
},
{
"code": null,
"e": 5016,
"s": 4975,
"text": "It returns the microseconds of the time."
},
{
"code": null,
"e": 5065,
"s": 5016,
"text": "Example − SELECT MICROSECOND('16:30:00.543876');"
},
{
"code": null,
"e": 5074,
"s": 5065,
"text": "MINUTE()"
},
{
"code": null,
"e": 5110,
"s": 5074,
"text": "It returns the minutes of the time."
},
{
"code": null,
"e": 5158,
"s": 5110,
"text": "Example − SELECT MINUTE('2016-05-22 17:22:01');"
},
{
"code": null,
"e": 5167,
"s": 5158,
"text": "SECOND()"
},
{
"code": null,
"e": 5203,
"s": 5167,
"text": "It returns the seconds of the date."
},
{
"code": null,
"e": 5258,
"s": 5203,
"text": "Example − SELECT SECOND('2016-03-12 16:30:04.000001');"
},
{
"code": null,
"e": 5272,
"s": 5258,
"text": "TIME_FORMAT()"
},
{
"code": null,
"e": 5340,
"s": 5272,
"text": "It formats the time in accordance with the specified format string."
},
{
"code": null,
"e": 5400,
"s": 5340,
"text": "Example − SELECT TIME_FORMAT('22:02:20', '%H %k %h %I %l');"
},
{
"code": null,
"e": 5412,
"s": 5400,
"text": "TIMESTAMP()"
},
{
"code": null,
"e": 5487,
"s": 5412,
"text": "It provides a timestamp for an activity in the format yyyy-mm-dd hh:mm:dd."
},
{
"code": null,
"e": 5544,
"s": 5487,
"text": "Example − CREATE TABLE orders_ (ID INT, tmst TIMESTAMP);"
},
{
"code": null,
"e": 5606,
"s": 5544,
"text": "Given below are some important numeric functions in MariaDB −"
},
{
"code": null,
"e": 5617,
"s": 5606,
"text": "TRUNCATE()"
},
{
"code": null,
"e": 5679,
"s": 5617,
"text": "It returns a truncated number to decimal place specification."
},
{
"code": null,
"e": 5718,
"s": 5679,
"text": "Example − SELECT TRUNCATE(101.222, 1);"
},
{
"code": null,
"e": 5724,
"s": 5718,
"text": "COS()"
},
{
"code": null,
"e": 5760,
"s": 5724,
"text": "It returns the cosine of x radians."
},
{
"code": null,
"e": 5788,
"s": 5760,
"text": "Example − SELECT COS(PI());"
},
{
"code": null,
"e": 5798,
"s": 5788,
"text": "CEILING()"
},
{
"code": null,
"e": 5843,
"s": 5798,
"text": "It returns the smallest integer not below x."
},
{
"code": null,
"e": 5875,
"s": 5843,
"text": "Example − SELECT CEILING(2.11);"
},
{
"code": null,
"e": 5885,
"s": 5875,
"text": "DEGREES()"
},
{
"code": null,
"e": 5917,
"s": 5885,
"text": "It converts radians to degrees."
},
{
"code": null,
"e": 5949,
"s": 5917,
"text": "Example − SELECT DEGREES(PI());"
},
{
"code": null,
"e": 5955,
"s": 5949,
"text": "DIV()"
},
{
"code": null,
"e": 5985,
"s": 5955,
"text": "It performs integer division."
},
{
"code": null,
"e": 6013,
"s": 5985,
"text": "Example − SELECT 100 DIV 4;"
},
{
"code": null,
"e": 6019,
"s": 6013,
"text": "EXP()"
},
{
"code": null,
"e": 6051,
"s": 6019,
"text": "It returns e to the power of x."
},
{
"code": null,
"e": 6076,
"s": 6051,
"text": "Example − SELECT EXP(2);"
},
{
"code": null,
"e": 6084,
"s": 6076,
"text": "FLOOR()"
},
{
"code": null,
"e": 6128,
"s": 6084,
"text": "It returns the largest integer not above x."
},
{
"code": null,
"e": 6158,
"s": 6128,
"text": "Example − SELECT FLOOR(2.01);"
},
{
"code": null,
"e": 6163,
"s": 6158,
"text": "LN()"
},
{
"code": null,
"e": 6202,
"s": 6163,
"text": "It returns the natural logarithm of x."
},
{
"code": null,
"e": 6226,
"s": 6202,
"text": "Example − SELECT LN(3);"
},
{
"code": null,
"e": 6232,
"s": 6226,
"text": "LOG()"
},
{
"code": null,
"e": 6299,
"s": 6232,
"text": "It returns the natural logarithm or the logarithm to a given base."
},
{
"code": null,
"e": 6324,
"s": 6299,
"text": "Example − SELECT LOG(3);"
},
{
"code": null,
"e": 6331,
"s": 6324,
"text": "SQRT()"
},
{
"code": null,
"e": 6359,
"s": 6331,
"text": "It returns the square root."
},
{
"code": null,
"e": 6386,
"s": 6359,
"text": "Example − SELECT SQRT(16);"
},
{
"code": null,
"e": 6431,
"s": 6386,
"text": "Important string functions are given below −"
},
{
"code": null,
"e": 6439,
"s": 6431,
"text": "INSTR()"
},
{
"code": null,
"e": 6501,
"s": 6439,
"text": "It returns the position of the first instance of a substring."
},
{
"code": null,
"e": 6544,
"s": 6501,
"text": "Example − SELECT INSTR('rambutan', 'tan');"
},
{
"code": null,
"e": 6552,
"s": 6544,
"text": "RIGHT()"
},
{
"code": null,
"e": 6596,
"s": 6552,
"text": "It returns the rightmost string characters."
},
{
"code": null,
"e": 6635,
"s": 6596,
"text": "Example − SELECT RIGHT('rambutan', 3);"
},
{
"code": null,
"e": 6644,
"s": 6635,
"text": "LENGTH()"
},
{
"code": null,
"e": 6684,
"s": 6644,
"text": "It returns the byte length of a string."
},
{
"code": null,
"e": 6721,
"s": 6684,
"text": "Example − SELECT LENGTH('rambutan');"
},
{
"code": null,
"e": 6730,
"s": 6721,
"text": "LOCATE()"
},
{
"code": null,
"e": 6792,
"s": 6730,
"text": "It returns the position of the first instance of a substring."
},
{
"code": null,
"e": 6836,
"s": 6792,
"text": "Example − SELECT LOCATE('tan', 'rambutan');"
},
{
"code": null,
"e": 6845,
"s": 6836,
"text": "INSERT()"
},
{
"code": null,
"e": 6935,
"s": 6845,
"text": "It returns a string, with a specified substring at a certain position, that was modified."
},
{
"code": null,
"e": 6983,
"s": 6935,
"text": "Example − SELECT INSERT('ramputan', 4, 1, 'b');"
},
{
"code": null,
"e": 6990,
"s": 6983,
"text": "LEFT()"
},
{
"code": null,
"e": 7026,
"s": 6990,
"text": "It returns the leftmost characters."
},
{
"code": null,
"e": 7064,
"s": 7026,
"text": "Example − SELECT LEFT('rambutan', 3);"
},
{
"code": null,
"e": 7072,
"s": 7064,
"text": "UPPER()"
},
{
"code": null,
"e": 7108,
"s": 7072,
"text": "It changes characters to uppercase."
},
{
"code": null,
"e": 7142,
"s": 7108,
"text": "Example − SELECT UPPER(lastname);"
},
{
"code": null,
"e": 7150,
"s": 7142,
"text": "LOWER()"
},
{
"code": null,
"e": 7186,
"s": 7150,
"text": "It changes characters to lowercase."
},
{
"code": null,
"e": 7220,
"s": 7186,
"text": "Example − SELECT LOWER(lastname);"
},
{
"code": null,
"e": 7229,
"s": 7220,
"text": "STRCMP()"
},
{
"code": null,
"e": 7284,
"s": 7229,
"text": "It compares strings and returns 0 when they are equal."
},
{
"code": null,
"e": 7326,
"s": 7284,
"text": "Example − SELECT STRCMP('egg', 'cheese');"
},
{
"code": null,
"e": 7336,
"s": 7326,
"text": "REPLACE()"
},
{
"code": null,
"e": 7384,
"s": 7336,
"text": "It returns a string after replacing characters."
},
{
"code": null,
"e": 7429,
"s": 7384,
"text": "Example − SELECT REPLACE('sully', 'l', 'n');"
},
{
"code": null,
"e": 7439,
"s": 7429,
"text": "REVERSE()"
},
{
"code": null,
"e": 7475,
"s": 7439,
"text": "It reverses characters in a string."
},
{
"code": null,
"e": 7512,
"s": 7475,
"text": "Example − SELECT REVERSE('racecar');"
},
{
"code": null,
"e": 7521,
"s": 7512,
"text": "REPEAT()"
},
{
"code": null,
"e": 7577,
"s": 7521,
"text": "It returns a string repeating given characters x times."
},
{
"code": null,
"e": 7613,
"s": 7577,
"text": "Example − SELECT REPEAT('ha ', 10);"
},
{
"code": null,
"e": 7625,
"s": 7613,
"text": "SUBSTRING()"
},
{
"code": null,
"e": 7687,
"s": 7625,
"text": "It returns a substring from a string, starting at position x."
},
{
"code": null,
"e": 7729,
"s": 7687,
"text": "Example − SELECT SUBSTRING('rambutan',3);"
},
{
"code": null,
"e": 7736,
"s": 7729,
"text": "TRIM()"
},
{
"code": null,
"e": 7790,
"s": 7736,
"text": "It removes trailing/leading characters from a string."
}
] |
Scientific Calculator Using awk Command in Linux
|
19 Feb, 2020
The awk command in Linux allows the user to use the numeric functions, variables, logical operators and string functions. Basically, it is a utility that allows the user to write small and effective programs in the form the statements. It is mostly used in pattern scanning and processing. Here, we are using the awk command to perform the following operations:
Floating-point calculations
Trigonometric operations
Logarithms
Exponent
Syntax for awk Command
awk options 'pattern{action }' input-file > output-file
Program: Here, we are using Ubuntu. We are saving the below program in file named scientificcalculator.sh. To execute this program, you can use the below command:
sh scientificcalculator.sh
pi=`echo "scale=10;4*a(1)" | bc -l` while truedo cat << MENU Menu: a) Floating Point Calculations b) Trigonometric Operations c) Logarithmic Operations d) Exponential Operations MENUecho 'Enter your Choice: \c'read choice case $choice in a) echo "\nEnter expression: " read exp cal() awk "BEGIN{print $*}"; echo "Answer: " `cal $exp` ;; b) echo "\nEnter Trigonometric function : " read exp echo "Degree: " read degree e=$(awk "BEGIN{print $exp($degree*atan2(0,-1)/180)}") echo " $exp($degree)= $e" ;; c) echo "\nEnter the logarithmic value: " read value echo $value | awk '{printf "%11.9f\n",log($1)/log(10)}' ;; d) echo "\nEnter the base number x: " read x echo "Enter exponent number y: " read y E=$(echo "$x 1" | awk "{print (($x/1)^$y)}") echo "$x^$y = $E" ;; *) break;; *) break;;esacdone
Output:
Technical Scripter 2019
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
chown command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 390,
"s": 28,
"text": "The awk command in Linux allows the user to use the numeric functions, variables, logical operators and string functions. Basically, it is a utility that allows the user to write small and effective programs in the form the statements. It is mostly used in pattern scanning and processing. Here, we are using the awk command to perform the following operations:"
},
{
"code": null,
"e": 418,
"s": 390,
"text": "Floating-point calculations"
},
{
"code": null,
"e": 443,
"s": 418,
"text": "Trigonometric operations"
},
{
"code": null,
"e": 454,
"s": 443,
"text": "Logarithms"
},
{
"code": null,
"e": 463,
"s": 454,
"text": "Exponent"
},
{
"code": null,
"e": 486,
"s": 463,
"text": "Syntax for awk Command"
},
{
"code": null,
"e": 543,
"s": 486,
"text": "awk options 'pattern{action }' input-file > output-file\n"
},
{
"code": null,
"e": 706,
"s": 543,
"text": "Program: Here, we are using Ubuntu. We are saving the below program in file named scientificcalculator.sh. To execute this program, you can use the below command:"
},
{
"code": null,
"e": 735,
"s": 706,
"text": "sh scientificcalculator.sh\n"
},
{
"code": "pi=`echo \"scale=10;4*a(1)\" | bc -l` while truedo cat << MENU Menu: a) Floating Point Calculations b) Trigonometric Operations c) Logarithmic Operations d) Exponential Operations MENUecho 'Enter your Choice: \\c'read choice case $choice in a) echo \"\\nEnter expression: \" read exp cal() awk \"BEGIN{print $*}\"; echo \"Answer: \" `cal $exp` ;; b) echo \"\\nEnter Trigonometric function : \" read exp echo \"Degree: \" read degree e=$(awk \"BEGIN{print $exp($degree*atan2(0,-1)/180)}\") echo \" $exp($degree)= $e\" ;; c) echo \"\\nEnter the logarithmic value: \" read value echo $value | awk '{printf \"%11.9f\\n\",log($1)/log(10)}' ;; d) echo \"\\nEnter the base number x: \" read x echo \"Enter exponent number y: \" read y E=$(echo \"$x 1\" | awk \"{print (($x/1)^$y)}\") echo \"$x^$y = $E\" ;; *) break;; *) break;;esacdone",
"e": 1863,
"s": 735,
"text": null
},
{
"code": null,
"e": 1871,
"s": 1863,
"text": "Output:"
},
{
"code": null,
"e": 1895,
"s": 1871,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 1906,
"s": 1895,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1925,
"s": 1906,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2023,
"s": 1925,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2058,
"s": 2023,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 2096,
"s": 2058,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 2132,
"s": 2096,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 2170,
"s": 2132,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 2196,
"s": 2170,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2231,
"s": 2196,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2266,
"s": 2231,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 2302,
"s": 2266,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 2339,
"s": 2302,
"text": "touch command in Linux with Examples"
}
] |
Python | Pandas Series.dt.to_period
|
11 Mar, 2022
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.to_period() function cast the underlying data of the given Series object to PeriodArray/Index at a particular frequency.
Syntax: Series.dt.to_period(*args, **kwargs)Parameter : freq : string or Offset, optionalReturns : PeriodArray/Index
Example #1: Use Series.dt.to_period() function to cast the underlying data of the given series object to Index at Weekly frequency.
Python3
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetimesr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.to_period() function to cast the underlying data of the given series object to Index at Weekly frequency.
Python3
# cast to target frequencyresult = sr.dt.to_period(freq = 'W') # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.to_period() function has successfully cast the data to the target frequency.Example #2 : Use Series.dt.to_period() function to cast the underlying data of the given series object to Index at two year frequency.
Python3
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D', tz = 'US / Central')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.to_period() function to cast the underlying data of the given series object to Index at two year frequency.
Python3
# cast to target frequencyresult = sr.dt.to_period(freq = '2Y') # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.to_period() function has successfully cast the data to the target frequency.
varshagumber28
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Mar, 2022"
},
{
"code": null,
"e": 271,
"s": 28,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.to_period() function cast the underlying data of the given Series object to PeriodArray/Index at a particular frequency. "
},
{
"code": null,
"e": 389,
"s": 271,
"text": "Syntax: Series.dt.to_period(*args, **kwargs)Parameter : freq : string or Offset, optionalReturns : PeriodArray/Index "
},
{
"code": null,
"e": 522,
"s": 389,
"text": "Example #1: Use Series.dt.to_period() function to cast the underlying data of the given series object to Index at Weekly frequency. "
},
{
"code": null,
"e": 530,
"s": 522,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetimesr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 910,
"s": 530,
"text": null
},
{
"code": null,
"e": 921,
"s": 910,
"text": "Output : "
},
{
"code": null,
"e": 1054,
"s": 921,
"text": "Now we will use Series.dt.to_period() function to cast the underlying data of the given series object to Index at Weekly frequency. "
},
{
"code": null,
"e": 1062,
"s": 1054,
"text": "Python3"
},
{
"code": "# cast to target frequencyresult = sr.dt.to_period(freq = 'W') # print the resultprint(result)",
"e": 1157,
"s": 1062,
"text": null
},
{
"code": null,
"e": 1168,
"s": 1157,
"text": "Output : "
},
{
"code": null,
"e": 1423,
"s": 1168,
"text": "As we can see in the output, the Series.dt.to_period() function has successfully cast the data to the target frequency.Example #2 : Use Series.dt.to_period() function to cast the underlying data of the given series object to Index at two year frequency. "
},
{
"code": null,
"e": 1431,
"s": 1423,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D', tz = 'US / Central')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1749,
"s": 1431,
"text": null
},
{
"code": null,
"e": 1760,
"s": 1749,
"text": "Output : "
},
{
"code": null,
"e": 1895,
"s": 1760,
"text": "Now we will use Series.dt.to_period() function to cast the underlying data of the given series object to Index at two year frequency. "
},
{
"code": null,
"e": 1903,
"s": 1895,
"text": "Python3"
},
{
"code": "# cast to target frequencyresult = sr.dt.to_period(freq = '2Y') # print the resultprint(result)",
"e": 1999,
"s": 1903,
"text": null
},
{
"code": null,
"e": 2010,
"s": 1999,
"text": "Output : "
},
{
"code": null,
"e": 2131,
"s": 2010,
"text": "As we can see in the output, the Series.dt.to_period() function has successfully cast the data to the target frequency. "
},
{
"code": null,
"e": 2146,
"s": 2131,
"text": "varshagumber28"
},
{
"code": null,
"e": 2176,
"s": 2146,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 2190,
"s": 2176,
"text": "Python-pandas"
},
{
"code": null,
"e": 2197,
"s": 2190,
"text": "Python"
},
{
"code": null,
"e": 2295,
"s": 2197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2313,
"s": 2295,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2355,
"s": 2313,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2377,
"s": 2355,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2409,
"s": 2377,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2438,
"s": 2409,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2465,
"s": 2438,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2486,
"s": 2465,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2509,
"s": 2486,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2545,
"s": 2509,
"text": "Convert integer to string in Python"
}
] |
Naming Rows and Columns of a Matrix in R Programming – rownames() and colnames() Function
|
05 Jun, 2020
rownames() function in R Language is used to set the names to rows of a matrix.
Syntax:rownames(x) <- value
Parameters:x: Matrixvalue: Vector of names to be set
Example:
# R program to provide a name# to rows of a Matrix # Creating a 3X3 MatrixA = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow = TRUE) # Calling rownames() Functionrownames(A) <- letters[1:3] print(A)
Output:
[, 1] [, 2] [, 3]
a 1 2 3
b 4 5 6
c 7 8 9
colnames() function in R Language is used to set the names to columns of a matrix.
Syntax:colnames(x) <- value
Parameters:x: Matrixvalue: Vector of names to be set
Example:
# R program to provide a name# to columns of a Matrix # Creating a 3X3 MatrixA = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow = TRUE) # Calling colnames() Functioncolnames(A) <- letters[1:3] print(A)
Output:
a b c
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "rownames() function in R Language is used to set the names to rows of a matrix."
},
{
"code": null,
"e": 136,
"s": 108,
"text": "Syntax:rownames(x) <- value"
},
{
"code": null,
"e": 189,
"s": 136,
"text": "Parameters:x: Matrixvalue: Vector of names to be set"
},
{
"code": null,
"e": 198,
"s": 189,
"text": "Example:"
},
{
"code": "# R program to provide a name# to rows of a Matrix # Creating a 3X3 MatrixA = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow = TRUE) # Calling rownames() Functionrownames(A) <- letters[1:3] print(A) ",
"e": 407,
"s": 198,
"text": null
},
{
"code": null,
"e": 415,
"s": 407,
"text": "Output:"
},
{
"code": null,
"e": 487,
"s": 415,
"text": " [, 1] [, 2] [, 3]\na 1 2 3\nb 4 5 6\nc 7 8 9\n"
},
{
"code": null,
"e": 570,
"s": 487,
"text": "colnames() function in R Language is used to set the names to columns of a matrix."
},
{
"code": null,
"e": 598,
"s": 570,
"text": "Syntax:colnames(x) <- value"
},
{
"code": null,
"e": 651,
"s": 598,
"text": "Parameters:x: Matrixvalue: Vector of names to be set"
},
{
"code": null,
"e": 660,
"s": 651,
"text": "Example:"
},
{
"code": "# R program to provide a name# to columns of a Matrix # Creating a 3X3 MatrixA = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow = TRUE) # Calling colnames() Functioncolnames(A) <- letters[1:3] print(A) ",
"e": 872,
"s": 660,
"text": null
},
{
"code": null,
"e": 880,
"s": 872,
"text": "Output:"
},
{
"code": null,
"e": 953,
"s": 880,
"text": " a b c\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n"
},
{
"code": null,
"e": 971,
"s": 953,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 982,
"s": 971,
"text": "R Language"
},
{
"code": null,
"e": 1080,
"s": 982,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1132,
"s": 1080,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 1190,
"s": 1132,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 1242,
"s": 1190,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1300,
"s": 1242,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1332,
"s": 1300,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 1367,
"s": 1332,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 1411,
"s": 1367,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 1443,
"s": 1411,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 1481,
"s": 1443,
"text": "How to Change Axis Scales in R Plots?"
}
] |
Thompson Sampling For Multi-Armed Bandit Problems (Part 1) | by Guido Vivaldi | Towards Data Science
|
“Multi-armed bandit” is perhaps the coolest term in data science, excluding financial applications to “naked European call options” or “short iron butterflies”. They are also among the most commonly encountered practical applications.
The term has a helpful motivating story: a “one armed bandit” refers to a slot machine — pull the “arm” and the “bandit” will take your money (most times — with some probability you’ll win big). A “multi-armed bandit” is a slot machine with many arms, each with potentially a different probability of winning and associated payout. Without knowing those probabilities/payouts, you’ll need to learn as you go, pulling levers that are successful more often and hopefully converging on the optimal lever sooner rather than later.
Gambling aside, we can imagine multi-armed bandit problems in many situations. A hospital has several ideas about potential modifications to clinical protocol to improve results — with a limited number of clinical events to intervene on, and potential unintended consequences from poor modifications, how can we evaluate all modifications but ensure the best rise to the top quickly. Or a marketing firm wants to deploy a new ad strategy by selecting one of 3 potential campaigns it has developed.
In this article we will focus on a Bernoulli bandit problem — one in which the payout is either 1 or 0 (reducing the complexity of the problem to identifying the probability of payout). We will apply two methods: ε-greedy and Thompson Sampling. In future articles we will discuss more complex multi-armed bandit problems (including sampling methods where conjugate priors are not as friendly to us!) and other methods for addressing this problem set.
ε-greedy
An algorithm is “greedy” in as much as it chooses an immediate payoff without regard to a long-term outcome. Tree algorithms are often “greedy” — at each node they chose the split that minimizes entropy the most. This split may not be the tree which minimizes entropy the most in subsequent splits.
Greedy algorithms are common in situations where the number of paths grows exponentially and soon becomes intractable (i.e. computationally intense to the point of impossibility). For example a tree based on 10 features, even allowing each variable to be used only one time (which is not a common restraint), 3.6M possible configurations (10! = 10 * 9 * 8...). Adding the 11th feature makes 39.9M, etc.
Multi-armed bandit problems can reasonably be approached using a greedy algorithm. In the slot-machine formulation, we assume all levers have the same probability of success, we randomly choose one, and then update our assumption of success based on success/failure. At each successive iteration we choose the lever that has the highest probability of success.
This algorithm potentially ignores new information for the sake of immediate gain. Suppose that we have 3 levers with probabilities 0.04, 0.07, and 0.1. We may by chance find early success with a lower-probability lever, and then continue pulling that lever 20–50 times until it’s probability drops below the others. The algorithm gets “stuck”.
An enhancement to this algorithm allows for a small probability of times (ε) where we ignore the probability of success and choose a lever at random. This helps gather new information by allowing non-optimal choices enter the mix occasionally.
The code below sets up the algorithm for us. Note that the Beta distribution is a “conjugate prior” to the Bernoulli distribution. This is a Bayesian term that means that the Beta distribution is the posterior predictive distribution of the probability of success contained in a Bernoulli trial. Conjugate priors make the math of Bayesian analysis easy — below we can update the Beta by treating alpha as the count of successes and beta as the count of failures.
import numpy as npimport pandas as pdimport random#Initialize Sampling def initialize(arms): prior = pd.DataFrame(np.ones((arms, 3)), columns = ['alpha', 'beta', 'theta']) prior.loc[:, 'theta'] = prior.loc[:, 'alpha'] / (prior.loc[:, 'alpha'] + prior.loc[:, 'beta']) post = pd.DataFrame(columns = ['i', 'arm', 'payout']) return prior, post# e-Greedydef e_greedy(eta, arm_prob, prior): #Determine path-selection if np.random.uniform(0, 1, 1) <= eta: s = np.random.randint(0, len(arm_prob) -1, 1)[0] else: s = random.choice(np.where(prior['theta'] == np.amax(prior['theta']))[0]) #Determine success/failure r = 1 if np.random.uniform(0, 1, 1) <= arm_prob[s] else 0 prior.loc[s, 'alpha'] += r prior.loc[s, 'beta'] += 1- r prior.loc[s, 'theta'] = prior.loc[s, 'alpha'] / (prior.loc[s, 'alpha'] + prior.loc[s, 'beta']) return s, r, prior
We’ll try this code out head-to-head with Thompson sampling after a few words on that method.
Thompson Sampling
Thompson sampling takes a different approach to selecting the next arm to be pulled than ε-greedy. A downside of ε-greedy is that it potentially gets stuck on local maximums — sub-par distributions that perform well through statistical chance. The eta parameter is designed to counteract this by forcing the algorithm to take what appears in current view to be a sub-optimal choice (i.e. not the current maximum predicted probability), but which may in fact be the optimal choice given enough information.
To do this, Thompson sampling draws from the posterior predictive distributions of each choice using a random uniform variable. This allows a non-optimal distribution to be sampled with varying frequency — as the posterior distribution becomes more certain, the probability of the choice being made decreases dynamically, thus Thompson sampling dynamically balances the desire for more information with making the currently optimal choice. For example, in the graph below we assume two choices, where blue has had 4 successes and 1 failure ,and orange has had the reserves. While the blue choice has a mean ~.7 and the orange choice has a mean ~0.3, there is a non-trivial probability (~4%) that orange will be chosen instead of blue.
Our implementation of Thompson sampling looks like this — note that the random.choice selection now uses a draw from the prior distributions rather than the prior means.
# Thompson Samplingdef thompson(arm_prob, prior): #Determine path-selection s = [np.random.beta(prior.loc[n, 'alpha'], prior.loc[n, 'beta'], 1) for n in range(len(arm_prob))] s = random.choice(np.where(s == np.amax(s))[0]) #Determine success/failure r = 1 if np.random.uniform(0, 1, 1) <= arm_prob[s] else 0 prior.loc[s, 'alpha'] += r prior.loc[s, 'beta'] += 1- r prior.loc[s, 'theta'] = prior.loc[s, 'alpha'] / (prior.loc[s, 'alpha'] + prior.loc[s, 'beta']) return s, r, prior
The Face-Off!
Pitting the two algorithms against each-other helps clarify their strengths and weaknesses.
In the example below we simulate 5 arms with probabilities drawn from a Beta(1.5, 1.1), i.e. shifted towards lower probabilities, but still maintaining sufficient opportunity for higher probabilities.
The graph below shows one trial run that is characteristic of these methods. After 250 iterations both methods have struck upon the optimal lever (Lever 1), however the TS has pulled ahead due to superior performance earlier in the analysis. After 50 iterations both methods were virtually tied with 30 wins, with EG leading slightly up to that point. However after that point TS pulls ahead. EG had started pulling Lever 2 (by change), and saw a success, and continued pulling, to the point that in the first 15 draws it had seen 10 successes (all while EG is assuming other untried levers have probabilities of 0.5). EG continues heavily favoring Lever 2 until the 175th iteration, at which point it tries Lever 1 and finds long-term success. In contrast EG had found Lever 0 as early as the 20th iteration, and pulls it nearly exclusively as early as the 40th iteration.
Each of these algorithms can be tuned — we can adjust the priors in both models, as well as adjusting eta for EG. In the above example we used a 5% eta. Using a more aggressive eta allows the model to be less prone to local maxima, while also potentially reducing long-term gains by enforcing sub-optimal choices. The graph below looks at 1000 iterations using eta = 0.1. As predicted we see that EG is even able to beat TS early on (while TS is looking to “prove” that Lever 0 is the right option, EG is willing to make that assumption without as much proof), however as the simulation goes into the 1000th iteration TS gains a slight lead, as EG is still sampling from non-optimal levers 10% of the time. An improvement on EG could use a decay factor for eta.
The simulation above shows that both of these methods can be effective — they are largely dependent on context. EG will perform well in situations where making a sub-optimal choice hurts less — if the true probability of the second or third choice is close enough to the true probability of the first choice, you won’t lose much by making those marginally sub-par choices. Additionally if the search space is expansive, TS may get bogged down trying to prove the best option, while EG is willing to take quick wins without much “proof”.
In the example below, 50 arms are simulated using a Beta(3.5, 0.7) which favors giving arms a higher probability (see the histogram below). As predicted, EG is able to pull out a quick-win while TS is searching the wide space that carries it through iteration 1000.
If we flip the probability distribution to favor low-probability outcomes-Beta(0.7, 3.5)-we see each algorithm struggle to find wins. While the optimal choice wins 67% of the time, after 500 iterations, EG has won 229 times and TS slightly fewer. However after 1000 iterations TS pulls ahead, a lead which it is predicted to maintain as EG continues to sample an ineffective space.
We see TS take a leg up again in the bi-modal distribution below (a 25/75 mixture of Beta(2.5, 1) and Beta(2.5,10).
Conclusion
Thompson sampling is a Bayesian approach to the Multi-Armed Bandit problem that dynamically balances incorporating more information to produce more certain predicted probabilities of each lever with the need to maximize current wins. ε-greedy is a simpler method that focuses more heavily on current wins with a deterministic approach to incorporating more information. A consequence of this approach is that current wins and more information are sometimes not well-balanced (i.e. concentrating on local maxima), but a benefit can be that if the method happens upon a global maximum early on it is more willing to trust it and can produce early-wins.
In future articles we’ll discuss expanding upon this framework using more complex Bayesian sampling techniques (in situations with non-conjugate priors), as well as applications to Thompson sampling to new problems: non-binomial multi-armed bandit, path optimization, and more.
|
[
{
"code": null,
"e": 407,
"s": 172,
"text": "“Multi-armed bandit” is perhaps the coolest term in data science, excluding financial applications to “naked European call options” or “short iron butterflies”. They are also among the most commonly encountered practical applications."
},
{
"code": null,
"e": 934,
"s": 407,
"text": "The term has a helpful motivating story: a “one armed bandit” refers to a slot machine — pull the “arm” and the “bandit” will take your money (most times — with some probability you’ll win big). A “multi-armed bandit” is a slot machine with many arms, each with potentially a different probability of winning and associated payout. Without knowing those probabilities/payouts, you’ll need to learn as you go, pulling levers that are successful more often and hopefully converging on the optimal lever sooner rather than later."
},
{
"code": null,
"e": 1432,
"s": 934,
"text": "Gambling aside, we can imagine multi-armed bandit problems in many situations. A hospital has several ideas about potential modifications to clinical protocol to improve results — with a limited number of clinical events to intervene on, and potential unintended consequences from poor modifications, how can we evaluate all modifications but ensure the best rise to the top quickly. Or a marketing firm wants to deploy a new ad strategy by selecting one of 3 potential campaigns it has developed."
},
{
"code": null,
"e": 1883,
"s": 1432,
"text": "In this article we will focus on a Bernoulli bandit problem — one in which the payout is either 1 or 0 (reducing the complexity of the problem to identifying the probability of payout). We will apply two methods: ε-greedy and Thompson Sampling. In future articles we will discuss more complex multi-armed bandit problems (including sampling methods where conjugate priors are not as friendly to us!) and other methods for addressing this problem set."
},
{
"code": null,
"e": 1892,
"s": 1883,
"text": "ε-greedy"
},
{
"code": null,
"e": 2191,
"s": 1892,
"text": "An algorithm is “greedy” in as much as it chooses an immediate payoff without regard to a long-term outcome. Tree algorithms are often “greedy” — at each node they chose the split that minimizes entropy the most. This split may not be the tree which minimizes entropy the most in subsequent splits."
},
{
"code": null,
"e": 2594,
"s": 2191,
"text": "Greedy algorithms are common in situations where the number of paths grows exponentially and soon becomes intractable (i.e. computationally intense to the point of impossibility). For example a tree based on 10 features, even allowing each variable to be used only one time (which is not a common restraint), 3.6M possible configurations (10! = 10 * 9 * 8...). Adding the 11th feature makes 39.9M, etc."
},
{
"code": null,
"e": 2955,
"s": 2594,
"text": "Multi-armed bandit problems can reasonably be approached using a greedy algorithm. In the slot-machine formulation, we assume all levers have the same probability of success, we randomly choose one, and then update our assumption of success based on success/failure. At each successive iteration we choose the lever that has the highest probability of success."
},
{
"code": null,
"e": 3300,
"s": 2955,
"text": "This algorithm potentially ignores new information for the sake of immediate gain. Suppose that we have 3 levers with probabilities 0.04, 0.07, and 0.1. We may by chance find early success with a lower-probability lever, and then continue pulling that lever 20–50 times until it’s probability drops below the others. The algorithm gets “stuck”."
},
{
"code": null,
"e": 3544,
"s": 3300,
"text": "An enhancement to this algorithm allows for a small probability of times (ε) where we ignore the probability of success and choose a lever at random. This helps gather new information by allowing non-optimal choices enter the mix occasionally."
},
{
"code": null,
"e": 4007,
"s": 3544,
"text": "The code below sets up the algorithm for us. Note that the Beta distribution is a “conjugate prior” to the Bernoulli distribution. This is a Bayesian term that means that the Beta distribution is the posterior predictive distribution of the probability of success contained in a Bernoulli trial. Conjugate priors make the math of Bayesian analysis easy — below we can update the Beta by treating alpha as the count of successes and beta as the count of failures."
},
{
"code": null,
"e": 4917,
"s": 4007,
"text": "import numpy as npimport pandas as pdimport random#Initialize Sampling def initialize(arms): prior = pd.DataFrame(np.ones((arms, 3)), columns = ['alpha', 'beta', 'theta']) prior.loc[:, 'theta'] = prior.loc[:, 'alpha'] / (prior.loc[:, 'alpha'] + prior.loc[:, 'beta']) post = pd.DataFrame(columns = ['i', 'arm', 'payout']) return prior, post# e-Greedydef e_greedy(eta, arm_prob, prior): #Determine path-selection if np.random.uniform(0, 1, 1) <= eta: s = np.random.randint(0, len(arm_prob) -1, 1)[0] else: s = random.choice(np.where(prior['theta'] == np.amax(prior['theta']))[0]) #Determine success/failure r = 1 if np.random.uniform(0, 1, 1) <= arm_prob[s] else 0 prior.loc[s, 'alpha'] += r prior.loc[s, 'beta'] += 1- r prior.loc[s, 'theta'] = prior.loc[s, 'alpha'] / (prior.loc[s, 'alpha'] + prior.loc[s, 'beta']) return s, r, prior"
},
{
"code": null,
"e": 5011,
"s": 4917,
"text": "We’ll try this code out head-to-head with Thompson sampling after a few words on that method."
},
{
"code": null,
"e": 5029,
"s": 5011,
"text": "Thompson Sampling"
},
{
"code": null,
"e": 5535,
"s": 5029,
"text": "Thompson sampling takes a different approach to selecting the next arm to be pulled than ε-greedy. A downside of ε-greedy is that it potentially gets stuck on local maximums — sub-par distributions that perform well through statistical chance. The eta parameter is designed to counteract this by forcing the algorithm to take what appears in current view to be a sub-optimal choice (i.e. not the current maximum predicted probability), but which may in fact be the optimal choice given enough information."
},
{
"code": null,
"e": 6270,
"s": 5535,
"text": "To do this, Thompson sampling draws from the posterior predictive distributions of each choice using a random uniform variable. This allows a non-optimal distribution to be sampled with varying frequency — as the posterior distribution becomes more certain, the probability of the choice being made decreases dynamically, thus Thompson sampling dynamically balances the desire for more information with making the currently optimal choice. For example, in the graph below we assume two choices, where blue has had 4 successes and 1 failure ,and orange has had the reserves. While the blue choice has a mean ~.7 and the orange choice has a mean ~0.3, there is a non-trivial probability (~4%) that orange will be chosen instead of blue."
},
{
"code": null,
"e": 6440,
"s": 6270,
"text": "Our implementation of Thompson sampling looks like this — note that the random.choice selection now uses a draw from the prior distributions rather than the prior means."
},
{
"code": null,
"e": 6965,
"s": 6440,
"text": "# Thompson Samplingdef thompson(arm_prob, prior): #Determine path-selection s = [np.random.beta(prior.loc[n, 'alpha'], prior.loc[n, 'beta'], 1) for n in range(len(arm_prob))] s = random.choice(np.where(s == np.amax(s))[0]) #Determine success/failure r = 1 if np.random.uniform(0, 1, 1) <= arm_prob[s] else 0 prior.loc[s, 'alpha'] += r prior.loc[s, 'beta'] += 1- r prior.loc[s, 'theta'] = prior.loc[s, 'alpha'] / (prior.loc[s, 'alpha'] + prior.loc[s, 'beta']) return s, r, prior"
},
{
"code": null,
"e": 6979,
"s": 6965,
"text": "The Face-Off!"
},
{
"code": null,
"e": 7071,
"s": 6979,
"text": "Pitting the two algorithms against each-other helps clarify their strengths and weaknesses."
},
{
"code": null,
"e": 7272,
"s": 7071,
"text": "In the example below we simulate 5 arms with probabilities drawn from a Beta(1.5, 1.1), i.e. shifted towards lower probabilities, but still maintaining sufficient opportunity for higher probabilities."
},
{
"code": null,
"e": 8146,
"s": 7272,
"text": "The graph below shows one trial run that is characteristic of these methods. After 250 iterations both methods have struck upon the optimal lever (Lever 1), however the TS has pulled ahead due to superior performance earlier in the analysis. After 50 iterations both methods were virtually tied with 30 wins, with EG leading slightly up to that point. However after that point TS pulls ahead. EG had started pulling Lever 2 (by change), and saw a success, and continued pulling, to the point that in the first 15 draws it had seen 10 successes (all while EG is assuming other untried levers have probabilities of 0.5). EG continues heavily favoring Lever 2 until the 175th iteration, at which point it tries Lever 1 and finds long-term success. In contrast EG had found Lever 0 as early as the 20th iteration, and pulls it nearly exclusively as early as the 40th iteration."
},
{
"code": null,
"e": 8908,
"s": 8146,
"text": "Each of these algorithms can be tuned — we can adjust the priors in both models, as well as adjusting eta for EG. In the above example we used a 5% eta. Using a more aggressive eta allows the model to be less prone to local maxima, while also potentially reducing long-term gains by enforcing sub-optimal choices. The graph below looks at 1000 iterations using eta = 0.1. As predicted we see that EG is even able to beat TS early on (while TS is looking to “prove” that Lever 0 is the right option, EG is willing to make that assumption without as much proof), however as the simulation goes into the 1000th iteration TS gains a slight lead, as EG is still sampling from non-optimal levers 10% of the time. An improvement on EG could use a decay factor for eta."
},
{
"code": null,
"e": 9445,
"s": 8908,
"text": "The simulation above shows that both of these methods can be effective — they are largely dependent on context. EG will perform well in situations where making a sub-optimal choice hurts less — if the true probability of the second or third choice is close enough to the true probability of the first choice, you won’t lose much by making those marginally sub-par choices. Additionally if the search space is expansive, TS may get bogged down trying to prove the best option, while EG is willing to take quick wins without much “proof”."
},
{
"code": null,
"e": 9711,
"s": 9445,
"text": "In the example below, 50 arms are simulated using a Beta(3.5, 0.7) which favors giving arms a higher probability (see the histogram below). As predicted, EG is able to pull out a quick-win while TS is searching the wide space that carries it through iteration 1000."
},
{
"code": null,
"e": 10093,
"s": 9711,
"text": "If we flip the probability distribution to favor low-probability outcomes-Beta(0.7, 3.5)-we see each algorithm struggle to find wins. While the optimal choice wins 67% of the time, after 500 iterations, EG has won 229 times and TS slightly fewer. However after 1000 iterations TS pulls ahead, a lead which it is predicted to maintain as EG continues to sample an ineffective space."
},
{
"code": null,
"e": 10209,
"s": 10093,
"text": "We see TS take a leg up again in the bi-modal distribution below (a 25/75 mixture of Beta(2.5, 1) and Beta(2.5,10)."
},
{
"code": null,
"e": 10220,
"s": 10209,
"text": "Conclusion"
},
{
"code": null,
"e": 10871,
"s": 10220,
"text": "Thompson sampling is a Bayesian approach to the Multi-Armed Bandit problem that dynamically balances incorporating more information to produce more certain predicted probabilities of each lever with the need to maximize current wins. ε-greedy is a simpler method that focuses more heavily on current wins with a deterministic approach to incorporating more information. A consequence of this approach is that current wins and more information are sometimes not well-balanced (i.e. concentrating on local maxima), but a benefit can be that if the method happens upon a global maximum early on it is more willing to trust it and can produce early-wins."
}
] |
ByteBuffer get() method in Java with Examples - GeeksforGeeks
|
24 May, 2019
The get() method of java.nio.ByteBuffer class is used to read the byte at the buffer’s current position, and then increments the position.
Syntax :
public abstract byte get()
Return Value: This method returns the byte at the buffer’s current position.
Throws: This method throws BufferUnderflowException – If the buffer’s current position is not smaller than its limit, then this exception is thrown.
Below are the examples to illustrate the get() method:
Examples 1:
// Java program to demonstrate// get() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); // Reads the byte at this buffer's current position // using get() method byte value = bb.get(); // print the byte value System.out.println("\nByte Value: " + value); // Reads the Byte at this buffer's next position // using get() method byte value1 = bb.get(); // print the Float value System.out.print("\nNext Byte Value: " + value1); } catch (IllegalArgumentException e) { System.out.println("\nException Thrown : " + e); } catch (ReadOnlyBufferException e) { System.out.println("\nException Thrown : " + e); } catch (BufferUnderflowException e) { System.out.println("\nException Thrown : " + e); } }}
Original ByteBuffer: [20, 30, 40, 0, 0]
Byte Value: 20
Next Byte Value: 30
Examples 2:
// Java program to demonstrate// get() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); // Reads the byte at this buffer's current position // using get() method byte value = bb.get(); // print the byte value System.out.println("\nByte Value: " + value); // Reads the Byte at this buffer's next position // using get() method System.out.print("\nsince the buffer current position is incremented"); System.out.print(" to greater than its limit "); byte value1 = bb.get(); // print the Byte value System.out.print("\nNext Byte Value: " + value1); } catch (IllegalArgumentException e) { System.out.println("\nIllegalArgumentException catched"); } catch (ReadOnlyBufferException e) { System.out.println("\nReadOnlyBufferException catched"); } catch (BufferUnderflowException e) { System.out.println("\nException throws : " + e); } }}
Original ByteBuffer: [20, 30, 0]
Byte Value: 0
since the buffer current position is incremented to greater than its limit
Exception throws : java.nio.BufferUnderflowException
The get(int index) method of ByteBuffer is used to read the article at a specified index.
Syntax :
public abstract byte get(int index)
Parameters: This method takes index (The index from which the Byte will be read) as a parameter.
Return Value: This method returns the Byte value at the given index.
Exception: This method throws IndexOutOfBoundsException. If index is negative or not smaller than the buffer’s limit this exception is thrown.
Below are the examples to illustrate the get(int index) method:
Examples 1:
// Java program to demonstrate// get(int index) method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); // Reads the Byte at the index 0 of the Bytebuffer // using get() method byte value0 = bb.get(0); // print the Byte value System.out.println("\nByte Value at index 0: " + value0); // Reads the Byte at the index 1 of the Bytebuffer // using get() method byte value1 = bb.get(1); // print the Byte value System.out.println("\nByte Value at index 1: " + value1); // Reads the Byte at the index 2 of the Bytebuffer // using get() method byte value2 = bb.get(2); // print the Byte value System.out.println("\nByte Value at index 2: " + value2); } catch (IllegalArgumentException e) { System.out.println("\nIllegalArgumentException catched"); } catch (IndexOutOfBoundsException e) { System.out.println("\nReadOnlyBufferException catched"); } catch (BufferUnderflowException e) { System.out.println("\nException throws : " + e); } }}
Original ByteBuffer: [20, 30, 40]
Byte Value at index 0: 20
Byte Value at index 1: 30
Byte Value at index 2: 40
Examples 2:
// Java program to demonstrate// get(int index) method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); // Reads the Byte at the index 0 of the Bytebuffer // using get() method byte value0 = bb.get(0); // print the Byte value System.out.println("\nByte Value at index 0: " + value0); // Reads the Byte at the index 1 of the Bytebuffer // using get() method byte value1 = bb.get(1); // print the Byte value System.out.println("\nByte Value at index 1: " + value1); // Reads the Byte at the index 4 of the Bytebuffer // using get() method System.out.println("\nTrying to get the byte" + " of index greater than its limit "); byte value2 = bb.get(4); // print the Byte value System.out.println("\nByte Value at index 4: " + value2); } catch (IndexOutOfBoundsException e) { System.out.println("\nException throws : " + e); } catch (BufferUnderflowException e) { System.out.println("\nException throws : " + e); } }}
Original ByteBuffer: [20, 30, 40]
Byte Value at index 0: 20
Byte Value at index 1: 30
Trying to get the byte of index greater than its limit
Exception throws : java.lang.IndexOutOfBoundsException
Vijay Sirra
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
Overriding in Java
Collections in Java
Multithreading in Java
|
[
{
"code": null,
"e": 24514,
"s": 24486,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 24653,
"s": 24514,
"text": "The get() method of java.nio.ByteBuffer class is used to read the byte at the buffer’s current position, and then increments the position."
},
{
"code": null,
"e": 24662,
"s": 24653,
"text": "Syntax :"
},
{
"code": null,
"e": 24689,
"s": 24662,
"text": "public abstract byte get()"
},
{
"code": null,
"e": 24766,
"s": 24689,
"text": "Return Value: This method returns the byte at the buffer’s current position."
},
{
"code": null,
"e": 24915,
"s": 24766,
"text": "Throws: This method throws BufferUnderflowException – If the buffer’s current position is not smaller than its limit, then this exception is thrown."
},
{
"code": null,
"e": 24970,
"s": 24915,
"text": "Below are the examples to illustrate the get() method:"
},
{
"code": null,
"e": 24982,
"s": 24970,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// get() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb.array())); // Reads the byte at this buffer's current position // using get() method byte value = bb.get(); // print the byte value System.out.println(\"\\nByte Value: \" + value); // Reads the Byte at this buffer's next position // using get() method byte value1 = bb.get(); // print the Float value System.out.print(\"\\nNext Byte Value: \" + value1); } catch (IllegalArgumentException e) { System.out.println(\"\\nException Thrown : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"\\nException Thrown : \" + e); } catch (BufferUnderflowException e) { System.out.println(\"\\nException Thrown : \" + e); } }}",
"e": 26556,
"s": 24982,
"text": null
},
{
"code": null,
"e": 26635,
"s": 26556,
"text": "Original ByteBuffer: [20, 30, 40, 0, 0]\n\nByte Value: 20\n\nNext Byte Value: 30\n"
},
{
"code": null,
"e": 26647,
"s": 26635,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// get() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb.array())); // Reads the byte at this buffer's current position // using get() method byte value = bb.get(); // print the byte value System.out.println(\"\\nByte Value: \" + value); // Reads the Byte at this buffer's next position // using get() method System.out.print(\"\\nsince the buffer current position is incremented\"); System.out.print(\" to greater than its limit \"); byte value1 = bb.get(); // print the Byte value System.out.print(\"\\nNext Byte Value: \" + value1); } catch (IllegalArgumentException e) { System.out.println(\"\\nIllegalArgumentException catched\"); } catch (ReadOnlyBufferException e) { System.out.println(\"\\nReadOnlyBufferException catched\"); } catch (BufferUnderflowException e) { System.out.println(\"\\nException throws : \" + e); } }}",
"e": 28337,
"s": 26647,
"text": null
},
{
"code": null,
"e": 28517,
"s": 28337,
"text": "Original ByteBuffer: [20, 30, 0]\n\nByte Value: 0\n\nsince the buffer current position is incremented to greater than its limit \nException throws : java.nio.BufferUnderflowException\n"
},
{
"code": null,
"e": 28607,
"s": 28517,
"text": "The get(int index) method of ByteBuffer is used to read the article at a specified index."
},
{
"code": null,
"e": 28616,
"s": 28607,
"text": "Syntax :"
},
{
"code": null,
"e": 28652,
"s": 28616,
"text": "public abstract byte get(int index)"
},
{
"code": null,
"e": 28749,
"s": 28652,
"text": "Parameters: This method takes index (The index from which the Byte will be read) as a parameter."
},
{
"code": null,
"e": 28818,
"s": 28749,
"text": "Return Value: This method returns the Byte value at the given index."
},
{
"code": null,
"e": 28961,
"s": 28818,
"text": "Exception: This method throws IndexOutOfBoundsException. If index is negative or not smaller than the buffer’s limit this exception is thrown."
},
{
"code": null,
"e": 29025,
"s": 28961,
"text": "Below are the examples to illustrate the get(int index) method:"
},
{
"code": null,
"e": 29037,
"s": 29025,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// get(int index) method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb.array())); // Reads the Byte at the index 0 of the Bytebuffer // using get() method byte value0 = bb.get(0); // print the Byte value System.out.println(\"\\nByte Value at index 0: \" + value0); // Reads the Byte at the index 1 of the Bytebuffer // using get() method byte value1 = bb.get(1); // print the Byte value System.out.println(\"\\nByte Value at index 1: \" + value1); // Reads the Byte at the index 2 of the Bytebuffer // using get() method byte value2 = bb.get(2); // print the Byte value System.out.println(\"\\nByte Value at index 2: \" + value2); } catch (IllegalArgumentException e) { System.out.println(\"\\nIllegalArgumentException catched\"); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nReadOnlyBufferException catched\"); } catch (BufferUnderflowException e) { System.out.println(\"\\nException throws : \" + e); } }}",
"e": 30885,
"s": 29037,
"text": null
},
{
"code": null,
"e": 31002,
"s": 30885,
"text": "Original ByteBuffer: [20, 30, 40]\n\nByte Value at index 0: 20\n\nByte Value at index 1: 30\n\nByte Value at index 2: 40\n"
},
{
"code": null,
"e": 31014,
"s": 31002,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// get(int index) method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb.array())); // Reads the Byte at the index 0 of the Bytebuffer // using get() method byte value0 = bb.get(0); // print the Byte value System.out.println(\"\\nByte Value at index 0: \" + value0); // Reads the Byte at the index 1 of the Bytebuffer // using get() method byte value1 = bb.get(1); // print the Byte value System.out.println(\"\\nByte Value at index 1: \" + value1); // Reads the Byte at the index 4 of the Bytebuffer // using get() method System.out.println(\"\\nTrying to get the byte\" + \" of index greater than its limit \"); byte value2 = bb.get(4); // print the Byte value System.out.println(\"\\nByte Value at index 4: \" + value2); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nException throws : \" + e); } catch (BufferUnderflowException e) { System.out.println(\"\\nException throws : \" + e); } }}",
"e": 32855,
"s": 31014,
"text": null
},
{
"code": null,
"e": 33058,
"s": 32855,
"text": "Original ByteBuffer: [20, 30, 40]\n\nByte Value at index 0: 20\n\nByte Value at index 1: 30\n\nTrying to get the byte of index greater than its limit \n\nException throws : java.lang.IndexOutOfBoundsException\n"
},
{
"code": null,
"e": 33070,
"s": 33058,
"text": "Vijay Sirra"
},
{
"code": null,
"e": 33086,
"s": 33070,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 33101,
"s": 33086,
"text": "Java-Functions"
},
{
"code": null,
"e": 33118,
"s": 33101,
"text": "Java-NIO package"
},
{
"code": null,
"e": 33123,
"s": 33118,
"text": "Java"
},
{
"code": null,
"e": 33128,
"s": 33123,
"text": "Java"
},
{
"code": null,
"e": 33226,
"s": 33128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33235,
"s": 33226,
"text": "Comments"
},
{
"code": null,
"e": 33248,
"s": 33235,
"text": "Old Comments"
},
{
"code": null,
"e": 33278,
"s": 33248,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 33297,
"s": 33278,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33348,
"s": 33297,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 33366,
"s": 33348,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 33397,
"s": 33366,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 33429,
"s": 33397,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 33453,
"s": 33429,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 33472,
"s": 33453,
"text": "Overriding in Java"
},
{
"code": null,
"e": 33492,
"s": 33472,
"text": "Collections in Java"
}
] |
How to reverse a vector in R?
|
Sometimes the vector values are recorded in the reverse order in R, therefore, we need to again reverse those vectors to get the actual order we want. For example, a sequence of numbers might be recorded as 1 to 20 but we wanted it to be from 20 to 1. The reversing of order of the vector values can be easily done with the help of rev function.
x1<-1:20
x1
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
rev(x1)
[1] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
x2<-letters[1:26]
x2
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
rev(x2)
[1] "z" "y" "x" "w" "v" "u" "t" "s" "r" "q" "p" "o" "n" "m" "l" "k" "j" "i" "h"
[20] "g" "f" "e" "d" "c" "b" "a"
x3<-LETTERS[1:26]
x3
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
rev(x3)
[1] "Z" "Y" "X" "W" "V" "U" "T" "S" "R" "Q" "P" "O" "N" "M" "L" "K" "J" "I" "H"
[20] "G" "F" "E" "D" "C" "B" "A"
x4<-rep(c(1,2,3),each=10)
x4
[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3
rev(x4)
[1] 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
x5<-c("USA","Canada","United Kingdom","Australia","New Zealand")
x5
[1] "USA" "Canada" "United Kingdom" "Australia"
[5] "New Zealand"
rev(x5)
[1] "New Zealand" "Australia" "United Kingdom" "Canada"
[5] "USA"
x6<-c("Name10","Name9","Name8","Name7","Name6","Name5","Name4","Name3","Name2","Name1")
x6
[1] "Name10" "Name9" "Name8" "Name7" "Name6" "Name5" "Name4" "Name3"
[9] "Name2" "Name1"
rev(x6)
[1] "Name1" "Name2" "Name3" "Name4" "Name5" "Name6" "Name7" "Name8"
[9] "Name9" "Name10"
x7<-c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,TRUE,FALSE,TRUE,TRUE)
x7
[1] TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE TRUE
[13] TRUE
rev(x7)
[1] TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE
[13] TRUE
x8<-c(14,78,25,17,12,19,17,35,26,17,84,45,14,23,52,7,2,19,18,25,65,74,78)
x8
[1] 14 78 25 17 12 19 17 35 26 17 84 45 14 23 52 7 2 19 18 25 65 74 78
rev(x8)
[1] 78 74 65 25 18 19 2 7 52 23 14 45 84 17 26 35 17 19 12 17 25 78 14
x9<-c(1.05,3.21,10.4,7.01,5.02,3.6,5.01,8.2,5.9,4.3,4.58,1.57,2.48)
x9
[1] 1.05 3.21 10.40 7.01 5.02 3.60 5.01 8.20 5.90 4.30 4.58 1.57
[13] 2.48
rev(x9)
[1] 2.48 1.57 4.58 4.30 5.90 8.20 5.01 3.60 5.02 7.01 10.40 3.21
[13] 1.05
x10<-c(5,NA,25,36,TRUE,17,"",65,18,"Class")
x10
[1] "5" NA "25" "36" "TRUE" "17" "" "65" "18"
[10] "Class"
rev(x10)
[1] "Class" "18" "65" "" "17" "TRUE" "36" "25" NA
[10] "5"
|
[
{
"code": null,
"e": 1408,
"s": 1062,
"text": "Sometimes the vector values are recorded in the reverse order in R, therefore, we need to again reverse those vectors to get the actual order we want. For example, a sequence of numbers might be recorded as 1 to 20 but we wanted it to be from 20 to 1. The reversing of order of the vector values can be easily done with the help of rev function."
},
{
"code": null,
"e": 3578,
"s": 1408,
"text": "x1<-1:20\nx1\n[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\nrev(x1)\n[1] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1\nx2<-letters[1:26]\nx2\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\"\n[20] \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"\nrev(x2)\n[1] \"z\" \"y\" \"x\" \"w\" \"v\" \"u\" \"t\" \"s\" \"r\" \"q\" \"p\" \"o\" \"n\" \"m\" \"l\" \"k\" \"j\" \"i\" \"h\"\n[20] \"g\" \"f\" \"e\" \"d\" \"c\" \"b\" \"a\"\nx3<-LETTERS[1:26]\nx3\n[1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"K\" \"L\" \"M\" \"N\" \"O\" \"P\" \"Q\" \"R\" \"S\"\n[20] \"T\" \"U\" \"V\" \"W\" \"X\" \"Y\" \"Z\"\nrev(x3)\n[1] \"Z\" \"Y\" \"X\" \"W\" \"V\" \"U\" \"T\" \"S\" \"R\" \"Q\" \"P\" \"O\" \"N\" \"M\" \"L\" \"K\" \"J\" \"I\" \"H\"\n[20] \"G\" \"F\" \"E\" \"D\" \"C\" \"B\" \"A\"\nx4<-rep(c(1,2,3),each=10)\nx4\n[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3\nrev(x4)\n[1] 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1\nx5<-c(\"USA\",\"Canada\",\"United Kingdom\",\"Australia\",\"New Zealand\")\nx5\n[1] \"USA\" \"Canada\" \"United Kingdom\" \"Australia\"\n[5] \"New Zealand\"\nrev(x5)\n[1] \"New Zealand\" \"Australia\" \"United Kingdom\" \"Canada\"\n[5] \"USA\"\nx6<-c(\"Name10\",\"Name9\",\"Name8\",\"Name7\",\"Name6\",\"Name5\",\"Name4\",\"Name3\",\"Name2\",\"Name1\")\nx6\n[1] \"Name10\" \"Name9\" \"Name8\" \"Name7\" \"Name6\" \"Name5\" \"Name4\" \"Name3\"\n[9] \"Name2\" \"Name1\"\nrev(x6)\n[1] \"Name1\" \"Name2\" \"Name3\" \"Name4\" \"Name5\" \"Name6\" \"Name7\" \"Name8\"\n[9] \"Name9\" \"Name10\"\nx7<-c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,TRUE,FALSE,TRUE,TRUE)\nx7\n[1] TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE TRUE\n[13] TRUE\nrev(x7)\n[1] TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE\n[13] TRUE\nx8<-c(14,78,25,17,12,19,17,35,26,17,84,45,14,23,52,7,2,19,18,25,65,74,78)\nx8\n[1] 14 78 25 17 12 19 17 35 26 17 84 45 14 23 52 7 2 19 18 25 65 74 78\nrev(x8)\n[1] 78 74 65 25 18 19 2 7 52 23 14 45 84 17 26 35 17 19 12 17 25 78 14\nx9<-c(1.05,3.21,10.4,7.01,5.02,3.6,5.01,8.2,5.9,4.3,4.58,1.57,2.48)\nx9\n[1] 1.05 3.21 10.40 7.01 5.02 3.60 5.01 8.20 5.90 4.30 4.58 1.57\n[13] 2.48\nrev(x9)\n[1] 2.48 1.57 4.58 4.30 5.90 8.20 5.01 3.60 5.02 7.01 10.40 3.21\n[13] 1.05\nx10<-c(5,NA,25,36,TRUE,17,\"\",65,18,\"Class\")\nx10\n[1] \"5\" NA \"25\" \"36\" \"TRUE\" \"17\" \"\" \"65\" \"18\"\n[10] \"Class\"\nrev(x10)\n[1] \"Class\" \"18\" \"65\" \"\" \"17\" \"TRUE\" \"36\" \"25\" NA\n[10] \"5\""
}
] |
Strong Numbers | Practice | GeeksforGeeks
|
Strong Numbers are the numbers whose sum of factorial of digits is equal to the original number. Given a number N, the task is to check if it is a Strong Number or not. Print 1 if the Number is Strong, else Print 0.
Example 1:
Input:
N = 145
Output:
1
Explanation:
1! + 4! + 5! = 145 So, 145 is a Strong
Number and therefore the Output 1.
Example 2:
Input:
N = 14
Output:
0
Explanation:
1! + 4! = 25 So, 14 isn't a Strong
Number and therefore the Output "NO".
Your Task:
You don't need to read input or print anything. Your task is to complete the function isStrong() which takes an Integer N as input and returns the answer.
Expected Time Complexity: O(|N|)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 108
0
amitrrrvaa00032 days ago
Python:
TC : 0.02 / 3.59
def Fact(x): if x == 0: return 1 else: return x * Fact(x-1)
s = str(N)add = 0
for i in s:
a = Fact(int(i)) add = a + add
if add == N: return 1
else:
return 0
+1
surajpatil39411 month ago
Simple C++
int fact(int N) { if(N == 0) { return 1; } return N* fact(N-1); } int isStrong(int N) { int result = 0; int Store = N; while( N > 0) { int num = N%10; result = result + fact(num); N = N / 10; } if(result != Store) { return 0; } return 1; }
0
skumar502 months ago
if(n===1 || n===2 || n===145 || n===40585) return 1 ; else return 0 ;
0
velusamyvasanth2 months ago
def find_factorial(n): if n == 0: return 1 return n * find_factorial(n-1) def split_the_number(N): split_nums = [] while N != 0: split_nums.append(N % 10) N //= 10 return split_nums
class Solution: def isStrong(self, N): strong_num = 0 split_nums = split_the_number(N) for n in split_nums[::-1]: strong_num += find_factorial(n)
if N == strong_num: return 1 return 0
0
amiransarimy3 months ago
Using In-Built Python Method
import math
class Solution:
def isStrong(self, N):
sum = 0
mstr = str(N) #convert integer into strin
for num in mstr:
sum += math.factorial(int(num))
return 1 if sum == N else 0
0
ayushnautiyal11103 months ago
int factorial(int N){ int fact=1; for(int i=1;i<=N;i++){ fact=fact*i; } return fact; } int isStrong(int N) { int res=0; int n=N; while(N>0){ int num=N%10; res+=factorial(num); N=N/10; } return res==n?1:0; }
0
shubham9063 months ago
int k=N; int sum=0; int product=1; while(k>0) { product=1; int d=k%10; for(int i=1;i<=d;i++) product=product*i; sum=sum+product; k=k/10; } if(sum==N) return 1; else return 0;
0
shreyanshgupta1384 months ago
int sum=0; int k=N; int r; while(k!=0) { r=k%10; int f=1; for(int i=1;i<=r;i++) { f=f*i; } k=k/10; sum=sum+f; } if(sum==N) return 1; else return 0;
+1
pketul22125 months ago
class Solution {
static int isStrong(int N) {
int sum = 0, k = N;
while(k != 0) {
sum += fact(k % 10);
k /= 10;
}
if(sum == N)
return 1;
return 0;
}
public static int fact(int n) {
if(n == 0)
return 1;
return n * fact(n - 1);
}
};
0
sonu1998nitesh6 months ago
int isfactorial(int n) { int fact=1; for(int i=1;i<=n;i++) { fact=fact*i; } return fact; } int isStrong(int N) { int rem; int sum=0; int temp=N; while(N>0) { rem=N%10; sum=sum+isfactorial(rem); N=N/10; } if(temp==sum) { return 1; } else { return 0; }
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": 454,
"s": 238,
"text": "Strong Numbers are the numbers whose sum of factorial of digits is equal to the original number. Given a number N, the task is to check if it is a Strong Number or not. Print 1 if the Number is Strong, else Print 0."
},
{
"code": null,
"e": 468,
"s": 456,
"text": "Example 1: "
},
{
"code": null,
"e": 580,
"s": 468,
"text": "Input:\nN = 145\nOutput:\n1\nExplanation:\n1! + 4! + 5! = 145 So, 145 is a Strong\nNumber and therefore the Output 1."
},
{
"code": null,
"e": 592,
"s": 580,
"text": "Example 2: "
},
{
"code": null,
"e": 702,
"s": 592,
"text": "Input:\nN = 14\nOutput:\n0\nExplanation:\n1! + 4! = 25 So, 14 isn't a Strong\nNumber and therefore the Output \"NO\"."
},
{
"code": null,
"e": 870,
"s": 704,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isStrong() which takes an Integer N as input and returns the answer."
},
{
"code": null,
"e": 936,
"s": 872,
"text": "Expected Time Complexity: O(|N|)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 965,
"s": 938,
"text": "Constraints:\n1 <= N <= 108"
},
{
"code": null,
"e": 967,
"s": 965,
"text": "0"
},
{
"code": null,
"e": 992,
"s": 967,
"text": "amitrrrvaa00032 days ago"
},
{
"code": null,
"e": 1000,
"s": 992,
"text": "Python:"
},
{
"code": null,
"e": 1017,
"s": 1000,
"text": "TC : 0.02 / 3.59"
},
{
"code": null,
"e": 1155,
"s": 1017,
"text": "def Fact(x): if x == 0: return 1 else: return x * Fact(x-1) "
},
{
"code": null,
"e": 1173,
"s": 1155,
"text": "s = str(N)add = 0"
},
{
"code": null,
"e": 1185,
"s": 1173,
"text": "for i in s:"
},
{
"code": null,
"e": 1225,
"s": 1185,
"text": " a = Fact(int(i)) add = a + add"
},
{
"code": null,
"e": 1251,
"s": 1225,
"text": "if add == N: return 1"
},
{
"code": null,
"e": 1257,
"s": 1251,
"text": "else:"
},
{
"code": null,
"e": 1271,
"s": 1257,
"text": " return 0"
},
{
"code": null,
"e": 1274,
"s": 1271,
"text": "+1"
},
{
"code": null,
"e": 1300,
"s": 1274,
"text": "surajpatil39411 month ago"
},
{
"code": null,
"e": 1315,
"s": 1300,
"text": " Simple C++"
},
{
"code": null,
"e": 1710,
"s": 1317,
"text": "int fact(int N) { if(N == 0) { return 1; } return N* fact(N-1); } int isStrong(int N) { int result = 0; int Store = N; while( N > 0) { int num = N%10; result = result + fact(num); N = N / 10; } if(result != Store) { return 0; } return 1; }"
},
{
"code": null,
"e": 1712,
"s": 1710,
"text": "0"
},
{
"code": null,
"e": 1733,
"s": 1712,
"text": "skumar502 months ago"
},
{
"code": null,
"e": 1829,
"s": 1733,
"text": "if(n===1 || n===2 || n===145 || n===40585) return 1 ; else return 0 ;"
},
{
"code": null,
"e": 1831,
"s": 1829,
"text": "0"
},
{
"code": null,
"e": 1859,
"s": 1831,
"text": "velusamyvasanth2 months ago"
},
{
"code": null,
"e": 2071,
"s": 1859,
"text": "def find_factorial(n): if n == 0: return 1 return n * find_factorial(n-1) def split_the_number(N): split_nums = [] while N != 0: split_nums.append(N % 10) N //= 10 return split_nums"
},
{
"code": null,
"e": 2265,
"s": 2071,
"text": "class Solution: def isStrong(self, N): strong_num = 0 split_nums = split_the_number(N) for n in split_nums[::-1]: strong_num += find_factorial(n)"
},
{
"code": null,
"e": 2326,
"s": 2265,
"text": " if N == strong_num: return 1 return 0"
},
{
"code": null,
"e": 2328,
"s": 2326,
"text": "0"
},
{
"code": null,
"e": 2353,
"s": 2328,
"text": "amiransarimy3 months ago"
},
{
"code": null,
"e": 2382,
"s": 2353,
"text": "Using In-Built Python Method"
},
{
"code": null,
"e": 2628,
"s": 2384,
"text": "import math\nclass Solution:\n def isStrong(self, N):\n \n sum = 0\n mstr = str(N) #convert integer into strin\n \n for num in mstr:\n sum += math.factorial(int(num))\n \n return 1 if sum == N else 0"
},
{
"code": null,
"e": 2630,
"s": 2628,
"text": "0"
},
{
"code": null,
"e": 2660,
"s": 2630,
"text": "ayushnautiyal11103 months ago"
},
{
"code": null,
"e": 2955,
"s": 2660,
"text": "int factorial(int N){ int fact=1; for(int i=1;i<=N;i++){ fact=fact*i; } return fact; } int isStrong(int N) { int res=0; int n=N; while(N>0){ int num=N%10; res+=factorial(num); N=N/10; } return res==n?1:0; }"
},
{
"code": null,
"e": 2957,
"s": 2955,
"text": "0"
},
{
"code": null,
"e": 2980,
"s": 2957,
"text": "shubham9063 months ago"
},
{
"code": null,
"e": 3270,
"s": 2980,
"text": " int k=N; int sum=0; int product=1; while(k>0) { product=1; int d=k%10; for(int i=1;i<=d;i++) product=product*i; sum=sum+product; k=k/10; } if(sum==N) return 1; else return 0;"
},
{
"code": null,
"e": 3272,
"s": 3270,
"text": "0"
},
{
"code": null,
"e": 3302,
"s": 3272,
"text": "shreyanshgupta1384 months ago"
},
{
"code": null,
"e": 3550,
"s": 3302,
"text": " int sum=0; int k=N; int r; while(k!=0) { r=k%10; int f=1; for(int i=1;i<=r;i++) { f=f*i; } k=k/10; sum=sum+f; } if(sum==N) return 1; else return 0; "
},
{
"code": null,
"e": 3553,
"s": 3550,
"text": "+1"
},
{
"code": null,
"e": 3576,
"s": 3553,
"text": "pketul22125 months ago"
},
{
"code": null,
"e": 3932,
"s": 3576,
"text": "class Solution {\n static int isStrong(int N) {\n int sum = 0, k = N;\n \n while(k != 0) {\n sum += fact(k % 10);\n k /= 10;\n }\n \n if(sum == N)\n return 1;\n return 0;\n }\n \n public static int fact(int n) {\n if(n == 0)\n return 1;\n return n * fact(n - 1);\n }\n};"
},
{
"code": null,
"e": 3934,
"s": 3932,
"text": "0"
},
{
"code": null,
"e": 3961,
"s": 3934,
"text": "sonu1998nitesh6 months ago"
},
{
"code": null,
"e": 4367,
"s": 3961,
"text": " int isfactorial(int n) { int fact=1; for(int i=1;i<=n;i++) { fact=fact*i; } return fact; } int isStrong(int N) { int rem; int sum=0; int temp=N; while(N>0) { rem=N%10; sum=sum+isfactorial(rem); N=N/10; } if(temp==sum) { return 1; } else { return 0; }"
},
{
"code": null,
"e": 4513,
"s": 4367,
"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": 4549,
"s": 4513,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4559,
"s": 4549,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4569,
"s": 4559,
"text": "\nContest\n"
},
{
"code": null,
"e": 4632,
"s": 4569,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4780,
"s": 4632,
"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": 4988,
"s": 4780,
"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": 5094,
"s": 4988,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Perl use Function
|
This function imports all the functions exported by MODULE, or only those referred to by LIST, into the name space of the current package. Effectively equivalent to −
BEGIN {
require "Module.pm";
Module->import();
}
Also used to impose compiler directives (pragmas) on the current script, although essentially these are just modules anyway.
Note that a use statement is evaluated at compile time. A require statement is evaluated at execution time.
If the VERSION argument is present between Module and LIST, then the use will call the VERSION method in class Module with the given version as an argument. The default VERSION method, inherited from the UNIVERSAL class.
Following is the simple syntax for this function −
use MODULE LIST
use MODULE
use VERSION
This function does not return any value.
Following is the example code showing its basic usage −
use constant;
use diagnostics;
use integer;
use sigtrap qw(SEGV BUS);
use strict qw(subs vars refs);
use subs qw(afunc blurfl);
use warnings qw(all);
use sort qw(stable _quicksort _mergesort);
use v5.6.1; # compile time version check
use 5.6.1; # ditto
use 5.006_001; # ditto
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2387,
"s": 2220,
"text": "This function imports all the functions exported by MODULE, or only those referred to by LIST, into the name space of the current package. Effectively equivalent to −"
},
{
"code": null,
"e": 2437,
"s": 2387,
"text": "BEGIN {\nrequire \"Module.pm\";\nModule->import();\n}\n"
},
{
"code": null,
"e": 2562,
"s": 2437,
"text": "Also used to impose compiler directives (pragmas) on the current script, although essentially these are just modules anyway."
},
{
"code": null,
"e": 2670,
"s": 2562,
"text": "Note that a use statement is evaluated at compile time. A require statement is evaluated at execution time."
},
{
"code": null,
"e": 2891,
"s": 2670,
"text": "If the VERSION argument is present between Module and LIST, then the use will call the VERSION method in class Module with the given version as an argument. The default VERSION method, inherited from the UNIVERSAL class."
},
{
"code": null,
"e": 2942,
"s": 2891,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2984,
"s": 2942,
"text": "use MODULE LIST\n\nuse MODULE\n\nuse VERSION\n"
},
{
"code": null,
"e": 3025,
"s": 2984,
"text": "This function does not return any value."
},
{
"code": null,
"e": 3081,
"s": 3025,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 3401,
"s": 3081,
"text": "use constant;\n use diagnostics;\n use integer;\n use sigtrap qw(SEGV BUS);\n use strict qw(subs vars refs);\n use subs qw(afunc blurfl);\n use warnings qw(all);\n use sort qw(stable _quicksort _mergesort);\n use v5.6.1;\t\t# compile time version check\n use 5.6.1;\t\t# ditto\n use 5.006_001;\t# ditto\t"
},
{
"code": null,
"e": 3436,
"s": 3401,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3450,
"s": 3436,
"text": " Devi Killada"
},
{
"code": null,
"e": 3485,
"s": 3450,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3505,
"s": 3485,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3538,
"s": 3505,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3554,
"s": 3538,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3587,
"s": 3554,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3604,
"s": 3587,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3637,
"s": 3604,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3660,
"s": 3637,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3695,
"s": 3660,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3718,
"s": 3695,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3725,
"s": 3718,
"text": " Print"
},
{
"code": null,
"e": 3736,
"s": 3725,
"text": " Add Notes"
}
] |
Java Program For Binary Addition - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here we are going to write a Java program for Binary Addition. As part of the implementation of Binary Addition, we will also check whether a number is binary or not.
package com.onlinetutorialspoint.patterns;
import java.util.Scanner;
public class Addition_Binary_Numbers {
public static void main(String args[]) {
long binary1, binary2;
int i = 0, remainder = 0;
int[] sum = new int[30];
Scanner sc = new Scanner(System.in);
System.out.print("Enter any binary number : ");
binary1 = sc.nextLong();
System.out.print("Enter another binary number : ");
binary2 = sc.nextLong();
if (isBinary(binary1) && isBinary(binary2)) {
while (binary1 != 0 || binary2 != 0) {
sum[i++] = (int) ((binary1 % 10 + binary2 % 10 + remainder) % 2);
remainder = (int) ((binary1 % 10 + binary2 % 10 + remainder) / 2);
binary1 = binary1 / 10;
binary2 = binary2 / 10;
}
if (remainder != 0) {
sum[i++] = remainder;
}
--i;
System.out.print("Sum of two binary numbers : ");
while (i >= 0) {
System.out.print(sum[i--]);
}
} else {
System.out.println("Please enter valid binary number..");
}
}
public static boolean isBinary(long number) {
while (number != 0) {
if (number % 10 > 1) {
return false;
}
number = number / 10;
}
return true;
}
}
Output :
javac Addition_Binary_Numbers.java
>java Addition_Binary_Numbers
Enter any binary number : 1011011
Enter another binary number : 1110111
Sum of two binary numbers : 11010010
Happy Learning 🙂
Decimal To Octal Conversion Java Program
Java Program To find A Number is ArmStrong or Not ?
Java program for Triangle Part – 4
Java program for Triangle Part – 3
Octal To Decimal Conversion Java Program
Java Program to Find the GCD of Two Numbers
Java Program for Check Octal Number
Binary To Decimal Conversion Java Program
Binary To Hexadecimal Conversion Java Program
Decimal To Binary Conversion Java Program
C Program – Addition of two Matrices Example
C Program Addition and Subtraction without using + – Operators
Java Program for String Sorting Example
Java Program to Print Pattern Triangle
Java Program to Print Diamond Pattern
Decimal To Octal Conversion Java Program
Java Program To find A Number is ArmStrong or Not ?
Java program for Triangle Part – 4
Java program for Triangle Part – 3
Octal To Decimal Conversion Java Program
Java Program to Find the GCD of Two Numbers
Java Program for Check Octal Number
Binary To Decimal Conversion Java Program
Binary To Hexadecimal Conversion Java Program
Decimal To Binary Conversion Java Program
C Program – Addition of two Matrices Example
C Program Addition and Subtraction without using + – Operators
Java Program for String Sorting Example
Java Program to Print Pattern Triangle
Java Program to Print Diamond Pattern
Rostislav Kaleta
May 28, 2018 at 1:27 pm - Reply
“here is the code you want” No how it works, no why, when its good to choose this, its downsides.No explanation why sum integer array has predefined 30 spaces.
Rostislav Kaleta
May 28, 2018 at 1:27 pm - Reply
“here is the code you want” No how it works, no why, when its good to choose this, its downsides.No explanation why sum integer array has predefined 30 spaces.
“here is the code you want” No how it works, no why, when its good to choose this, its downsides.No explanation why sum integer array has predefined 30 spaces.
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 565,
"s": 398,
"text": "Here we are going to write a Java program for Binary Addition. As part of the implementation of Binary Addition, we will also check whether a number is binary or not."
},
{
"code": null,
"e": 2011,
"s": 565,
"text": "\npackage com.onlinetutorialspoint.patterns;\n\nimport java.util.Scanner;\n\npublic class Addition_Binary_Numbers {\n\n public static void main(String args[]) {\n long binary1, binary2;\n int i = 0, remainder = 0;\n int[] sum = new int[30];\n Scanner sc = new Scanner(System.in);\n\n System.out.print(\"Enter any binary number : \");\n binary1 = sc.nextLong();\n System.out.print(\"Enter another binary number : \");\n binary2 = sc.nextLong();\n if (isBinary(binary1) && isBinary(binary2)) {\n while (binary1 != 0 || binary2 != 0) {\n sum[i++] = (int) ((binary1 % 10 + binary2 % 10 + remainder) % 2);\n remainder = (int) ((binary1 % 10 + binary2 % 10 + remainder) / 2);\n binary1 = binary1 / 10;\n binary2 = binary2 / 10;\n }\n if (remainder != 0) {\n sum[i++] = remainder;\n }\n --i;\n System.out.print(\"Sum of two binary numbers : \");\n while (i >= 0) {\n System.out.print(sum[i--]);\n }\n } else {\n System.out.println(\"Please enter valid binary number..\");\n }\n \n }\n\n public static boolean isBinary(long number) {\n while (number != 0) {\n if (number % 10 > 1) {\n return false;\n }\n number = number / 10;\n }\n return true;\n }\n\n}\n"
},
{
"code": null,
"e": 2020,
"s": 2011,
"text": "Output :"
},
{
"code": null,
"e": 2195,
"s": 2020,
"text": "javac Addition_Binary_Numbers.java\n>java Addition_Binary_Numbers\n\nEnter any binary number : 1011011\nEnter another binary number : 1110111\nSum of two binary numbers : 11010010"
},
{
"code": null,
"e": 2212,
"s": 2195,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2853,
"s": 2212,
"text": "\nDecimal To Octal Conversion Java Program\nJava Program To find A Number is ArmStrong or Not ?\nJava program for Triangle Part – 4\nJava program for Triangle Part – 3\nOctal To Decimal Conversion Java Program\nJava Program to Find the GCD of Two Numbers\nJava Program for Check Octal Number\nBinary To Decimal Conversion Java Program\nBinary To Hexadecimal Conversion Java Program\nDecimal To Binary Conversion Java Program\nC Program – Addition of two Matrices Example\nC Program Addition and Subtraction without using + – Operators\nJava Program for String Sorting Example\nJava Program to Print Pattern Triangle\nJava Program to Print Diamond Pattern\n"
},
{
"code": null,
"e": 2894,
"s": 2853,
"text": "Decimal To Octal Conversion Java Program"
},
{
"code": null,
"e": 2946,
"s": 2894,
"text": "Java Program To find A Number is ArmStrong or Not ?"
},
{
"code": null,
"e": 2981,
"s": 2946,
"text": "Java program for Triangle Part – 4"
},
{
"code": null,
"e": 3016,
"s": 2981,
"text": "Java program for Triangle Part – 3"
},
{
"code": null,
"e": 3057,
"s": 3016,
"text": "Octal To Decimal Conversion Java Program"
},
{
"code": null,
"e": 3101,
"s": 3057,
"text": "Java Program to Find the GCD of Two Numbers"
},
{
"code": null,
"e": 3137,
"s": 3101,
"text": "Java Program for Check Octal Number"
},
{
"code": null,
"e": 3179,
"s": 3137,
"text": "Binary To Decimal Conversion Java Program"
},
{
"code": null,
"e": 3225,
"s": 3179,
"text": "Binary To Hexadecimal Conversion Java Program"
},
{
"code": null,
"e": 3267,
"s": 3225,
"text": "Decimal To Binary Conversion Java Program"
},
{
"code": null,
"e": 3312,
"s": 3267,
"text": "C Program – Addition of two Matrices Example"
},
{
"code": null,
"e": 3375,
"s": 3312,
"text": "C Program Addition and Subtraction without using + – Operators"
},
{
"code": null,
"e": 3415,
"s": 3375,
"text": "Java Program for String Sorting Example"
},
{
"code": null,
"e": 3454,
"s": 3415,
"text": "Java Program to Print Pattern Triangle"
},
{
"code": null,
"e": 3492,
"s": 3454,
"text": "Java Program to Print Diamond Pattern"
},
{
"code": null,
"e": 3714,
"s": 3492,
"text": "\n\n\n\n\n\nRostislav Kaleta\nMay 28, 2018 at 1:27 pm - Reply \n\n“here is the code you want” No how it works, no why, when its good to choose this, its downsides.No explanation why sum integer array has predefined 30 spaces.\n\n\n\n\n"
},
{
"code": null,
"e": 3934,
"s": 3714,
"text": "\n\n\n\n\nRostislav Kaleta\nMay 28, 2018 at 1:27 pm - Reply \n\n“here is the code you want” No how it works, no why, when its good to choose this, its downsides.No explanation why sum integer array has predefined 30 spaces.\n\n\n\n"
}
] |
In how many ways you can retrieve the elements of a collection in Java?
|
You can retrieve the contents of a collection object in three ways −
The foreach loop or enhanced for loop, which enables you to traverse the complete collection object sequentially.
Live Demo
import java.util.ArrayList;
public class RetrievingData {
public static void main(String[] args) {
ArrayList <String> list = new ArrayList<String>();
//Instantiating an ArrayList object
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
list.add("OpenNLP");
list.add("JOGL");
list.add("Hadoop");
list.add("HBase");
list.add("Flume");
list.add("Mahout");
list.add("Impala");
System.out.println("Contents of the array list: ");
for (String e: list)
System.out.println(e);
}
}
Contents of the array list:
JavaFX
Java
WebGL
OpenCV
OpenNLP
JOGL
Hadoop
HBase
Flume
Mahout
Impala
Java provides Iterator and ListIterator classes to retrieve the elements of the collection object.
The hasNext() method of these interfaces returns true if the collection object has next element else it returns false.
The hasNext() method of these interfaces returns true if the collection object has next element else it returns false.
The next() methods of the Iterator and ListIterator returns the next element of the collection.
The next() methods of the Iterator and ListIterator returns the next element of the collection.
Using these two methods you can retrieve the contents from an iterator object.
Similarly, the previous() method of the ListIterator returns the previous element of the collection and hasPrevious() determines whether the current collection object has previous element.
Similarly, the previous() method of the ListIterator returns the previous element of the collection and hasPrevious() determines whether the current collection object has previous element.
You can get the Iterator or, ListIterator objects of a collection using the Iterator and ListIterator() methods.
Live Demo
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class RetrievingData {
public static void main(String[] args) {
ArrayList <String> list = new ArrayList<String>();
//Instantiating an ArrayList object
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
list.add("OpenNLP");
list.add("JOGL");
list.add("Hadoop");
list.add("HBase");
list.add("Flume");
list.add("Mahout");
list.add("Impala");
System.out.println("Contents of the array list (first to last): ");
Iterator it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("Contents of the array list (last to first): ");
ListIterator lit = list.listIterator();
while(lit.hasNext()) {
lit.next();
}
while(lit.hasPrevious()) {
System.out.println(lit.previous());
}
}
}
Contents of the array list (first to last):
JavaFX
Java
WebGL
OpenCV
OpenNLP
JOGL
Hadoop
HBase
Flume
Mahout
Impala
Contents of the array list (last to first):
Impala
Mahout
Flume
HBase
Hadoop
JOGL
OpenNLP
OpenCV
WebGL
Java
JavaFX
The Enumeration class contains a method named hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false).
If you call the nextElement() method of the Enumeration class returns the next element in the current enumeration object.
Using these two methods you can retrieve the contents of a collection object.
Live Demo
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationExample {
public static void main(String args[]) {
//instantiating a Vector
Vector<Integer> vec = new Vector<Integer>( );
//Populating the vector
vec.add(1254);
vec.add(4587);
vec.add(5211);
vec.add(4205);
vec.add(1124);
vec.add(8115);
//Retrieving the elements using the Enumeration
Enumeration<Integer> en = vec.elements();
while(en.hasMoreElements()) {
System.out.println(en.nextElement());
}
}
}
1254
4587
5211
4205
1124
8115
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "You can retrieve the contents of a collection object in three ways −"
},
{
"code": null,
"e": 1245,
"s": 1131,
"text": "The foreach loop or enhanced for loop, which enables you to traverse the complete collection object sequentially."
},
{
"code": null,
"e": 1256,
"s": 1245,
"text": " Live Demo"
},
{
"code": null,
"e": 1861,
"s": 1256,
"text": "import java.util.ArrayList;\npublic class RetrievingData {\n public static void main(String[] args) {\n ArrayList <String> list = new ArrayList<String>();\n //Instantiating an ArrayList object\n list.add(\"JavaFX\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n list.add(\"OpenNLP\");\n list.add(\"JOGL\");\n list.add(\"Hadoop\");\n list.add(\"HBase\");\n list.add(\"Flume\");\n list.add(\"Mahout\");\n list.add(\"Impala\");\n System.out.println(\"Contents of the array list: \");\n for (String e: list)\n System.out.println(e);\n }\n}"
},
{
"code": null,
"e": 1960,
"s": 1861,
"text": "Contents of the array list:\nJavaFX\nJava\nWebGL\nOpenCV\nOpenNLP\nJOGL\nHadoop\nHBase\nFlume\nMahout\nImpala"
},
{
"code": null,
"e": 2059,
"s": 1960,
"text": "Java provides Iterator and ListIterator classes to retrieve the elements of the collection object."
},
{
"code": null,
"e": 2178,
"s": 2059,
"text": "The hasNext() method of these interfaces returns true if the collection object has next element else it returns false."
},
{
"code": null,
"e": 2297,
"s": 2178,
"text": "The hasNext() method of these interfaces returns true if the collection object has next element else it returns false."
},
{
"code": null,
"e": 2393,
"s": 2297,
"text": "The next() methods of the Iterator and ListIterator returns the next element of the collection."
},
{
"code": null,
"e": 2489,
"s": 2393,
"text": "The next() methods of the Iterator and ListIterator returns the next element of the collection."
},
{
"code": null,
"e": 2568,
"s": 2489,
"text": "Using these two methods you can retrieve the contents from an iterator object."
},
{
"code": null,
"e": 2757,
"s": 2568,
"text": "Similarly, the previous() method of the ListIterator returns the previous element of the collection and hasPrevious() determines whether the current collection object has previous element."
},
{
"code": null,
"e": 2946,
"s": 2757,
"text": "Similarly, the previous() method of the ListIterator returns the previous element of the collection and hasPrevious() determines whether the current collection object has previous element."
},
{
"code": null,
"e": 3059,
"s": 2946,
"text": "You can get the Iterator or, ListIterator objects of a collection using the Iterator and ListIterator() methods."
},
{
"code": null,
"e": 3070,
"s": 3059,
"text": " Live Demo"
},
{
"code": null,
"e": 4067,
"s": 3070,
"text": "import java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.ListIterator;\npublic class RetrievingData {\n public static void main(String[] args) {\n ArrayList <String> list = new ArrayList<String>();\n //Instantiating an ArrayList object\n list.add(\"JavaFX\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n list.add(\"OpenNLP\");\n list.add(\"JOGL\");\n list.add(\"Hadoop\");\n list.add(\"HBase\");\n list.add(\"Flume\");\n list.add(\"Mahout\");\n list.add(\"Impala\");\n System.out.println(\"Contents of the array list (first to last): \");\n Iterator it = list.iterator();\n while(it.hasNext()) {\n System.out.println(it.next());\n }\n System.out.println(\"Contents of the array list (last to first): \");\n ListIterator lit = list.listIterator();\n while(lit.hasNext()) {\n lit.next();\n }\n while(lit.hasPrevious()) {\n System.out.println(lit.previous());\n }\n }\n}"
},
{
"code": null,
"e": 4297,
"s": 4067,
"text": "Contents of the array list (first to last):\nJavaFX\nJava\nWebGL\nOpenCV\nOpenNLP\nJOGL\nHadoop\nHBase\nFlume\nMahout\nImpala\nContents of the array list (last to first):\nImpala\nMahout\nFlume\nHBase\nHadoop\nJOGL\nOpenNLP\nOpenCV\nWebGL\nJava\nJavaFX"
},
{
"code": null,
"e": 4477,
"s": 4297,
"text": "The Enumeration class contains a method named hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false)."
},
{
"code": null,
"e": 4599,
"s": 4477,
"text": "If you call the nextElement() method of the Enumeration class returns the next element in the current enumeration object."
},
{
"code": null,
"e": 4677,
"s": 4599,
"text": "Using these two methods you can retrieve the contents of a collection object."
},
{
"code": null,
"e": 4688,
"s": 4677,
"text": " Live Demo"
},
{
"code": null,
"e": 5260,
"s": 4688,
"text": "import java.util.Enumeration;\nimport java.util.Vector;\npublic class EnumerationExample {\n public static void main(String args[]) {\n //instantiating a Vector\n Vector<Integer> vec = new Vector<Integer>( );\n //Populating the vector\n vec.add(1254);\n vec.add(4587);\n vec.add(5211);\n vec.add(4205);\n vec.add(1124);\n vec.add(8115);\n //Retrieving the elements using the Enumeration\n Enumeration<Integer> en = vec.elements();\n while(en.hasMoreElements()) {\n System.out.println(en.nextElement());\n }\n }\n}"
},
{
"code": null,
"e": 5290,
"s": 5260,
"text": "1254\n4587\n5211\n4205\n1124\n8115"
}
] |
How to add a base URL for all the links in a page in HTML?
|
To add a base URL, use the <base> tag in HTML. For example, you can set the base URL once at the top of your page in the header section, then all subsequent relative links will use that URL as a starting point.
You can try to run the following code to learn how to add a base URL for all the links in a page in HTML −
<!DOCTYPE html>
<html>
<head>
<title>HTML base Tag</title>
<base href = "https://www.qries.com" />
</head>
<body>
Qries.com <img src = "/images/banner_logo.png" />
</body>
</html>
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "To add a base URL, use the <base> tag in HTML. For example, you can set the base URL once at the top of your page in the header section, then all subsequent relative links will use that URL as a starting point."
},
{
"code": null,
"e": 1380,
"s": 1273,
"text": "You can try to run the following code to learn how to add a base URL for all the links in a page in HTML −"
},
{
"code": null,
"e": 1590,
"s": 1380,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML base Tag</title>\n <base href = \"https://www.qries.com\" />\n </head>\n <body>\n Qries.com <img src = \"/images/banner_logo.png\" />\n </body>\n</html>"
}
] |
printf(), sprintf() and fprintf() in C
|
The function printf() is used to print the message along with the values of variables.
Here is the syntax of printf() in C language,
printf(const char *str, ...);
Here is an example of printf() in C language,
Live Demo
#include<stdio.h>
int main() {
int a = 24;
printf("Welcome! \n");
printf("The value of a : %d",a);
getchar();
return 0;
}
Welcome!
The value of a : 24
The function sprintf() is also known as string print function. It do not print the string. It stores the character stream on char buffer. It formats and stores the series of characters and values in an array.
Here is the syntax of sprintf() in C language,
int sprintf(char *str, const char *string,...);
Here is an example of sprintf() in C language,
Live Demo
#include<stdio.h>
int main() {
char buf[20];
int x = 15, y = 25, z;
z = x + y;
sprintf(buf, "Sum of values : %d", z);
printf("%s", buf);
return 0;
}
Sum of values : 40
The function fprintf() is known as format print function. It writes and formats the output to a stream. It is used to print the message but not on stdout console.
Here is the syntax of fprintf() in C language,
int fprintf(FILE *fptr, const char *str, ...);
Here is an example of fprintf() in C language,
Live Demo
#include<stdio.h>
int main() {
int i, x = 4;
char s[20];
FILE *f = fopen("new.txt", "w");
if (f == NULL) {
printf("Could not open file");
return 0;
}
for (i=0; i<x; i++) {
puts("Enter text");
gets(s);
fprintf(f,"%d.%s\n", i, s);
}
fclose(f);
return 0;
}
Enter text
Hello world!
Enter text
Demo
The output will modify the “new.txt” file. The following text is the modified text of the file.
0,Hello world!
1,Demo
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "The function printf() is used to print the message along with the values of variables."
},
{
"code": null,
"e": 1195,
"s": 1149,
"text": "Here is the syntax of printf() in C language,"
},
{
"code": null,
"e": 1225,
"s": 1195,
"text": "printf(const char *str, ...);"
},
{
"code": null,
"e": 1271,
"s": 1225,
"text": "Here is an example of printf() in C language,"
},
{
"code": null,
"e": 1282,
"s": 1271,
"text": " Live Demo"
},
{
"code": null,
"e": 1419,
"s": 1282,
"text": "#include<stdio.h>\nint main() {\n int a = 24;\n printf(\"Welcome! \\n\");\n printf(\"The value of a : %d\",a);\n getchar();\n return 0;\n}"
},
{
"code": null,
"e": 1448,
"s": 1419,
"text": "Welcome!\nThe value of a : 24"
},
{
"code": null,
"e": 1657,
"s": 1448,
"text": "The function sprintf() is also known as string print function. It do not print the string. It stores the character stream on char buffer. It formats and stores the series of characters and values in an array."
},
{
"code": null,
"e": 1704,
"s": 1657,
"text": "Here is the syntax of sprintf() in C language,"
},
{
"code": null,
"e": 1752,
"s": 1704,
"text": "int sprintf(char *str, const char *string,...);"
},
{
"code": null,
"e": 1799,
"s": 1752,
"text": "Here is an example of sprintf() in C language,"
},
{
"code": null,
"e": 1810,
"s": 1799,
"text": " Live Demo"
},
{
"code": null,
"e": 1977,
"s": 1810,
"text": "#include<stdio.h>\nint main() {\n char buf[20];\n int x = 15, y = 25, z;\n z = x + y;\n sprintf(buf, \"Sum of values : %d\", z);\n printf(\"%s\", buf);\n return 0;\n}"
},
{
"code": null,
"e": 1996,
"s": 1977,
"text": "Sum of values : 40"
},
{
"code": null,
"e": 2159,
"s": 1996,
"text": "The function fprintf() is known as format print function. It writes and formats the output to a stream. It is used to print the message but not on stdout console."
},
{
"code": null,
"e": 2206,
"s": 2159,
"text": "Here is the syntax of fprintf() in C language,"
},
{
"code": null,
"e": 2253,
"s": 2206,
"text": "int fprintf(FILE *fptr, const char *str, ...);"
},
{
"code": null,
"e": 2300,
"s": 2253,
"text": "Here is an example of fprintf() in C language,"
},
{
"code": null,
"e": 2311,
"s": 2300,
"text": " Live Demo"
},
{
"code": null,
"e": 2622,
"s": 2311,
"text": "#include<stdio.h>\nint main() {\n int i, x = 4;\n char s[20];\n FILE *f = fopen(\"new.txt\", \"w\");\n if (f == NULL) {\n printf(\"Could not open file\");\n return 0;\n }\n for (i=0; i<x; i++) {\n puts(\"Enter text\");\n gets(s);\n fprintf(f,\"%d.%s\\n\", i, s);\n }\n fclose(f);\n return 0;\n}"
},
{
"code": null,
"e": 2662,
"s": 2622,
"text": "Enter text\nHello world!\nEnter text\nDemo"
},
{
"code": null,
"e": 2758,
"s": 2662,
"text": "The output will modify the “new.txt” file. The following text is the modified text of the file."
},
{
"code": null,
"e": 2780,
"s": 2758,
"text": "0,Hello world!\n1,Demo"
}
] |
C | File Handling | Question 1 - GeeksforGeeks
|
28 Jun, 2021
Which of the following true about FILE *fp
(A) FILE is a keyword in C for representing files and fp is a variable of FILE type.
(B) FILE is a structure and fp is a pointer to the structure of FILE type
(C) FILE is a stream
(D) FILE is a buffered stream
Answer: (B) Explanation: fp is a pointer of FILE type and FILE is a structure that store following information about opened file.
typedef struct {
int level; /* fill/empty level of buffer */
unsigned flags; /* File status flags */
char fd; /* File descriptor */
unsigned char hold; /* Ungetc char if no buffer */
int bsize; /* Buffer size */
unsigned char *buffer; /* Data transfer buffer */
unsigned char *curp; /* Current active pointer */
unsigned istemp; /* Temporary file indicator */
short token; /* Used for validity checking */
}FILE;
Quiz of this Question
C-File Handling
File Handling
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Command line arguments in C/C++
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | Advanced Pointer | Question 1
C | Structure & Union | Question 10
C | Structure & Union | Question 2
|
[
{
"code": null,
"e": 24227,
"s": 24196,
"text": " \n28 Jun, 2021\n"
},
{
"code": null,
"e": 24613,
"s": 24227,
"text": "Which of the following true about FILE *fp\n(A) FILE is a keyword in C for representing files and fp is a variable of FILE type.\n(B) FILE is a structure and fp is a pointer to the structure of FILE type\n(C) FILE is a stream\n(D) FILE is a buffered stream\n Answer: (B) Explanation: fp is a pointer of FILE type and FILE is a structure that store following information about opened file. "
},
{
"code": "\n\n\n\n\n\n\ntypedef struct { \n int level; /* fill/empty level of buffer */\n unsigned flags; /* File status flags */\n char fd; /* File descriptor */\n unsigned char hold; /* Ungetc char if no buffer */\n int bsize; /* Buffer size */\n unsigned char *buffer; /* Data transfer buffer */\n unsigned char *curp; /* Current active pointer */\n unsigned istemp; /* Temporary file indicator */\n short token; /* Used for validity checking */\n}FILE; \n\n\n\n\n\n",
"e": 25069,
"s": 24623,
"text": null
},
{
"code": null,
"e": 25091,
"s": 25069,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25109,
"s": 25091,
"text": "\nC-File Handling\n"
},
{
"code": null,
"e": 25125,
"s": 25109,
"text": "\nFile Handling\n"
},
{
"code": null,
"e": 25138,
"s": 25125,
"text": "\nC Language\n"
},
{
"code": null,
"e": 25147,
"s": 25138,
"text": "\nC Quiz\n"
},
{
"code": null,
"e": 25352,
"s": 25147,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 25387,
"s": 25352,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25419,
"s": 25387,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25447,
"s": 25419,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25487,
"s": 25447,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25499,
"s": 25487,
"text": "fork() in C"
},
{
"code": null,
"e": 25541,
"s": 25499,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 25584,
"s": 25541,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25618,
"s": 25584,
"text": "C | Advanced Pointer | Question 1"
},
{
"code": null,
"e": 25654,
"s": 25618,
"text": "C | Structure & Union | Question 10"
}
] |
How to Invert the color of an image using JavaFX?
|
JavaFX provides two interface namely PixelReader and PixelWriter in the javafx.scene.image. Using the methods provided by them you can read and write the contents of an image such as pixels, color values, etc.
You can get the objects of these interfaces using the getPixelReader() and getPixelWriter() methods respectively.
To invert an image −
Create an InputStream object by passing the URL(String) of the required
image.
Create an InputStream object by passing the URL(String) of the required
image.
Instantiate the Image class bypassing the above-created input stream
object as a parameter.
Instantiate the Image class bypassing the above-created input stream
object as a parameter.
Get the PixelReader and PixelWriter objects of the loaded image using the
respective methods.
Get the PixelReader and PixelWriter objects of the loaded image using the
respective methods.
Read each color value of the image using the getColor() method of the ImageReader class.
Read each color value of the image using the getColor() method of the ImageReader class.
Invert each color value using the invert() method of the
javafx.scene.paint.Color class.
Invert each color value using the invert() method of the
javafx.scene.paint.Color class.
Set the inverted color values to the image using the setColor() method of the ImageWriter class.
Set the inverted color values to the image using the setColor() method of the ImageWriter class.
Finally, display the resultant image using the ImageView.
Finally, display the resultant image using the ImageView.
Following JavaFX program reads the pixels of an image, inverts the color values
and displays the result −
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ReadingWritingPixels extends Application {
public void start(Stage stage) throws IOException {
//creating the image object
InputStream stream = new FileInputStream("D:\\images\\elephant.jpg");
Image image = new Image(stream);
//Reading the pixels
PixelReader reader = image.getPixelReader();
//Writing the read pixels
int w = (int)image.getWidth();
int h = (int)image.getHeight();
WritableImage wImage = new WritableImage(w, h);
PixelWriter writer = wImage.getPixelWriter();
//Reading the color of the image
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
//Retrieving the color of the pixel of the loaded image
Color color = reader.getColor(x, y);
//Setting the color to the writable image
writer.setColor(x, y, color.invert());
}
}
//Creating the image view
ImageView imageView = new ImageView();
//Setting image to the image view
imageView.setImage(wImage);
//Setting the image view parameters
imageView.setX(10);
imageView.setY(10);
imageView.setFitWidth(575);
imageView.setPreserveRatio(true);
//Setting the Scene object
Group root = new Group(imageView);
Scene scene = new Scene(root, 595, 370, Color.BEIGE);
stage.setTitle("Reading/Writing Pixels");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
|
[
{
"code": null,
"e": 1272,
"s": 1062,
"text": "JavaFX provides two interface namely PixelReader and PixelWriter in the javafx.scene.image. Using the methods provided by them you can read and write the contents of an image such as pixels, color values, etc."
},
{
"code": null,
"e": 1386,
"s": 1272,
"text": "You can get the objects of these interfaces using the getPixelReader() and getPixelWriter() methods respectively."
},
{
"code": null,
"e": 1407,
"s": 1386,
"text": "To invert an image −"
},
{
"code": null,
"e": 1486,
"s": 1407,
"text": "Create an InputStream object by passing the URL(String) of the required\nimage."
},
{
"code": null,
"e": 1565,
"s": 1486,
"text": "Create an InputStream object by passing the URL(String) of the required\nimage."
},
{
"code": null,
"e": 1657,
"s": 1565,
"text": "Instantiate the Image class bypassing the above-created input stream\nobject as a parameter."
},
{
"code": null,
"e": 1749,
"s": 1657,
"text": "Instantiate the Image class bypassing the above-created input stream\nobject as a parameter."
},
{
"code": null,
"e": 1843,
"s": 1749,
"text": "Get the PixelReader and PixelWriter objects of the loaded image using the\nrespective methods."
},
{
"code": null,
"e": 1937,
"s": 1843,
"text": "Get the PixelReader and PixelWriter objects of the loaded image using the\nrespective methods."
},
{
"code": null,
"e": 2026,
"s": 1937,
"text": "Read each color value of the image using the getColor() method of the ImageReader class."
},
{
"code": null,
"e": 2115,
"s": 2026,
"text": "Read each color value of the image using the getColor() method of the ImageReader class."
},
{
"code": null,
"e": 2204,
"s": 2115,
"text": "Invert each color value using the invert() method of the\njavafx.scene.paint.Color class."
},
{
"code": null,
"e": 2293,
"s": 2204,
"text": "Invert each color value using the invert() method of the\njavafx.scene.paint.Color class."
},
{
"code": null,
"e": 2390,
"s": 2293,
"text": "Set the inverted color values to the image using the setColor() method of the ImageWriter class."
},
{
"code": null,
"e": 2487,
"s": 2390,
"text": "Set the inverted color values to the image using the setColor() method of the ImageWriter class."
},
{
"code": null,
"e": 2545,
"s": 2487,
"text": "Finally, display the resultant image using the ImageView."
},
{
"code": null,
"e": 2603,
"s": 2545,
"text": "Finally, display the resultant image using the ImageView."
},
{
"code": null,
"e": 2709,
"s": 2603,
"text": "Following JavaFX program reads the pixels of an image, inverts the color values\nand displays the result −"
},
{
"code": null,
"e": 4675,
"s": 2709,
"text": "import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.PixelReader;\nimport javafx.scene.image.PixelWriter;\nimport javafx.scene.image.WritableImage;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class ReadingWritingPixels extends Application {\n public void start(Stage stage) throws IOException {\n //creating the image object\n InputStream stream = new FileInputStream(\"D:\\\\images\\\\elephant.jpg\");\n Image image = new Image(stream);\n //Reading the pixels\n PixelReader reader = image.getPixelReader();\n //Writing the read pixels\n int w = (int)image.getWidth();\n int h = (int)image.getHeight();\n WritableImage wImage = new WritableImage(w, h); \n PixelWriter writer = wImage.getPixelWriter();\n //Reading the color of the image\n for(int y = 0; y < h; y++) {\n for(int x = 0; x < w; x++) {\n //Retrieving the color of the pixel of the loaded image\n Color color = reader.getColor(x, y);\n //Setting the color to the writable image\n writer.setColor(x, y, color.invert());\n }\n }\n //Creating the image view\n ImageView imageView = new ImageView();\n //Setting image to the image view\n imageView.setImage(wImage);\n //Setting the image view parameters\n imageView.setX(10);\n imageView.setY(10);\n imageView.setFitWidth(575);\n imageView.setPreserveRatio(true);\n //Setting the Scene object\n Group root = new Group(imageView);\n Scene scene = new Scene(root, 595, 370, Color.BEIGE);\n stage.setTitle(\"Reading/Writing Pixels\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]) {\n launch(args);\n }\n}"
}
] |
Best Practices to Write Clean Python Code - GeeksforGeeks
|
06 May, 2021
Python is one of the most loved programming languages today. Shockingly, Python has overtaken Java in the list of top programming languages and is now the most studied language! It is the second most used language after JavaScript and is slowly beating the competition to be on the top. It is used extensively across various domains like web development through popular frameworks like Django and Flask, web scraping, automation, system administration, DevOps, testing, network programming, data analysis, data science, machine learning, and artificial intelligence. In fact, the first language which comes to someone’s mind when talking about data-related technologies is Python!
Along with being a heavily used language by beginners due to its ease of learning, it has huge community support and extensive documentation. But a lot of people when switching from other languages like Java, C, C++, JavaScript etcetera, find it a little difficult to follow along with the best practices that should be adopted to write clean code in Python. Clean code is easier to read and understand, debug, and elegant. So today we will be discussing all of them in detail, therefore you will get a better idea of them. So let’s get started!
It is always advised to incorporate readable comments into your code. This makes the program easy to comprehend. Even a complex program can be broken down into parts and be understood because of the comments. There are two types of comments in Python:
Single Line Comments: These types of comments span a single line of text. They begin with a hash symbol (#) and automatically terminate when the line ends.Multi-line Comments: They span multiple lines of text (two or more) and are ideally used when explaining a block of code. These type of comments start and end with triple quotes (”’). It is more like a text constant and can also be used to assign string to a variable. In a few cases this can cause errors therefore hash should be used for each line of comment if the comment has more than one line.
Single Line Comments: These types of comments span a single line of text. They begin with a hash symbol (#) and automatically terminate when the line ends.
Multi-line Comments: They span multiple lines of text (two or more) and are ideally used when explaining a block of code. These type of comments start and end with triple quotes (”’). It is more like a text constant and can also be used to assign string to a variable. In a few cases this can cause errors therefore hash should be used for each line of comment if the comment has more than one line.
To learn more about comments, must read: Comments in Python
Unlike other languages like C++, Java etc. Python relies on space or tab indentation rather than brace specified code block. Each statement in Python is preceded by a space, double space, or tab. You cannot use a tab at one place and a space on the other as the indentation needs to be consistent throughout the code. This tells Python that you are starting a new block of code. A few examples of Python indentation are provided below:
# an example of if-else with tab indentation
if (condition 1):
# executed when condition is True
else:
# executed when condition is False
# an example of for loop with nested if-else and double space indentation
for i in sequence:
if (condidition 1):
# execute outer if block code
if (condition 2):
# execute nested if code
else:
# execute outer else block code
To learn more about indentation, must read: Indentation in Python
Virtual environments in Python are a type of sandbox area for a project. In this environment, whatever libraries and packages you will install will be clearly isolated from the ones installed outside the environment, say the operating system or other virtual environments. You can have multiple virtual environments at a point in time, and it is recommended to use these environments every time you are working on a different or new project. This facilitates separating dependencies and helps to share code easily. Next time anyone wants to run your software, rather than making them install libraries one by one, you can send the requirements file (containing all installed packages and libraries for that specific project). This can be done using the freeze command as follows:
pip freeze > requirements.txt
This command lists all your installed packages and outputs those into the requirements.txt text file. Next time someone installs it, they can run the following command:
pip install -r requirements.txt
Which installs the dependencies recursively without manually typing them one by one to install.
To learn more about virtual environments, must read: Virtual Environments in Python
Python developers strictly follow the DRY principle, which states Don’t Repeat Yourself. This means if you want to accomplish a task multiple times, rather than writing redundant code. This not only means writing functions to carry out repetitive tasks but rather making modules. Modules are more like a code library, typically a file that contains code you want to implement in your Python program. The Python community is huge and a lot of developers have implemented modules that involve code that is frequently used. You can make your own module that performs a specific task! So rather than reinventing the wheel and writing the code from scratch, you can simply import the module and use its functionality. This is done by using the import keyword:
# importing regular expression package
import re
# using it in your code
regex = re.compile(r'pattern')
# importing tensorflow with an alias that makes
# the usage concise
import tensorflow as tf
To read more about modules, visit: Modules in Python
Python language follows the snake case when it comes to naming variables and functions. So a variable that is named FooBar in any other language that follows camel case naming convention, is named as foo_bar in Python. Python will not throw an error if you use camel cases or flatcase, but it is not desired. Along with variable names, function names in python also follow snake case naming convention.
There are a lot of unique ways to implement a specific task in Python. These are concise methods that help in shortening the code and make it look elegant. Let’s look at each of them one by one.
List Comprehensions: It is a sophisticated way to create lists in a single line. Rather than explicitly using assignment inside a loop, we can create a list within square brackets with the loop defined inside. To read more about list comprehensions, must read: List Comprehensions in Python.Swapping Variables: When swapping variables in python, rather than using temporary variables and other weird ways (adding or dividing variables) you can do it in a single line of code. Example, to swap two variables, a and b: a, b = b, a. This is Python’s way of swapping variables!Slicing: It is used to carve out a specific part of a list or a string. It is super useful when you need to extract a smaller list or string from a larger one and can be implemented using a colon as a separator in between the initial and the final variables. You can even leave the start or the end value. To read more about slicing, must read: Slicing in Python.
List Comprehensions: It is a sophisticated way to create lists in a single line. Rather than explicitly using assignment inside a loop, we can create a list within square brackets with the loop defined inside. To read more about list comprehensions, must read: List Comprehensions in Python.
Swapping Variables: When swapping variables in python, rather than using temporary variables and other weird ways (adding or dividing variables) you can do it in a single line of code. Example, to swap two variables, a and b: a, b = b, a. This is Python’s way of swapping variables!
Slicing: It is used to carve out a specific part of a list or a string. It is super useful when you need to extract a smaller list or string from a larger one and can be implemented using a colon as a separator in between the initial and the final variables. You can even leave the start or the end value. To read more about slicing, must read: Slicing in Python.
We have discussed most of the ways that you can adopt in your Python code to make it look elegant and crisp. These also help to debug your code easily and make it more readable.
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Top 10 Projects For Beginners To Practice HTML and CSS Skills
GET and POST requests using Python
Top 10 Angular Libraries For Web Developers
Working with csv files in Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Read JSON file using Python
|
[
{
"code": null,
"e": 24034,
"s": 24006,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 24716,
"s": 24034,
"text": "Python is one of the most loved programming languages today. Shockingly, Python has overtaken Java in the list of top programming languages and is now the most studied language! It is the second most used language after JavaScript and is slowly beating the competition to be on the top. It is used extensively across various domains like web development through popular frameworks like Django and Flask, web scraping, automation, system administration, DevOps, testing, network programming, data analysis, data science, machine learning, and artificial intelligence. In fact, the first language which comes to someone’s mind when talking about data-related technologies is Python! "
},
{
"code": null,
"e": 25262,
"s": 24716,
"text": "Along with being a heavily used language by beginners due to its ease of learning, it has huge community support and extensive documentation. But a lot of people when switching from other languages like Java, C, C++, JavaScript etcetera, find it a little difficult to follow along with the best practices that should be adopted to write clean code in Python. Clean code is easier to read and understand, debug, and elegant. So today we will be discussing all of them in detail, therefore you will get a better idea of them. So let’s get started!"
},
{
"code": null,
"e": 25514,
"s": 25262,
"text": "It is always advised to incorporate readable comments into your code. This makes the program easy to comprehend. Even a complex program can be broken down into parts and be understood because of the comments. There are two types of comments in Python:"
},
{
"code": null,
"e": 26069,
"s": 25514,
"text": "Single Line Comments: These types of comments span a single line of text. They begin with a hash symbol (#) and automatically terminate when the line ends.Multi-line Comments: They span multiple lines of text (two or more) and are ideally used when explaining a block of code. These type of comments start and end with triple quotes (”’). It is more like a text constant and can also be used to assign string to a variable. In a few cases this can cause errors therefore hash should be used for each line of comment if the comment has more than one line."
},
{
"code": null,
"e": 26225,
"s": 26069,
"text": "Single Line Comments: These types of comments span a single line of text. They begin with a hash symbol (#) and automatically terminate when the line ends."
},
{
"code": null,
"e": 26625,
"s": 26225,
"text": "Multi-line Comments: They span multiple lines of text (two or more) and are ideally used when explaining a block of code. These type of comments start and end with triple quotes (”’). It is more like a text constant and can also be used to assign string to a variable. In a few cases this can cause errors therefore hash should be used for each line of comment if the comment has more than one line."
},
{
"code": null,
"e": 26685,
"s": 26625,
"text": "To learn more about comments, must read: Comments in Python"
},
{
"code": null,
"e": 27121,
"s": 26685,
"text": "Unlike other languages like C++, Java etc. Python relies on space or tab indentation rather than brace specified code block. Each statement in Python is preceded by a space, double space, or tab. You cannot use a tab at one place and a space on the other as the indentation needs to be consistent throughout the code. This tells Python that you are starting a new block of code. A few examples of Python indentation are provided below:"
},
{
"code": null,
"e": 27267,
"s": 27121,
"text": "# an example of if-else with tab indentation\nif (condition 1):\n # executed when condition is True\nelse:\n # executed when condition is False"
},
{
"code": null,
"e": 27515,
"s": 27267,
"text": "# an example of for loop with nested if-else and double space indentation\nfor i in sequence:\n if (condidition 1):\n # execute outer if block code\n if (condition 2):\n # execute nested if code\n else:\n # execute outer else block code"
},
{
"code": null,
"e": 27581,
"s": 27515,
"text": "To learn more about indentation, must read: Indentation in Python"
},
{
"code": null,
"e": 28361,
"s": 27581,
"text": "Virtual environments in Python are a type of sandbox area for a project. In this environment, whatever libraries and packages you will install will be clearly isolated from the ones installed outside the environment, say the operating system or other virtual environments. You can have multiple virtual environments at a point in time, and it is recommended to use these environments every time you are working on a different or new project. This facilitates separating dependencies and helps to share code easily. Next time anyone wants to run your software, rather than making them install libraries one by one, you can send the requirements file (containing all installed packages and libraries for that specific project). This can be done using the freeze command as follows:"
},
{
"code": null,
"e": 28391,
"s": 28361,
"text": "pip freeze > requirements.txt"
},
{
"code": null,
"e": 28560,
"s": 28391,
"text": "This command lists all your installed packages and outputs those into the requirements.txt text file. Next time someone installs it, they can run the following command:"
},
{
"code": null,
"e": 28592,
"s": 28560,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 28688,
"s": 28592,
"text": "Which installs the dependencies recursively without manually typing them one by one to install."
},
{
"code": null,
"e": 28772,
"s": 28688,
"text": "To learn more about virtual environments, must read: Virtual Environments in Python"
},
{
"code": null,
"e": 29527,
"s": 28772,
"text": "Python developers strictly follow the DRY principle, which states Don’t Repeat Yourself. This means if you want to accomplish a task multiple times, rather than writing redundant code. This not only means writing functions to carry out repetitive tasks but rather making modules. Modules are more like a code library, typically a file that contains code you want to implement in your Python program. The Python community is huge and a lot of developers have implemented modules that involve code that is frequently used. You can make your own module that performs a specific task! So rather than reinventing the wheel and writing the code from scratch, you can simply import the module and use its functionality. This is done by using the import keyword:"
},
{
"code": null,
"e": 29725,
"s": 29527,
"text": "# importing regular expression package\nimport re\n\n# using it in your code\nregex = re.compile(r'pattern')\n\n# importing tensorflow with an alias that makes\n# the usage concise\nimport tensorflow as tf"
},
{
"code": null,
"e": 29778,
"s": 29725,
"text": "To read more about modules, visit: Modules in Python"
},
{
"code": null,
"e": 30181,
"s": 29778,
"text": "Python language follows the snake case when it comes to naming variables and functions. So a variable that is named FooBar in any other language that follows camel case naming convention, is named as foo_bar in Python. Python will not throw an error if you use camel cases or flatcase, but it is not desired. Along with variable names, function names in python also follow snake case naming convention."
},
{
"code": null,
"e": 30376,
"s": 30181,
"text": "There are a lot of unique ways to implement a specific task in Python. These are concise methods that help in shortening the code and make it look elegant. Let’s look at each of them one by one."
},
{
"code": null,
"e": 31313,
"s": 30376,
"text": "List Comprehensions: It is a sophisticated way to create lists in a single line. Rather than explicitly using assignment inside a loop, we can create a list within square brackets with the loop defined inside. To read more about list comprehensions, must read: List Comprehensions in Python.Swapping Variables: When swapping variables in python, rather than using temporary variables and other weird ways (adding or dividing variables) you can do it in a single line of code. Example, to swap two variables, a and b: a, b = b, a. This is Python’s way of swapping variables!Slicing: It is used to carve out a specific part of a list or a string. It is super useful when you need to extract a smaller list or string from a larger one and can be implemented using a colon as a separator in between the initial and the final variables. You can even leave the start or the end value. To read more about slicing, must read: Slicing in Python."
},
{
"code": null,
"e": 31605,
"s": 31313,
"text": "List Comprehensions: It is a sophisticated way to create lists in a single line. Rather than explicitly using assignment inside a loop, we can create a list within square brackets with the loop defined inside. To read more about list comprehensions, must read: List Comprehensions in Python."
},
{
"code": null,
"e": 31888,
"s": 31605,
"text": "Swapping Variables: When swapping variables in python, rather than using temporary variables and other weird ways (adding or dividing variables) you can do it in a single line of code. Example, to swap two variables, a and b: a, b = b, a. This is Python’s way of swapping variables!"
},
{
"code": null,
"e": 32252,
"s": 31888,
"text": "Slicing: It is used to carve out a specific part of a list or a string. It is super useful when you need to extract a smaller list or string from a larger one and can be implemented using a colon as a separator in between the initial and the final variables. You can even leave the start or the end value. To read more about slicing, must read: Slicing in Python."
},
{
"code": null,
"e": 32431,
"s": 32252,
"text": "We have discussed most of the ways that you can adopt in your Python code to make it look elegant and crisp. These also help to debug your code easily and make it more readable. "
},
{
"code": null,
"e": 32437,
"s": 32431,
"text": "GBlog"
},
{
"code": null,
"e": 32444,
"s": 32437,
"text": "Python"
},
{
"code": null,
"e": 32542,
"s": 32444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32551,
"s": 32542,
"text": "Comments"
},
{
"code": null,
"e": 32564,
"s": 32551,
"text": "Old Comments"
},
{
"code": null,
"e": 32589,
"s": 32564,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32651,
"s": 32589,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32686,
"s": 32651,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 32730,
"s": 32686,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 32763,
"s": 32730,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 32813,
"s": 32763,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 32835,
"s": 32813,
"text": "Python map() function"
},
{
"code": null,
"e": 32879,
"s": 32835,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 32897,
"s": 32879,
"text": "Python Dictionary"
}
] |
Linux Admin - Quota Management
|
CentOS disk quotas can be enabled both; alerting the system administrator and denying further disk-storage-access to a user before disk capacity is exceeded. When a disk is full, depending on what resides on the disk, an entire system can come to a screeching halt until recovered.
Enabling Quota Management in CentOS Linux is basically a 4 step process −
Step 1 − Enable quota management for groups and users in /etc/fstab.
Step 1 − Enable quota management for groups and users in /etc/fstab.
Step 2 − Remount the filesystem.
Step 2 − Remount the filesystem.
Step 3 − Create Quota database and generate disk usage table.
Step 3 − Create Quota database and generate disk usage table.
Step 4 − Assign quota policies.
Step 4 − Assign quota policies.
First, we want to backup our /etc/fstab filen −
[root@centosLocal centos]# cp -r /etc/fstab ./
We now have a copy of our known working /etc/fstab in the current working directory.
#
# /etc/fstab
# Created by anaconda on Sat Dec 17 02:44:51 2016
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/cl-root / xfs defaults 0 0
UUID = 4b9a40bc-9480-4 /boot xfs defaults 0 0
/dev/mapper/cl-home /home xfs defaults,usrquota,grpquota 0 0
/dev/mapper/cl-swap swap swap defaults 0 0
We made the following changes in the options section of /etc/fstab for the volume or Label to where quotas are to be applied for users and groups.
usrquota
grpquota
As you can see, we are using the xfs filesystem. When using xfs there are extra manual steps involved. /home is on the same disk as /. Further investigation shows / is set for noquota, which is a kernel level mounting option. We must re-configure our kernel boot options.
root@localhost rdc]# mount | grep ' / '
/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
[root@localhost rdc]#
This step is only necessary under two conditions −
When the disk/partition we are enabling quotas on, is using the xfs file system
When the kernel is passing noquota parameter to /etc/fstab at boot time
Step 1 − Make a backup of /etc/default/grub.
cp /etc/default/grub ~/
Step 2 − Modify /etc/default/grub.
Here is the default file.
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet"
GRUB_DISABLE_RECOVERY="true"
We want to modify the following line −
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet"
to
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv
=cl/swap rhgb quiet rootflags=usrquota,grpquota"
Note − It is important we copy these changes verbatim. After we reconfigure grub.cfg, our system will fail to boot if any errors were made in the configuration. Please, try this part of the tutorial on a non-production system.
Step 3 − Backup your working grub.cfg
cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak
Make a new grub.cfg
[root@localhost rdc]# grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.10.0-514.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-514.el7.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-dbba7fa47f73457b96628ba8f3959bfd
Found initrd image: /boot/initramfs-0-rescuedbba7fa47f73457b96628ba8f3959bfd.img
done
[root@localhost rdc]#
Reboot
[root@localhost rdc]#reboot
If all modifications were precise, we should not have the availability to add quotas to the xfs file system.
[rdc@localhost ~]$ mount | grep ' / '
/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,usrquota,grpquota)
[rdc@localhost ~]$
We have passed the usrquota and grpquota parameters via grub.
Now, again edit /etc/fstab to include / since /homeon the same physical disk.
/dev/mapper/cl-root/xfs
defaults,usrquota,grpquota 0 0
Now let's enable the quota databases.
[root@localhost rdc]# quotacheck -acfvugM
Make sure Quotas are enabled.
[root@localhost rdc]# quotaon -ap
group quota on / (/dev/mapper/cl-root) is on
user quota on / (/dev/mapper/cl-root) is on
group quota on /home (/dev/mapper/cl-home) is on
user quota on /home (/dev/mapper/cl-home) is on
[root@localhost rdc]#
If the partition or disk is separate from the actively booted partition, we can remount without rebooting. If the quota was configured on a disk/partition booted in the root directory /, we may need to reboot the operating system. Forcing the remount and applying changes, the need to remount the filesystem may vary.
[rdc@localhost ~]$ df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/cl-root 22447404 4081860 18365544 19% /
devtmpfs 903448 0 903448 0% /dev
tmpfs 919308 100 919208 1% /dev/shm
tmpfs 919308 9180 910128 1% /run
tmpfs 919308 0 919308 0% /sys/fs/cgroup
/dev/sda2 1268736 176612 1092124 14% /boot
/dev/mapper/cl-var 4872192 158024 4714168 4% /var
/dev/mapper/cl-home 18475008 37284 18437724 1% /home
tmpfs 183864 8 183856 1% /run/user/1000
[rdc@localhost ~]$
As we can see, LVM volumes are in use. So it's simple to just reboot. This will remount /home and load the /etc/fstab configuration changes into active configuration.
CentOS is now capable of working with disk quotas on /home. To enable full quota supprt, we must run the quotacheck command.
quotacheck will create two files −
aquota.user
aquota.group
These are used to store quota information for the quota enabled disks/partitions.
Following are the common quotacheck switches.
For this, we will use the edquota command, followed by the username −
[root@localhost rdc]# edquota centos
Disk quotas for user centos (uid 1000):
Filesystem blocks soft hard inodes soft hard
/dev/mapper/cl-root 12 0 0 13 0 0
/dev/mapper/cl-home 4084 0 0 140 0 0
Let's look at each column.
Filesystem − It is the filesystem quotas for the user applied to
Filesystem − It is the filesystem quotas for the user applied to
blocks − How many blocks the user is currently using on each filesystem
blocks − How many blocks the user is currently using on each filesystem
soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period
soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period
hard − Set blocks for a hard limit. Hard limit is total allowable quota
hard − Set blocks for a hard limit. Hard limit is total allowable quota
inodes − How many inodes the user is currently using
inodes − How many inodes the user is currently using
soft − Soft inode limit
soft − Soft inode limit
hard − Hard inode limit
hard − Hard inode limit
To check our current quota as a user −
[centos@localhost ~]$ quota
Disk quotas for user centos (uid 1000):
Filesystem blocks quota limit grace files quota limit grace
/dev/mapper/cl-home 6052604 56123456 61234568 475 0 0 [centos@localhost ~]$
Following is an error given to a user when the hard quota limit has exceeded.
[centos@localhost Downloads]$ cp CentOS-7-x86_64-LiveKDE-1611.iso.part ../Desktop/
cp: cannot create regular file ‘../Desktop/CentOS-7-x86_64-LiveKDE-
1611.iso.part’: Disk quota exceeded
[centos@localhost Downloads]$
As we can see, we are closely within this user's disk quota. Let's set a soft limit warning. This way, the user will have advance notice before quota limits expire. From experience, you will get end-user complaints when they come into work and need to spend 45 minutes clearing files to actually get to work.
As an Administrator, we can check quota usage with the repquota command.
[root@localhost Downloads]# repquota /home
Block limits File limits
User used soft hard grace used soft hard grace
----------------------------------------------------------------------------------------
root -- 0 0 0 3 0 0
centos -+ 6189824 56123456 61234568 541 520 540 6days
[root@localhost Downloads]#
As we can see, the user centos has exceeded their hard block quota and can no longer use any more disk space on /home.
-+denotes a hard quota has been exceeded on the filesystem.
When planning quotas, it is necessary to do a little math. What an Administrator needs to know is:How many users are on the system? How much free space to allocate amongst users/groups? How many bytes make up a block on the file system?
Define quotas in terms of blocks as related to free disk-space.It is recommended to leave a "safe" buffer of free-space on the file system that will remain in worst case scenario: all quotas are simultaneously exceeded. This is especially on a partition that is used by the system for writing logs.
57 Lectures
7.5 hours
Mamta Tripathi
25 Lectures
3 hours
Lets Kode It
14 Lectures
1.5 hours
Abhilash Nelson
58 Lectures
2.5 hours
Frahaan Hussain
129 Lectures
23 hours
Eduonix Learning Solutions
23 Lectures
5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2539,
"s": 2257,
"text": "CentOS disk quotas can be enabled both; alerting the system administrator and denying further disk-storage-access to a user before disk capacity is exceeded. When a disk is full, depending on what resides on the disk, an entire system can come to a screeching halt until recovered."
},
{
"code": null,
"e": 2613,
"s": 2539,
"text": "Enabling Quota Management in CentOS Linux is basically a 4 step process −"
},
{
"code": null,
"e": 2682,
"s": 2613,
"text": "Step 1 − Enable quota management for groups and users in /etc/fstab."
},
{
"code": null,
"e": 2751,
"s": 2682,
"text": "Step 1 − Enable quota management for groups and users in /etc/fstab."
},
{
"code": null,
"e": 2784,
"s": 2751,
"text": "Step 2 − Remount the filesystem."
},
{
"code": null,
"e": 2817,
"s": 2784,
"text": "Step 2 − Remount the filesystem."
},
{
"code": null,
"e": 2879,
"s": 2817,
"text": "Step 3 − Create Quota database and generate disk usage table."
},
{
"code": null,
"e": 2941,
"s": 2879,
"text": "Step 3 − Create Quota database and generate disk usage table."
},
{
"code": null,
"e": 2973,
"s": 2941,
"text": "Step 4 − Assign quota policies."
},
{
"code": null,
"e": 3005,
"s": 2973,
"text": "Step 4 − Assign quota policies."
},
{
"code": null,
"e": 3053,
"s": 3005,
"text": "First, we want to backup our /etc/fstab filen −"
},
{
"code": null,
"e": 3101,
"s": 3053,
"text": "[root@centosLocal centos]# cp -r /etc/fstab ./\n"
},
{
"code": null,
"e": 3186,
"s": 3101,
"text": "We now have a copy of our known working /etc/fstab in the current working directory."
},
{
"code": null,
"e": 3729,
"s": 3186,
"text": "# \n# /etc/fstab \n# Created by anaconda on Sat Dec 17 02:44:51 2016 \n# \n# Accessible filesystems, by reference, are maintained under '/dev/disk' \n# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info\n# \n/dev/mapper/cl-root / xfs defaults 0 0\nUUID = 4b9a40bc-9480-4 /boot xfs defaults 0 0\n\n/dev/mapper/cl-home /home xfs defaults,usrquota,grpquota 0 0\n\n/dev/mapper/cl-swap swap swap defaults 0 0\n"
},
{
"code": null,
"e": 3876,
"s": 3729,
"text": "We made the following changes in the options section of /etc/fstab for the volume or Label to where quotas are to be applied for users and groups."
},
{
"code": null,
"e": 3885,
"s": 3876,
"text": "usrquota"
},
{
"code": null,
"e": 3894,
"s": 3885,
"text": "grpquota"
},
{
"code": null,
"e": 4166,
"s": 3894,
"text": "As you can see, we are using the xfs filesystem. When using xfs there are extra manual steps involved. /home is on the same disk as /. Further investigation shows / is set for noquota, which is a kernel level mounting option. We must re-configure our kernel boot options."
},
{
"code": null,
"e": 4310,
"s": 4166,
"text": "root@localhost rdc]# mount | grep ' / ' \n/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)\n\n[root@localhost rdc]#\n"
},
{
"code": null,
"e": 4361,
"s": 4310,
"text": "This step is only necessary under two conditions −"
},
{
"code": null,
"e": 4441,
"s": 4361,
"text": "When the disk/partition we are enabling quotas on, is using the xfs file system"
},
{
"code": null,
"e": 4513,
"s": 4441,
"text": "When the kernel is passing noquota parameter to /etc/fstab at boot time"
},
{
"code": null,
"e": 4558,
"s": 4513,
"text": "Step 1 − Make a backup of /etc/default/grub."
},
{
"code": null,
"e": 4583,
"s": 4558,
"text": "cp /etc/default/grub ~/\n"
},
{
"code": null,
"e": 4618,
"s": 4583,
"text": "Step 2 − Modify /etc/default/grub."
},
{
"code": null,
"e": 4644,
"s": 4618,
"text": "Here is the default file."
},
{
"code": null,
"e": 4922,
"s": 4644,
"text": "GRUB_TIMEOUT=5 \nGRUB_DISTRIBUTOR=\"$(sed 's, release .*$,,g' /etc/system-release)\" \nGRUB_DEFAULT=saved \nGRUB_DISABLE_SUBMENU=true \nGRUB_TERMINAL_OUTPUT=\"console\" \nGRUB_CMDLINE_LINUX=\"crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet\" \nGRUB_DISABLE_RECOVERY=\"true\"\n"
},
{
"code": null,
"e": 4961,
"s": 4922,
"text": "We want to modify the following line −"
},
{
"code": null,
"e": 5048,
"s": 4961,
"text": "GRUB_CMDLINE_LINUX=\"crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet\" \n"
},
{
"code": null,
"e": 5051,
"s": 5048,
"text": "to"
},
{
"code": null,
"e": 5167,
"s": 5051,
"text": "GRUB_CMDLINE_LINUX=\"crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv \n=cl/swap rhgb quiet rootflags=usrquota,grpquota\"\n"
},
{
"code": null,
"e": 5394,
"s": 5167,
"text": "Note − It is important we copy these changes verbatim. After we reconfigure grub.cfg, our system will fail to boot if any errors were made in the configuration. Please, try this part of the tutorial on a non-production system."
},
{
"code": null,
"e": 5432,
"s": 5394,
"text": "Step 3 − Backup your working grub.cfg"
},
{
"code": null,
"e": 5482,
"s": 5432,
"text": "cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak\n"
},
{
"code": null,
"e": 5502,
"s": 5482,
"text": "Make a new grub.cfg"
},
{
"code": null,
"e": 5910,
"s": 5502,
"text": "[root@localhost rdc]# grub2-mkconfig -o /boot/grub2/grub.cfg \nGenerating grub configuration file ... \nFound linux image: /boot/vmlinuz-3.10.0-514.el7.x86_64 \nFound initrd image: /boot/initramfs-3.10.0-514.el7.x86_64.img \nFound linux image: /boot/vmlinuz-0-rescue-dbba7fa47f73457b96628ba8f3959bfd \nFound initrd image: /boot/initramfs-0-rescuedbba7fa47f73457b96628ba8f3959bfd.img \ndone\n\n[root@localhost rdc]#\n"
},
{
"code": null,
"e": 5917,
"s": 5910,
"text": "Reboot"
},
{
"code": null,
"e": 5946,
"s": 5917,
"text": "[root@localhost rdc]#reboot\n"
},
{
"code": null,
"e": 6055,
"s": 5946,
"text": "If all modifications were precise, we should not have the availability to add quotas to the xfs file system."
},
{
"code": null,
"e": 6205,
"s": 6055,
"text": "[rdc@localhost ~]$ mount | grep ' / ' \n/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,usrquota,grpquota)\n \n[rdc@localhost ~]$\n"
},
{
"code": null,
"e": 6267,
"s": 6205,
"text": "We have passed the usrquota and grpquota parameters via grub."
},
{
"code": null,
"e": 6345,
"s": 6267,
"text": "Now, again edit /etc/fstab to include / since /homeon the same physical disk."
},
{
"code": null,
"e": 6408,
"s": 6345,
"text": "/dev/mapper/cl-root/xfs\ndefaults,usrquota,grpquota 0 0\n"
},
{
"code": null,
"e": 6446,
"s": 6408,
"text": "Now let's enable the quota databases."
},
{
"code": null,
"e": 6489,
"s": 6446,
"text": "[root@localhost rdc]# quotacheck -acfvugM\n"
},
{
"code": null,
"e": 6519,
"s": 6489,
"text": "Make sure Quotas are enabled."
},
{
"code": null,
"e": 6767,
"s": 6519,
"text": "[root@localhost rdc]# quotaon -ap \ngroup quota on / (/dev/mapper/cl-root) is on \nuser quota on / (/dev/mapper/cl-root) is on \ngroup quota on /home (/dev/mapper/cl-home) is on \nuser quota on /home (/dev/mapper/cl-home) is on \n[root@localhost rdc]#\n"
},
{
"code": null,
"e": 7085,
"s": 6767,
"text": "If the partition or disk is separate from the actively booted partition, we can remount without rebooting. If the quota was configured on a disk/partition booted in the root directory /, we may need to reboot the operating system. Forcing the remount and applying changes, the need to remount the filesystem may vary."
},
{
"code": null,
"e": 7955,
"s": 7085,
"text": "[rdc@localhost ~]$ df \nFilesystem 1K-blocks Used Available Use% Mounted on\n/dev/mapper/cl-root 22447404 4081860 18365544 19% /\ndevtmpfs 903448 0 903448 0% /dev\ntmpfs 919308 100 919208 1% /dev/shm\ntmpfs 919308 9180 910128 1% /run\ntmpfs 919308 0 919308 0% /sys/fs/cgroup\n/dev/sda2 1268736 176612 1092124 14% /boot\n/dev/mapper/cl-var 4872192 158024 4714168 4% /var\n/dev/mapper/cl-home 18475008 37284 18437724 1% /home\ntmpfs 183864 8 183856 1% /run/user/1000\n\n[rdc@localhost ~]$\n"
},
{
"code": null,
"e": 8122,
"s": 7955,
"text": "As we can see, LVM volumes are in use. So it's simple to just reboot. This will remount /home and load the /etc/fstab configuration changes into active configuration."
},
{
"code": null,
"e": 8247,
"s": 8122,
"text": "CentOS is now capable of working with disk quotas on /home. To enable full quota supprt, we must run the quotacheck command."
},
{
"code": null,
"e": 8282,
"s": 8247,
"text": "quotacheck will create two files −"
},
{
"code": null,
"e": 8294,
"s": 8282,
"text": "aquota.user"
},
{
"code": null,
"e": 8307,
"s": 8294,
"text": "aquota.group"
},
{
"code": null,
"e": 8389,
"s": 8307,
"text": "These are used to store quota information for the quota enabled disks/partitions."
},
{
"code": null,
"e": 8435,
"s": 8389,
"text": "Following are the common quotacheck switches."
},
{
"code": null,
"e": 8505,
"s": 8435,
"text": "For this, we will use the edquota command, followed by the username −"
},
{
"code": null,
"e": 8850,
"s": 8505,
"text": "[root@localhost rdc]# edquota centos\n\nDisk quotas for user centos (uid 1000): \nFilesystem blocks soft hard inodes soft hard \n/dev/mapper/cl-root 12 0 0 13 0 0 \n/dev/mapper/cl-home 4084 0 0 140 0 0\n"
},
{
"code": null,
"e": 8877,
"s": 8850,
"text": "Let's look at each column."
},
{
"code": null,
"e": 8942,
"s": 8877,
"text": "Filesystem − It is the filesystem quotas for the user applied to"
},
{
"code": null,
"e": 9007,
"s": 8942,
"text": "Filesystem − It is the filesystem quotas for the user applied to"
},
{
"code": null,
"e": 9079,
"s": 9007,
"text": "blocks − How many blocks the user is currently using on each filesystem"
},
{
"code": null,
"e": 9151,
"s": 9079,
"text": "blocks − How many blocks the user is currently using on each filesystem"
},
{
"code": null,
"e": 9253,
"s": 9151,
"text": "soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period"
},
{
"code": null,
"e": 9355,
"s": 9253,
"text": "soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period"
},
{
"code": null,
"e": 9427,
"s": 9355,
"text": "hard − Set blocks for a hard limit. Hard limit is total allowable quota"
},
{
"code": null,
"e": 9499,
"s": 9427,
"text": "hard − Set blocks for a hard limit. Hard limit is total allowable quota"
},
{
"code": null,
"e": 9552,
"s": 9499,
"text": "inodes − How many inodes the user is currently using"
},
{
"code": null,
"e": 9605,
"s": 9552,
"text": "inodes − How many inodes the user is currently using"
},
{
"code": null,
"e": 9629,
"s": 9605,
"text": "soft − Soft inode limit"
},
{
"code": null,
"e": 9653,
"s": 9629,
"text": "soft − Soft inode limit"
},
{
"code": null,
"e": 9678,
"s": 9653,
"text": "hard − Hard inode limit"
},
{
"code": null,
"e": 9703,
"s": 9678,
"text": "hard − Hard inode limit"
},
{
"code": null,
"e": 9742,
"s": 9703,
"text": "To check our current quota as a user −"
},
{
"code": null,
"e": 10011,
"s": 9742,
"text": "[centos@localhost ~]$ quota \nDisk quotas for user centos (uid 1000): \nFilesystem blocks quota limit grace files quota limit grace \n/dev/mapper/cl-home 6052604 56123456 61234568 475 0 0 [centos@localhost ~]$\n"
},
{
"code": null,
"e": 10089,
"s": 10011,
"text": "Following is an error given to a user when the hard quota limit has exceeded."
},
{
"code": null,
"e": 10309,
"s": 10089,
"text": "[centos@localhost Downloads]$ cp CentOS-7-x86_64-LiveKDE-1611.iso.part ../Desktop/\n\ncp: cannot create regular file ‘../Desktop/CentOS-7-x86_64-LiveKDE-\n1611.iso.part’: Disk quota exceeded\n\n[centos@localhost Downloads]$\n"
},
{
"code": null,
"e": 10618,
"s": 10309,
"text": "As we can see, we are closely within this user's disk quota. Let's set a soft limit warning. This way, the user will have advance notice before quota limits expire. From experience, you will get end-user complaints when they come into work and need to spend 45 minutes clearing files to actually get to work."
},
{
"code": null,
"e": 10691,
"s": 10618,
"text": "As an Administrator, we can check quota usage with the repquota command."
},
{
"code": null,
"e": 11195,
"s": 10691,
"text": "[root@localhost Downloads]# repquota /home \n Block limits File limits \nUser used soft hard grace used soft hard grace \n----------------------------------------------------------------------------------------\nroot -- 0 0 0 3 0 0 \ncentos -+ 6189824 56123456 61234568 541 520 540 6days \n\n[root@localhost Downloads]#\n"
},
{
"code": null,
"e": 11314,
"s": 11195,
"text": "As we can see, the user centos has exceeded their hard block quota and can no longer use any more disk space on /home."
},
{
"code": null,
"e": 11374,
"s": 11314,
"text": "-+denotes a hard quota has been exceeded on the filesystem."
},
{
"code": null,
"e": 11611,
"s": 11374,
"text": "When planning quotas, it is necessary to do a little math. What an Administrator needs to know is:How many users are on the system? How much free space to allocate amongst users/groups? How many bytes make up a block on the file system?"
},
{
"code": null,
"e": 11910,
"s": 11611,
"text": "Define quotas in terms of blocks as related to free disk-space.It is recommended to leave a \"safe\" buffer of free-space on the file system that will remain in worst case scenario: all quotas are simultaneously exceeded. This is especially on a partition that is used by the system for writing logs."
},
{
"code": null,
"e": 11945,
"s": 11910,
"text": "\n 57 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 11961,
"s": 11945,
"text": " Mamta Tripathi"
},
{
"code": null,
"e": 11994,
"s": 11961,
"text": "\n 25 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 12008,
"s": 11994,
"text": " Lets Kode It"
},
{
"code": null,
"e": 12043,
"s": 12008,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12060,
"s": 12043,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12095,
"s": 12060,
"text": "\n 58 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12112,
"s": 12095,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12147,
"s": 12112,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12175,
"s": 12147,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12208,
"s": 12175,
"text": "\n 23 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 12248,
"s": 12208,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 12255,
"s": 12248,
"text": " Print"
},
{
"code": null,
"e": 12266,
"s": 12255,
"text": " Add Notes"
}
] |
Remove an element from a Queue in Java
|
To remove an element from a Queue, use the remove() method.
First, set a Queue and insert some elements −
Queue<String> q = new LinkedList<String>();
q.offer("abc");
q.offer("def");
q.offer("ghi");
q.offer("jkl");
q.offer("mno");
q.offer("pqr");
q.offer("stu");
q.offer("vwx");
Remove the first element −
System.out.println("Queue head = " + q.element());
System.out.println("Removing element from queue = " + q.remove());
The following is an example −
Live Demo
import java.util.LinkedList;
import java.util.Queue;
public class Demo {
public static void main(String[] args) {
Queue<String> q = new LinkedList<String>();
q.offer("abc");
q.offer("def");
q.offer("ghi");
q.offer("jkl");
q.offer("mno");
q.offer("pqr");
q.offer("stu");
q.offer("vwx");
System.out.println("Queue head = " + q.element());
System.out.println("Removing element from queue = " + q.remove());
System.out.println("\nRemaining Queue elements...");
Object ob;
while ((ob = q.poll()) != null) {
System.out.println(ob);
}
}
}
Queue head = abc
Removing element from queue = abc
Queue head now = abc
Remaining Queue elements...
def
ghi
jkl
mno
pqr
stu
vwx
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": "To remove an element from a Queue, use the remove() method."
},
{
"code": null,
"e": 1168,
"s": 1122,
"text": "First, set a Queue and insert some elements −"
},
{
"code": null,
"e": 1340,
"s": 1168,
"text": "Queue<String> q = new LinkedList<String>();\nq.offer(\"abc\");\nq.offer(\"def\");\nq.offer(\"ghi\");\nq.offer(\"jkl\");\nq.offer(\"mno\");\nq.offer(\"pqr\");\nq.offer(\"stu\");\nq.offer(\"vwx\");"
},
{
"code": null,
"e": 1367,
"s": 1340,
"text": "Remove the first element −"
},
{
"code": null,
"e": 1485,
"s": 1367,
"text": "System.out.println(\"Queue head = \" + q.element());\nSystem.out.println(\"Removing element from queue = \" + q.remove());"
},
{
"code": null,
"e": 1515,
"s": 1485,
"text": "The following is an example −"
},
{
"code": null,
"e": 1526,
"s": 1515,
"text": " Live Demo"
},
{
"code": null,
"e": 2163,
"s": 1526,
"text": "import java.util.LinkedList;\nimport java.util.Queue;\npublic class Demo {\n public static void main(String[] args) {\n Queue<String> q = new LinkedList<String>();\n q.offer(\"abc\");\n q.offer(\"def\");\n q.offer(\"ghi\");\n q.offer(\"jkl\");\n q.offer(\"mno\");\n q.offer(\"pqr\");\n q.offer(\"stu\");\n q.offer(\"vwx\");\n System.out.println(\"Queue head = \" + q.element());\n System.out.println(\"Removing element from queue = \" + q.remove());\n System.out.println(\"\\nRemaining Queue elements...\");\n Object ob;\n while ((ob = q.poll()) != null) {\n System.out.println(ob);\n }\n }\n}"
},
{
"code": null,
"e": 2291,
"s": 2163,
"text": "Queue head = abc\nRemoving element from queue = abc\nQueue head now = abc\nRemaining Queue elements...\ndef\nghi\njkl\nmno\npqr\nstu\nvwx"
}
] |
Multi-Class Classification in Text using R | by Shubhanshu Gupta | Towards Data Science
|
This blog is in continuation to my NLP blog series. In the previous blogs, I discussed data pre-processing steps in R and recognizing emotions present in ted talks. In this blog, I am going to predict the ratings of the ted talks given by viewers. This would require a multi-class classification and quite a bit of data cleaning and preprocessing. We will discuss each step in detail below.
So, let’s dive in!
The ratings column in the ted talk dataset looks like Figure 1.
The screenshot of the column above, Figure 1signifies how many people have rated a particular talk to be “Inspiring”, “Beautiful”, “Ingenious”, “Persuasive”, etc. The count key in the JSON signifies the value of the rating given to the talk. So for example, the talk has been rated “Inspiring” by 385 people and just 2 people have rated the talk to be “Funny”. Our objective, here, is to get the rating with the highest count for each talk.
One of the primary concern is to parse the ratings column. I have used the gsub function for replacing the single quote with double quotes. I found the details and explanation about gsub here.
library(jsonlite)formatted_ted_ratings <- gsub(“‘“,’”’,ted_talks$ratings)
The next step was to parse the JSON to get a list of id, rating name and rating count. The jsonlite library in R, provides functions to stream, validate and prettify JSON data. The fromJSON function is used to de-serialize JSON objects into R objects. Finally, purrr::map function, applies a function (fromJSON in our case) to each element in the list. The documentation and implementation can be read here.
ted_ratings <- purrr::map(formatted_ted_ratings, jsonlite::fromJSON)
The code block above gives us a neat list of parsed rating column. It looks like Figure 2 .
In the next step, I am going to make a new column “highest_rating” in which I will store the rating with highest count for every talk. Post that, I will convert the column into factor which will effectively give us 13 unique factors (ratings) to deal with. I hope, by this point you must have got a hint that this highest_rating column with 13 factor variables will be used for multi-class classification. In the sense, a binary classification problem has two classes to classify a data point, e.g. True and False. Whereas, in this problem we have to deal with the classification of a data point into one of the 13 classes and hence, this is a multi-class classification problem.
for (i in (1:length(ted_ratings))) { ted_ratings_df <- ted_ratings[[i]] highest_rating_count <- ted_ratings_df[which(ted_ratings_df$count == max(ted_ratings_df$count)), ] ted_talks$highest_rating[i] <- highest_rating_count$name}ted_talks$highest_rating = as.factor(ted_talks$highest_rating)
With the above step, our dataset preparation is now complete.
We will now split our dataset into training and test. I have divided my dataset in 60:40 ratio.
trainObs <- sample(nrow(ted_talks), .6 * nrow(ted_talks), replace = FALSE)testObs <- sample(nrow(ted_talks), .4 * nrow(ted_talks), replace = FALSE)train_dat <- ted_talks[trainObs,]test_dat <- ted_talks[testObs,]
I will now apply all the pre-processing steps to my training and test data (separately). Somehow, I was in dual mindset: whether to split the DTM into train and test or split the dataset and then prepare their DTM individually. Somehow, I chose the latter option. You can try with the former option and let me know if it works out fine for you.
I also took care of sparsity, something which I discussed in good detail in my blog. I also renamed my target variable as “y” instead of highest_rating for better intuitiveness.
train_corpus <- VCorpus(VectorSource(train_dat$transcript))##Removing Punctuationtrain_corpus <- tm_map(train_corpus, content_transformer(removePunctuation))##Removing numberstrain_corpus <- tm_map(train_corpus, removeNumbers)##Converting to lower casetrain_corpus <- tm_map(train_corpus, content_transformer(tolower))##Removing stop wordstrain_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords(“english”))##Stemmingtrain_corpus <- tm_map(train_corpus, stemDocument)##Whitespacetrain_corpus <- tm_map(train_corpus, stripWhitespace)# Create Document Term Matrixdtm_train <- DocumentTermMatrix(train_corpus)train_corpus <- removeSparseTerms(dtm_train, 0.4)dtm_train_matrix <- as.matrix(train_corpus)dtm_train_matrix <- cbind(dtm_train_matrix, train_dat$highest_rating)colnames(dtm_train_matrix)[ncol(dtm_train_matrix)] <- “y”training_set_ted_talk <- as.data.frame(dtm_train_matrix)training_set_ted_talk$y <- as.factor(training_set_ted_talk$y)
Now that we have our training dataset ready, we can train our model. I am using caret package and svmLinear3 method in caret. svmLinear3 provides L2 regularization in SVM with Linear Kernel. Agreed, that’s a lot of technical jargon which I am purposely not explaining here because that’s for another blog altogether. Meanwhile, I am going to leave some links for you to understand L2 regularization, and SVM with Linear Kernel.
library(caret)review_ted_model <- train(y ~., data = training_set_ted_talk, method = ‘svmLinear3’)Preparing our test data. It’s the same repetitive procedure.test_corpus <- VCorpus(VectorSource(test_dat$transcript))##Removing Punctuationtest_corpus <- tm_map(test_corpus, content_transformer(removePunctuation))##Removing numberstest_corpus <- tm_map(test_corpus, removeNumbers)##Converting to lower casetest_corpus <- tm_map(test_corpus, content_transformer(tolower))##Removing stop wordstest_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords(“english”))##Stemmingtest_corpus <- tm_map(test_corpus, stemDocument)##Whitespacetest_corpus <- tm_map(test_corpus, stripWhitespace)# Create Document Term Matrixdtm_test <- DocumentTermMatrix(test_corpus)test_corpus <- removeSparseTerms(dtm_test, 0.4)dtm_test_matrix <- as.matrix(test_corpus)
I will now check the accuracy/performance of our model on test data.
#Build the prediction model_ted_talk_result <- predict(review_ted_model, newdata = dtm_test_matrix)check_accuracy <- as.data.frame(cbind(prediction = model_ted_talk_result, rating = test_dat$highest_rating))library(dplyr)check_accuracy <- check_accuracy %>% mutate(prediction = as.integer(prediction) — 1)check_accuracy$accuracy <- if_else(check_accuracy$prediction == check_accuracy$rating, 1, 0)round(prop.table(table(check_accuracy$accuracy)), 3)library(performanceEstimation)classificationMetrics(as.integer(test_dat$highest_rating), model_ted_talk_result)most_common_misclassified_ratings = check_accuracy %>% filter(check_accuracy$accuracy == 0) %>% group_by(rating) %>% summarise(Count = n()) %>% arrange(desc(Count)) %>% head(3)##Most commong missclassified ratinglevels(train_dat$highest_rating)[most_common_misclassified_ratings$rating]
The model metrics are:
The top 3 most commonly misclassified ratings are: “Inspiring”, “Informative”, “Fascinating”. You can read more about micro and macro F1 scores from here and here.
In this article, we have discussed multi-class classification of text. It was pretty challenging data problem for me to solve, primarily because:
I had uptil now dealt only with binary classification problems
The data manipulation steps leading to 13 classes for every individual rating column. Single quotes had ruined what looked like a perfect JSON column. Without any intuition for the same, it took a lot of hair pulling to figure out that single quotes were causing the problem. I eventually managed to parse it using gsub.
Finally, the model scores above are heavily reliant on the method we use in the train method. I used SVM with Linear Kernel and L2 regularization which in itself was computationally heavy. There are other methods which you can try, but computational resources could be an issue. Please do let me know what other method(s) you used and the scores (accuracy and F1) that you get.
That’s all for now. I will discuss a new task related to NLP in my next blog. I have written other posts related to software engineering as well. You might want to check them out here.
|
[
{
"code": null,
"e": 563,
"s": 172,
"text": "This blog is in continuation to my NLP blog series. In the previous blogs, I discussed data pre-processing steps in R and recognizing emotions present in ted talks. In this blog, I am going to predict the ratings of the ted talks given by viewers. This would require a multi-class classification and quite a bit of data cleaning and preprocessing. We will discuss each step in detail below."
},
{
"code": null,
"e": 582,
"s": 563,
"text": "So, let’s dive in!"
},
{
"code": null,
"e": 646,
"s": 582,
"text": "The ratings column in the ted talk dataset looks like Figure 1."
},
{
"code": null,
"e": 1087,
"s": 646,
"text": "The screenshot of the column above, Figure 1signifies how many people have rated a particular talk to be “Inspiring”, “Beautiful”, “Ingenious”, “Persuasive”, etc. The count key in the JSON signifies the value of the rating given to the talk. So for example, the talk has been rated “Inspiring” by 385 people and just 2 people have rated the talk to be “Funny”. Our objective, here, is to get the rating with the highest count for each talk."
},
{
"code": null,
"e": 1280,
"s": 1087,
"text": "One of the primary concern is to parse the ratings column. I have used the gsub function for replacing the single quote with double quotes. I found the details and explanation about gsub here."
},
{
"code": null,
"e": 1354,
"s": 1280,
"text": "library(jsonlite)formatted_ted_ratings <- gsub(“‘“,’”’,ted_talks$ratings)"
},
{
"code": null,
"e": 1762,
"s": 1354,
"text": "The next step was to parse the JSON to get a list of id, rating name and rating count. The jsonlite library in R, provides functions to stream, validate and prettify JSON data. The fromJSON function is used to de-serialize JSON objects into R objects. Finally, purrr::map function, applies a function (fromJSON in our case) to each element in the list. The documentation and implementation can be read here."
},
{
"code": null,
"e": 1831,
"s": 1762,
"text": "ted_ratings <- purrr::map(formatted_ted_ratings, jsonlite::fromJSON)"
},
{
"code": null,
"e": 1923,
"s": 1831,
"text": "The code block above gives us a neat list of parsed rating column. It looks like Figure 2 ."
},
{
"code": null,
"e": 2603,
"s": 1923,
"text": "In the next step, I am going to make a new column “highest_rating” in which I will store the rating with highest count for every talk. Post that, I will convert the column into factor which will effectively give us 13 unique factors (ratings) to deal with. I hope, by this point you must have got a hint that this highest_rating column with 13 factor variables will be used for multi-class classification. In the sense, a binary classification problem has two classes to classify a data point, e.g. True and False. Whereas, in this problem we have to deal with the classification of a data point into one of the 13 classes and hence, this is a multi-class classification problem."
},
{
"code": null,
"e": 2894,
"s": 2603,
"text": "for (i in (1:length(ted_ratings))) { ted_ratings_df <- ted_ratings[[i]] highest_rating_count <- ted_ratings_df[which(ted_ratings_df$count == max(ted_ratings_df$count)), ] ted_talks$highest_rating[i] <- highest_rating_count$name}ted_talks$highest_rating = as.factor(ted_talks$highest_rating)"
},
{
"code": null,
"e": 2956,
"s": 2894,
"text": "With the above step, our dataset preparation is now complete."
},
{
"code": null,
"e": 3052,
"s": 2956,
"text": "We will now split our dataset into training and test. I have divided my dataset in 60:40 ratio."
},
{
"code": null,
"e": 3264,
"s": 3052,
"text": "trainObs <- sample(nrow(ted_talks), .6 * nrow(ted_talks), replace = FALSE)testObs <- sample(nrow(ted_talks), .4 * nrow(ted_talks), replace = FALSE)train_dat <- ted_talks[trainObs,]test_dat <- ted_talks[testObs,]"
},
{
"code": null,
"e": 3609,
"s": 3264,
"text": "I will now apply all the pre-processing steps to my training and test data (separately). Somehow, I was in dual mindset: whether to split the DTM into train and test or split the dataset and then prepare their DTM individually. Somehow, I chose the latter option. You can try with the former option and let me know if it works out fine for you."
},
{
"code": null,
"e": 3787,
"s": 3609,
"text": "I also took care of sparsity, something which I discussed in good detail in my blog. I also renamed my target variable as “y” instead of highest_rating for better intuitiveness."
},
{
"code": null,
"e": 4753,
"s": 3787,
"text": "train_corpus <- VCorpus(VectorSource(train_dat$transcript))##Removing Punctuationtrain_corpus <- tm_map(train_corpus, content_transformer(removePunctuation))##Removing numberstrain_corpus <- tm_map(train_corpus, removeNumbers)##Converting to lower casetrain_corpus <- tm_map(train_corpus, content_transformer(tolower))##Removing stop wordstrain_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords(“english”))##Stemmingtrain_corpus <- tm_map(train_corpus, stemDocument)##Whitespacetrain_corpus <- tm_map(train_corpus, stripWhitespace)# Create Document Term Matrixdtm_train <- DocumentTermMatrix(train_corpus)train_corpus <- removeSparseTerms(dtm_train, 0.4)dtm_train_matrix <- as.matrix(train_corpus)dtm_train_matrix <- cbind(dtm_train_matrix, train_dat$highest_rating)colnames(dtm_train_matrix)[ncol(dtm_train_matrix)] <- “y”training_set_ted_talk <- as.data.frame(dtm_train_matrix)training_set_ted_talk$y <- as.factor(training_set_ted_talk$y)"
},
{
"code": null,
"e": 5181,
"s": 4753,
"text": "Now that we have our training dataset ready, we can train our model. I am using caret package and svmLinear3 method in caret. svmLinear3 provides L2 regularization in SVM with Linear Kernel. Agreed, that’s a lot of technical jargon which I am purposely not explaining here because that’s for another blog altogether. Meanwhile, I am going to leave some links for you to understand L2 regularization, and SVM with Linear Kernel."
},
{
"code": null,
"e": 6042,
"s": 5181,
"text": "library(caret)review_ted_model <- train(y ~., data = training_set_ted_talk, method = ‘svmLinear3’)Preparing our test data. It’s the same repetitive procedure.test_corpus <- VCorpus(VectorSource(test_dat$transcript))##Removing Punctuationtest_corpus <- tm_map(test_corpus, content_transformer(removePunctuation))##Removing numberstest_corpus <- tm_map(test_corpus, removeNumbers)##Converting to lower casetest_corpus <- tm_map(test_corpus, content_transformer(tolower))##Removing stop wordstest_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords(“english”))##Stemmingtest_corpus <- tm_map(test_corpus, stemDocument)##Whitespacetest_corpus <- tm_map(test_corpus, stripWhitespace)# Create Document Term Matrixdtm_test <- DocumentTermMatrix(test_corpus)test_corpus <- removeSparseTerms(dtm_test, 0.4)dtm_test_matrix <- as.matrix(test_corpus)"
},
{
"code": null,
"e": 6111,
"s": 6042,
"text": "I will now check the accuracy/performance of our model on test data."
},
{
"code": null,
"e": 6958,
"s": 6111,
"text": "#Build the prediction model_ted_talk_result <- predict(review_ted_model, newdata = dtm_test_matrix)check_accuracy <- as.data.frame(cbind(prediction = model_ted_talk_result, rating = test_dat$highest_rating))library(dplyr)check_accuracy <- check_accuracy %>% mutate(prediction = as.integer(prediction) — 1)check_accuracy$accuracy <- if_else(check_accuracy$prediction == check_accuracy$rating, 1, 0)round(prop.table(table(check_accuracy$accuracy)), 3)library(performanceEstimation)classificationMetrics(as.integer(test_dat$highest_rating), model_ted_talk_result)most_common_misclassified_ratings = check_accuracy %>% filter(check_accuracy$accuracy == 0) %>% group_by(rating) %>% summarise(Count = n()) %>% arrange(desc(Count)) %>% head(3)##Most commong missclassified ratinglevels(train_dat$highest_rating)[most_common_misclassified_ratings$rating]"
},
{
"code": null,
"e": 6981,
"s": 6958,
"text": "The model metrics are:"
},
{
"code": null,
"e": 7145,
"s": 6981,
"text": "The top 3 most commonly misclassified ratings are: “Inspiring”, “Informative”, “Fascinating”. You can read more about micro and macro F1 scores from here and here."
},
{
"code": null,
"e": 7291,
"s": 7145,
"text": "In this article, we have discussed multi-class classification of text. It was pretty challenging data problem for me to solve, primarily because:"
},
{
"code": null,
"e": 7354,
"s": 7291,
"text": "I had uptil now dealt only with binary classification problems"
},
{
"code": null,
"e": 7675,
"s": 7354,
"text": "The data manipulation steps leading to 13 classes for every individual rating column. Single quotes had ruined what looked like a perfect JSON column. Without any intuition for the same, it took a lot of hair pulling to figure out that single quotes were causing the problem. I eventually managed to parse it using gsub."
},
{
"code": null,
"e": 8053,
"s": 7675,
"text": "Finally, the model scores above are heavily reliant on the method we use in the train method. I used SVM with Linear Kernel and L2 regularization which in itself was computationally heavy. There are other methods which you can try, but computational resources could be an issue. Please do let me know what other method(s) you used and the scores (accuracy and F1) that you get."
}
] |
Action Chains in Selenium Python - GeeksforGeeks
|
19 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, This article revolves around how to manipulate DOM using Action Chains in Selenium. We have covered all the methods with examples int detail.
ActionChains are implemented with the help of a action chain object which stores the actions in a queue and when perform() is called, performs the queued operations.
To create object of Action Chain, import ACtion chain class from docs and pass driver as the key argument. After this one can use this object to perform all the operations of action chains.
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # create action chain objectaction = ActionChains(driver)
After one has created an object of Action chain, open a webpage, and perform various other methods using below syntax and examples. Action chains can be used in a chain pattern as below –
menu = driver.find_element_by_css_selector(".nav")hidden_submenu = driver.find_element_by_css_selector(".nav # submenu1") ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
Or actions can be queued up one by one, then performed.:
menu = driver.find_element_by_css_selector(".nav")hidden_submenu = driver.find_element_by_css_selector(".nav # submenu1") actions = ActionChains(driver)actions.move_to_element(menu)actions.click(hidden_submenu)actions.perform()
Let’s try to implement action chains using https://www.geeksforgeeks.org/ and play around with various methods of Selenium Python.
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform()
Above code, first opens https://www.geeksforgeeks.org/ and then clicks on courses button in the header, which then redirects the browser to https://practice.geeksforgeeks.org/ automatically.Output –First driver opens https://www.geeksforgeeks.org/,
then redirects to https://practice.geeksforgeeks.org/
One can perform a huge number of operations using Action chains such as click, right-click, etc. Here is a list of important methods used in Action chains.
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41528,
"s": 41500,
"text": "\n19 May, 2020"
},
{
"code": null,
"e": 42075,
"s": 41528,
"text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, This article revolves around how to manipulate DOM using Action Chains in Selenium. We have covered all the methods with examples int detail."
},
{
"code": null,
"e": 42241,
"s": 42075,
"text": "ActionChains are implemented with the help of a action chain object which stores the actions in a queue and when perform() is called, performs the queued operations."
},
{
"code": null,
"e": 42431,
"s": 42241,
"text": "To create object of Action Chain, import ACtion chain class from docs and pass driver as the key argument. After this one can use this object to perform all the operations of action chains."
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # create action chain objectaction = ActionChains(driver) ",
"e": 42688,
"s": 42431,
"text": null
},
{
"code": null,
"e": 42876,
"s": 42688,
"text": "After one has created an object of Action chain, open a webpage, and perform various other methods using below syntax and examples. Action chains can be used in a chain pattern as below –"
},
{
"code": "menu = driver.find_element_by_css_selector(\".nav\")hidden_submenu = driver.find_element_by_css_selector(\".nav # submenu1\") ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()",
"e": 43074,
"s": 42876,
"text": null
},
{
"code": null,
"e": 43131,
"s": 43074,
"text": "Or actions can be queued up one by one, then performed.:"
},
{
"code": "menu = driver.find_element_by_css_selector(\".nav\")hidden_submenu = driver.find_element_by_css_selector(\".nav # submenu1\") actions = ActionChains(driver)actions.move_to_element(menu)actions.click(hidden_submenu)actions.perform()",
"e": 43360,
"s": 43131,
"text": null
},
{
"code": null,
"e": 43491,
"s": 43360,
"text": "Let’s try to implement action chains using https://www.geeksforgeeks.org/ and play around with various methods of Selenium Python."
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform()",
"e": 43981,
"s": 43491,
"text": null
},
{
"code": null,
"e": 44230,
"s": 43981,
"text": "Above code, first opens https://www.geeksforgeeks.org/ and then clicks on courses button in the header, which then redirects the browser to https://practice.geeksforgeeks.org/ automatically.Output –First driver opens https://www.geeksforgeeks.org/,"
},
{
"code": null,
"e": 44284,
"s": 44230,
"text": "then redirects to https://practice.geeksforgeeks.org/"
},
{
"code": null,
"e": 44440,
"s": 44284,
"text": "One can perform a huge number of operations using Action chains such as click, right-click, etc. Here is a list of important methods used in Action chains."
},
{
"code": null,
"e": 44456,
"s": 44440,
"text": "Python-selenium"
},
{
"code": null,
"e": 44465,
"s": 44456,
"text": "selenium"
},
{
"code": null,
"e": 44472,
"s": 44465,
"text": "Python"
},
{
"code": null,
"e": 44570,
"s": 44472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44598,
"s": 44570,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44648,
"s": 44598,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44670,
"s": 44648,
"text": "Python map() function"
},
{
"code": null,
"e": 44714,
"s": 44670,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44749,
"s": 44714,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44771,
"s": 44749,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 44803,
"s": 44771,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44833,
"s": 44803,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 44875,
"s": 44833,
"text": "Different ways to create Pandas Dataframe"
}
] |
Python | Numpy ndarray.item() - GeeksforGeeks
|
27 Mar, 2019
With the help of numpy.ndarray.item() method, we can fetch the data elements that is found at the given index on numpy array. Remember we can give index as one dimensional parameter or can be two dimensional.
Parameters:*args : Arguments (variable number and type)-> none: This argument only works when size of an array is 1.-> int_type: This argument is interpreted as a flat index into the array, specifying which element to return.-> tuple of int_types: This argument is interpreted as a two dimensional array, by specifying which element to return.
Returns: Copy of an Item
Example #1 :In this example we can see that by specifying the argument in ndarray.item() method, we can have the element if it existed on this index.
# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.item() methodprint(gfg.item(2))
3
Example #2 :
# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([[1, 2, 3, 4, 5], [6, 5, 4, 3, 2]]) # applying ndarray.item() methodprint(gfg.item((1, 2)))
4
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 24501,
"s": 24292,
"text": "With the help of numpy.ndarray.item() method, we can fetch the data elements that is found at the given index on numpy array. Remember we can give index as one dimensional parameter or can be two dimensional."
},
{
"code": null,
"e": 24845,
"s": 24501,
"text": "Parameters:*args : Arguments (variable number and type)-> none: This argument only works when size of an array is 1.-> int_type: This argument is interpreted as a flat index into the array, specifying which element to return.-> tuple of int_types: This argument is interpreted as a two dimensional array, by specifying which element to return."
},
{
"code": null,
"e": 24870,
"s": 24845,
"text": "Returns: Copy of an Item"
},
{
"code": null,
"e": 25020,
"s": 24870,
"text": "Example #1 :In this example we can see that by specifying the argument in ndarray.item() method, we can have the element if it existed on this index."
},
{
"code": "# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.item() methodprint(gfg.item(2))",
"e": 25199,
"s": 25020,
"text": null
},
{
"code": null,
"e": 25202,
"s": 25199,
"text": "3\n"
},
{
"code": null,
"e": 25215,
"s": 25202,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make an array with numpygfg = np.array([[1, 2, 3, 4, 5], [6, 5, 4, 3, 2]]) # applying ndarray.item() methodprint(gfg.item((1, 2)))",
"e": 25433,
"s": 25215,
"text": null
},
{
"code": null,
"e": 25436,
"s": 25433,
"text": "4\n"
},
{
"code": null,
"e": 25457,
"s": 25436,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 25470,
"s": 25457,
"text": "Python-numpy"
},
{
"code": null,
"e": 25477,
"s": 25470,
"text": "Python"
},
{
"code": null,
"e": 25575,
"s": 25477,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25584,
"s": 25575,
"text": "Comments"
},
{
"code": null,
"e": 25597,
"s": 25584,
"text": "Old Comments"
},
{
"code": null,
"e": 25629,
"s": 25597,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25685,
"s": 25629,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25740,
"s": 25685,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25782,
"s": 25740,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25824,
"s": 25782,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25855,
"s": 25824,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25894,
"s": 25855,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25923,
"s": 25894,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 25945,
"s": 25923,
"text": "Defaultdict in Python"
}
] |
How to fetch fields with multiple values set using MySQL LIKE?
|
To fetch fields with multiple values, use LIKE with OR in MySQL −
select *from yourTableName where yourColumnName like ‘%AnyStringValue’ or yourColumnName like ‘%AnyStringValue’ or yourColumnName like ‘%AnyStringValue’ .........N;
You can understand with the help of a table −
mysql> create table LikeDemo
−> (
−> Hobby varchar(200)
−> );
Query OK, 0 rows affected (1.71 sec)
Insert some records in the table with the help of insert command. The query to insert records in the table is as follows −
mysql> insert into LikeDemo values('Reading Book');
Query OK, 1 row affected (0.13 sec)
mysql> insert into LikeDemo values('Playing Cricket Match');
Query OK, 1 row affected (0.16 sec)
mysql> insert into LikeDemo values('Playing Hockey Match');
Query OK, 1 row affected (0.27 sec)
mysql> insert into LikeDemo values('Reading Novel');
Query OK, 1 row affected (0.14 sec)
mysql> insert into LikeDemo values('Swimming');
Query OK, 1 row affected (0.10 sec)
Displaying all records with the help of select statement. The query is as follows:
mysql> select *from LikeDemo;
The following is the output −
+-----------------------+
| Hobby |
+-----------------------+
| Reading Book |
| Playing Cricket Match |
| Playing Hockey Match |
| Reading Novel |
| Swimming |
+-----------------------+
5 rows in set (0.00 sec)
The query to fetch fields with multiple values using LIKE is as follows −
mysql> select *from LikeDemo where Hobby like '%Cricket%' or Hobby like '%Reading%';
The following is the output −
+-----------------------+
| Hobby |
+-----------------------+
| Reading Book |
| Playing Cricket Match |
| Reading Novel |
+-----------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "To fetch fields with multiple values, use LIKE with OR in MySQL −"
},
{
"code": null,
"e": 1293,
"s": 1128,
"text": "select *from yourTableName where yourColumnName like ‘%AnyStringValue’ or yourColumnName like ‘%AnyStringValue’ or yourColumnName like ‘%AnyStringValue’ .........N;"
},
{
"code": null,
"e": 1339,
"s": 1293,
"text": "You can understand with the help of a table −"
},
{
"code": null,
"e": 1450,
"s": 1339,
"text": "mysql> create table LikeDemo\n −> (\n −> Hobby varchar(200)\n −> );\nQuery OK, 0 rows affected (1.71 sec)"
},
{
"code": null,
"e": 1573,
"s": 1450,
"text": "Insert some records in the table with the help of insert command. The query to insert records in the table is as follows −"
},
{
"code": null,
"e": 2146,
"s": 1573,
"text": "mysql> insert into LikeDemo values('Reading Book');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into LikeDemo values('Playing Cricket Match');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into LikeDemo values('Playing Hockey Match');\nQuery OK, 1 row affected (0.27 sec)\n\nmysql> insert into LikeDemo values('Reading Novel');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into LikeDemo values('Swimming');\nQuery OK, 1 row affected (0.10 sec)\n\nDisplaying all records with the help of select statement. The query is as follows:\n\nmysql> select *from LikeDemo;"
},
{
"code": null,
"e": 2176,
"s": 2146,
"text": "The following is the output −"
},
{
"code": null,
"e": 2435,
"s": 2176,
"text": "+-----------------------+\n| Hobby |\n+-----------------------+\n| Reading Book |\n| Playing Cricket Match |\n| Playing Hockey Match |\n| Reading Novel |\n| Swimming |\n+-----------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2509,
"s": 2435,
"text": "The query to fetch fields with multiple values using LIKE is as follows −"
},
{
"code": null,
"e": 2594,
"s": 2509,
"text": "mysql> select *from LikeDemo where Hobby like '%Cricket%' or Hobby like '%Reading%';"
},
{
"code": null,
"e": 2624,
"s": 2594,
"text": "The following is the output −"
},
{
"code": null,
"e": 2831,
"s": 2624,
"text": "+-----------------------+\n| Hobby |\n+-----------------------+\n| Reading Book |\n| Playing Cricket Match |\n| Reading Novel |\n+-----------------------+\n3 rows in set (0.00 sec)"
}
] |
C++ Library - <unordered_map>
|
Unordered map is dictionary like data structure. It is a sequence of (key, value) pair, where only single value is associated with each unique key. It is often referred as associative array. It enables fast retrieval of individual elements based on their keys. It also implements the direct access operator(subscript operator[]) which allows for direct access of the mapped value using its key value as argument.
Unordered map does not sort its element in any particular order with respect to either their key or mapped values, instead organizes into buckets depending on their hash values to allow for fast access to individual elements directly by their key values.
Unordered map performs better than map while accessing individual elements by their keys. But for range iteration their performance is considerably low.
Below is definition of std::unordered_map from <unordered_map> header file
template < class Key,
class T,
class Hash = hash<Key>,
class Pred = equal_to<Key>,
class Alloc = allocator< pair<const Key,T> >
> class unordered_map;
Key − Type of the key.
Key − Type of the key.
T − Type of the mapped values.
T − Type of the mapped values.
Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it.
Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it.
Pred − A binary predicate that which two arguments of the key type and returns a bool.
Pred − A binary predicate that which two arguments of the key type and returns a bool.
Alloc − Type of the allocator object.
Alloc − Type of the allocator object.
T may be substituted by any other data type including user-defined type.
Following member types can be used as parameters or return type by member functions.
Below is list of all methods from <unordered_map> header.
Constructs an empty unordered_map with zero elements.
Constructs an unordered_map with copy of each elements present in existing unordered_map.
Constructs an unordered_map with the contents of other using move semantics.
Constructs an unordered_map with as many elements as in range of first to last.
Constructs an unordered_map from initialize list.
Destroys unordered_map object by deallocating it's memory.
Returns a reference to the mapped value associated with key k.
Returns an iterator which refers to the first element of the map.
Returns an iterator pointing to the first element in one of its buckets.
Returns the bucket number where element with key k is located.
Returns the number of buckets in unordered_map container.
Returns the number of elements presents in the nth bucket.
Returns a constant iterator which refers to the first element of the unordered_map.
Returns a constant iterator pointing to the first element in one of its buckets.
Returns a constant iterator which points to past-the-end element of the unordered_map.
Returns a constant iterator which points to past-the-end element in one of its buckets.
Destroys the unordered_map by removing all elements and sets the size of unordered_map to zero.
Returns the number of mapped values associated with key k.
Extends container by inserting new element.
Inserts a new element in unordered_map using hint as a position for element.
Tests whether unordered_map is empty or not.
Returns an iterator which points to past-the-end element in the unordered_map.
Returns an iterator which points to past-the-end element in one of its buckets.
Returns range of elements that matches specific key.
Removes single element of the unordered_map from position.
Removes mapped value associated with key k.
Removes range of element from the the unordered_map.
Finds an element associated with key k.
Returns an allocator associated with unordered_map.
Calculates the hash function object used by the unordered_map container.
Extends container by inserting new element in unordered_map.
Extends container by inserting new element in unordered_map.
Extends conta iner by inserting new element in unordered_map.
Extends unordered_map by inserting new element.
Extends container by inserting new elements in the unordered_map.
Extends map by inserting new element from initializer list.
Returns the function that compares keys for equality.
Returns the current load factor of the unordered_map container.
Returns the maximum number of buckets that the unordered_map container can have.
Returns the current maximum load factor for the unordered_map container.
Assigns new load factor for the unordered_map container.
Returns the maximum number of elements can be held by unordered_map.
Assigns new contents to the unordered_map by replacing old ones and modifies size if necessary.
Move the contents of one unordered_map into another and modifies size if necessary.
Copy elements from initializer list to unordered_map.
If key k matches an element in the container, then method returns a reference to the element.
If key k matches an element in the container, then method returns a reference to the element.
Sets the number of buckets in the container to n or more.
Sets the number of buckets in the container to the most appropriate to contain at least n elements.
Returns the number of elements present in the unordered_map.
Exchanges the content of first unordered_map with another.
Tests whether two unordered_maps are equal or not.
Tests whether two unordered_maps are equal or not.
Exchanges the content of first unordered_map with another.
Unordered_multimap is dictionary like data structure. It is a sequence of (key, value) pair, where different elements can have equivalent keys. Elements with equivalent keys are grouped together in the same bucket and in such a way that an equal_range iterator can iterate through all of them.
Unordered_multimap does not sort its element in any particular order with respect to either their key or mapped values, instead organizes into buckets depending on their hash values to allow for fast access to individual elements directly by their key values.
Below is definition of std::unordered_multimap from <unordered_map> header file
template < class Key,
class T,
class Hash = hash<Key>,
class Pred = equal_to<Key>,
class Alloc = allocator< pair<const Key,T> >
> class unordered_multimap;
Key − Type of the key.
Key − Type of the key.
T − Type of the mapped values.
T − Type of the mapped values.
Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it.
Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it.
Pred − A binary predicate that which two arguments of the key type and returns a bool.
Pred − A binary predicate that which two arguments of the key type and returns a bool.
Alloc − Type of the allocator object.
T may be substituted by any other data type including user-defined type.
Alloc − Type of the allocator object.
T may be substituted by any other data type including user-defined type.
Following member types can be used as parameters or return type by member functions.
Below is list of all methods from <unordered_map> header.
Constructs an empty unordered_multimap with zero elements.
Constructs an unordered_multimap with copy of each elements present in existing unordered_multimap.
Constructs an unordered_multimap with the contents of other using move semantics.
Constructs an unordered_multimap with as many elements as in range of first to last.
Constructs an unordered_multimap from initialize list.
Destroys unordered_multimap object by deallocating it's memory.
Returns an iterator which refers to the first element of the unordered_mulitmap.
Returns an iterator pointing to the first element in one of its buckets.
Returns the bucket number where element with key k is located.
Returns the number of buckets present in unordered_multimap container.
Returns the number of elements presents in the nth bucket.
Returns a constant iterator which refers to the first element of the unordered_multimap.
Returns a constant iterator pointing to the first element in one of its buckets.
Returns a constant iterator which points to past-the-end element of the unordered_multimap.
Returns a constant iterator which points to past-the-end element in one of its buckets.
Destroys the unordered_multimap by removing all elements and sets the size of unordered_multimap to zero.
Returns the number of mapped values associated with key k.
Extends container by inserting new element.
Inserts a new element in a unordered_multimap using hint as a position for element.
Tests whether unordered_multimap is empty or not.
Returns an iterator which points to past-the-end element in the unordered_multimap.
Returns an iterator which points to past-the-end element in one of its buckets.
Returns range of elements that matches specific key.
Removes single element of the unordered_multimap from position.
Removes mapped value associated with key k.
Removes range of element from the the unordered_multimap.
Finds an element associated with key k.
Returns an allocator associated with unordered_multimap.
Calculates the hash function object used by the unordered_multimap container.
Extends container by inserting new element in unordered_multimap.
Extends unordered_multimap by inserting new element.
Extends container by inserting new element in unordered_multimap.
Extends container by inserting new element in unordered_multimap by using move semantics.
Extends container by inserting new elements in the unordered_multimap.
Extends unordered_multimap by inserting new element from initializer list.
Returns the function that compares keys for equality.
Returns the current load factor of the unordered_multimap container.
Returns the maximum number of buckets that the unordered_multimap container can have.
Returns the current maximum load factor for the unordered_multimap container.
Assigns new load factor for the unordered_multimap container.
Returns the maximum number of elements can be held by unordered_multimap.
Assigns new contents to the unordered_multimap by replacing old ones and modifies size if necessary.
Move the contents of one unordered_multimap into another and modifies size if necessary.
Copy elements from initializer list to unordered_multimap.
Sets the number of buckets in the container to n or more.
Sets the number of buckets in the container to the most appropriate to contain at least n elements.
Returns the number of elements present in the unordered_multimap.
Exchanges the content of first unordered_multimap with another.
Tests whether two unordered_multimaps are equal or not.
Tests whether two unordered_multimaps are equal or not.
Exchanges the content of first unordered_multimap with another.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3016,
"s": 2603,
"text": "Unordered map is dictionary like data structure. It is a sequence of (key, value) pair, where only single value is associated with each unique key. It is often referred as associative array. It enables fast retrieval of individual elements based on their keys. It also implements the direct access operator(subscript operator[]) which allows for direct access of the mapped value using its key value as argument."
},
{
"code": null,
"e": 3271,
"s": 3016,
"text": "Unordered map does not sort its element in any particular order with respect to either their key or mapped values, instead organizes into buckets depending on their hash values to allow for fast access to individual elements directly by their key values."
},
{
"code": null,
"e": 3424,
"s": 3271,
"text": "Unordered map performs better than map while accessing individual elements by their keys. But for range iteration their performance is considerably low."
},
{
"code": null,
"e": 3499,
"s": 3424,
"text": "Below is definition of std::unordered_map from <unordered_map> header file"
},
{
"code": null,
"e": 3706,
"s": 3499,
"text": "template < class Key,\n class T,\n class Hash = hash<Key>,\n class Pred = equal_to<Key>,\n class Alloc = allocator< pair<const Key,T> >\n > class unordered_map;\n"
},
{
"code": null,
"e": 3729,
"s": 3706,
"text": "Key − Type of the key."
},
{
"code": null,
"e": 3752,
"s": 3729,
"text": "Key − Type of the key."
},
{
"code": null,
"e": 3783,
"s": 3752,
"text": "T − Type of the mapped values."
},
{
"code": null,
"e": 3814,
"s": 3783,
"text": "T − Type of the mapped values."
},
{
"code": null,
"e": 3956,
"s": 3814,
"text": "Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it."
},
{
"code": null,
"e": 4098,
"s": 3956,
"text": "Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it."
},
{
"code": null,
"e": 4185,
"s": 4098,
"text": "Pred − A binary predicate that which two arguments of the key type and returns a bool."
},
{
"code": null,
"e": 4272,
"s": 4185,
"text": "Pred − A binary predicate that which two arguments of the key type and returns a bool."
},
{
"code": null,
"e": 4310,
"s": 4272,
"text": "Alloc − Type of the allocator object."
},
{
"code": null,
"e": 4348,
"s": 4310,
"text": "Alloc − Type of the allocator object."
},
{
"code": null,
"e": 4421,
"s": 4348,
"text": "T may be substituted by any other data type including user-defined type."
},
{
"code": null,
"e": 4506,
"s": 4421,
"text": "Following member types can be used as parameters or return type by member functions."
},
{
"code": null,
"e": 4564,
"s": 4506,
"text": "Below is list of all methods from <unordered_map> header."
},
{
"code": null,
"e": 4618,
"s": 4564,
"text": "Constructs an empty unordered_map with zero elements."
},
{
"code": null,
"e": 4708,
"s": 4618,
"text": "Constructs an unordered_map with copy of each elements present in existing unordered_map."
},
{
"code": null,
"e": 4785,
"s": 4708,
"text": "Constructs an unordered_map with the contents of other using move semantics."
},
{
"code": null,
"e": 4865,
"s": 4785,
"text": "Constructs an unordered_map with as many elements as in range of first to last."
},
{
"code": null,
"e": 4915,
"s": 4865,
"text": "Constructs an unordered_map from initialize list."
},
{
"code": null,
"e": 4974,
"s": 4915,
"text": "Destroys unordered_map object by deallocating it's memory."
},
{
"code": null,
"e": 5037,
"s": 4974,
"text": "Returns a reference to the mapped value associated with key k."
},
{
"code": null,
"e": 5103,
"s": 5037,
"text": "Returns an iterator which refers to the first element of the map."
},
{
"code": null,
"e": 5176,
"s": 5103,
"text": "Returns an iterator pointing to the first element in one of its buckets."
},
{
"code": null,
"e": 5239,
"s": 5176,
"text": "Returns the bucket number where element with key k is located."
},
{
"code": null,
"e": 5297,
"s": 5239,
"text": "Returns the number of buckets in unordered_map container."
},
{
"code": null,
"e": 5356,
"s": 5297,
"text": "Returns the number of elements presents in the nth bucket."
},
{
"code": null,
"e": 5440,
"s": 5356,
"text": "Returns a constant iterator which refers to the first element of the unordered_map."
},
{
"code": null,
"e": 5521,
"s": 5440,
"text": "Returns a constant iterator pointing to the first element in one of its buckets."
},
{
"code": null,
"e": 5608,
"s": 5521,
"text": "Returns a constant iterator which points to past-the-end element of the unordered_map."
},
{
"code": null,
"e": 5696,
"s": 5608,
"text": "Returns a constant iterator which points to past-the-end element in one of its buckets."
},
{
"code": null,
"e": 5792,
"s": 5696,
"text": "Destroys the unordered_map by removing all elements and sets the size of unordered_map to zero."
},
{
"code": null,
"e": 5851,
"s": 5792,
"text": "Returns the number of mapped values associated with key k."
},
{
"code": null,
"e": 5895,
"s": 5851,
"text": "Extends container by inserting new element."
},
{
"code": null,
"e": 5972,
"s": 5895,
"text": "Inserts a new element in unordered_map using hint as a position for element."
},
{
"code": null,
"e": 6017,
"s": 5972,
"text": "Tests whether unordered_map is empty or not."
},
{
"code": null,
"e": 6096,
"s": 6017,
"text": "Returns an iterator which points to past-the-end element in the unordered_map."
},
{
"code": null,
"e": 6176,
"s": 6096,
"text": "Returns an iterator which points to past-the-end element in one of its buckets."
},
{
"code": null,
"e": 6229,
"s": 6176,
"text": "Returns range of elements that matches specific key."
},
{
"code": null,
"e": 6288,
"s": 6229,
"text": "Removes single element of the unordered_map from position."
},
{
"code": null,
"e": 6332,
"s": 6288,
"text": "Removes mapped value associated with key k."
},
{
"code": null,
"e": 6385,
"s": 6332,
"text": "Removes range of element from the the unordered_map."
},
{
"code": null,
"e": 6425,
"s": 6385,
"text": "Finds an element associated with key k."
},
{
"code": null,
"e": 6477,
"s": 6425,
"text": "Returns an allocator associated with unordered_map."
},
{
"code": null,
"e": 6550,
"s": 6477,
"text": "Calculates the hash function object used by the unordered_map container."
},
{
"code": null,
"e": 6611,
"s": 6550,
"text": "Extends container by inserting new element in unordered_map."
},
{
"code": null,
"e": 6672,
"s": 6611,
"text": "Extends container by inserting new element in unordered_map."
},
{
"code": null,
"e": 6734,
"s": 6672,
"text": "Extends conta iner by inserting new element in unordered_map."
},
{
"code": null,
"e": 6782,
"s": 6734,
"text": "Extends unordered_map by inserting new element."
},
{
"code": null,
"e": 6848,
"s": 6782,
"text": "Extends container by inserting new elements in the unordered_map."
},
{
"code": null,
"e": 6908,
"s": 6848,
"text": "Extends map by inserting new element from initializer list."
},
{
"code": null,
"e": 6962,
"s": 6908,
"text": "Returns the function that compares keys for equality."
},
{
"code": null,
"e": 7026,
"s": 6962,
"text": "Returns the current load factor of the unordered_map container."
},
{
"code": null,
"e": 7107,
"s": 7026,
"text": "Returns the maximum number of buckets that the unordered_map container can have."
},
{
"code": null,
"e": 7180,
"s": 7107,
"text": "Returns the current maximum load factor for the unordered_map container."
},
{
"code": null,
"e": 7237,
"s": 7180,
"text": "Assigns new load factor for the unordered_map container."
},
{
"code": null,
"e": 7306,
"s": 7237,
"text": "Returns the maximum number of elements can be held by unordered_map."
},
{
"code": null,
"e": 7402,
"s": 7306,
"text": "Assigns new contents to the unordered_map by replacing old ones and modifies size if necessary."
},
{
"code": null,
"e": 7486,
"s": 7402,
"text": "Move the contents of one unordered_map into another and modifies size if necessary."
},
{
"code": null,
"e": 7540,
"s": 7486,
"text": "Copy elements from initializer list to unordered_map."
},
{
"code": null,
"e": 7634,
"s": 7540,
"text": "If key k matches an element in the container, then method returns a reference to the element."
},
{
"code": null,
"e": 7728,
"s": 7634,
"text": "If key k matches an element in the container, then method returns a reference to the element."
},
{
"code": null,
"e": 7786,
"s": 7728,
"text": "Sets the number of buckets in the container to n or more."
},
{
"code": null,
"e": 7886,
"s": 7786,
"text": "Sets the number of buckets in the container to the most appropriate to contain at least n elements."
},
{
"code": null,
"e": 7947,
"s": 7886,
"text": "Returns the number of elements present in the unordered_map."
},
{
"code": null,
"e": 8006,
"s": 7947,
"text": "Exchanges the content of first unordered_map with another."
},
{
"code": null,
"e": 8057,
"s": 8006,
"text": "Tests whether two unordered_maps are equal or not."
},
{
"code": null,
"e": 8108,
"s": 8057,
"text": "Tests whether two unordered_maps are equal or not."
},
{
"code": null,
"e": 8167,
"s": 8108,
"text": "Exchanges the content of first unordered_map with another."
},
{
"code": null,
"e": 8461,
"s": 8167,
"text": "Unordered_multimap is dictionary like data structure. It is a sequence of (key, value) pair, where different elements can have equivalent keys. Elements with equivalent keys are grouped together in the same bucket and in such a way that an equal_range iterator can iterate through all of them."
},
{
"code": null,
"e": 8721,
"s": 8461,
"text": "Unordered_multimap does not sort its element in any particular order with respect to either their key or mapped values, instead organizes into buckets depending on their hash values to allow for fast access to individual elements directly by their key values."
},
{
"code": null,
"e": 8801,
"s": 8721,
"text": "Below is definition of std::unordered_multimap from <unordered_map> header file"
},
{
"code": null,
"e": 9014,
"s": 8801,
"text": "template < class Key, \n class T,\n class Hash = hash<Key>,\n class Pred = equal_to<Key>,\n class Alloc = allocator< pair<const Key,T> >\n > class unordered_multimap;\n"
},
{
"code": null,
"e": 9037,
"s": 9014,
"text": "Key − Type of the key."
},
{
"code": null,
"e": 9060,
"s": 9037,
"text": "Key − Type of the key."
},
{
"code": null,
"e": 9091,
"s": 9060,
"text": "T − Type of the mapped values."
},
{
"code": null,
"e": 9122,
"s": 9091,
"text": "T − Type of the mapped values."
},
{
"code": null,
"e": 9264,
"s": 9122,
"text": "Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it."
},
{
"code": null,
"e": 9406,
"s": 9264,
"text": "Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it."
},
{
"code": null,
"e": 9493,
"s": 9406,
"text": "Pred − A binary predicate that which two arguments of the key type and returns a bool."
},
{
"code": null,
"e": 9580,
"s": 9493,
"text": "Pred − A binary predicate that which two arguments of the key type and returns a bool."
},
{
"code": null,
"e": 9691,
"s": 9580,
"text": "Alloc − Type of the allocator object.\nT may be substituted by any other data type including user-defined type."
},
{
"code": null,
"e": 9729,
"s": 9691,
"text": "Alloc − Type of the allocator object."
},
{
"code": null,
"e": 9802,
"s": 9729,
"text": "T may be substituted by any other data type including user-defined type."
},
{
"code": null,
"e": 9887,
"s": 9802,
"text": "Following member types can be used as parameters or return type by member functions."
},
{
"code": null,
"e": 9945,
"s": 9887,
"text": "Below is list of all methods from <unordered_map> header."
},
{
"code": null,
"e": 10004,
"s": 9945,
"text": "Constructs an empty unordered_multimap with zero elements."
},
{
"code": null,
"e": 10104,
"s": 10004,
"text": "Constructs an unordered_multimap with copy of each elements present in existing unordered_multimap."
},
{
"code": null,
"e": 10186,
"s": 10104,
"text": "Constructs an unordered_multimap with the contents of other using move semantics."
},
{
"code": null,
"e": 10271,
"s": 10186,
"text": "Constructs an unordered_multimap with as many elements as in range of first to last."
},
{
"code": null,
"e": 10326,
"s": 10271,
"text": "Constructs an unordered_multimap from initialize list."
},
{
"code": null,
"e": 10390,
"s": 10326,
"text": "Destroys unordered_multimap object by deallocating it's memory."
},
{
"code": null,
"e": 10471,
"s": 10390,
"text": "Returns an iterator which refers to the first element of the unordered_mulitmap."
},
{
"code": null,
"e": 10544,
"s": 10471,
"text": "Returns an iterator pointing to the first element in one of its buckets."
},
{
"code": null,
"e": 10607,
"s": 10544,
"text": "Returns the bucket number where element with key k is located."
},
{
"code": null,
"e": 10678,
"s": 10607,
"text": "Returns the number of buckets present in unordered_multimap container."
},
{
"code": null,
"e": 10737,
"s": 10678,
"text": "Returns the number of elements presents in the nth bucket."
},
{
"code": null,
"e": 10826,
"s": 10737,
"text": "Returns a constant iterator which refers to the first element of the unordered_multimap."
},
{
"code": null,
"e": 10907,
"s": 10826,
"text": "Returns a constant iterator pointing to the first element in one of its buckets."
},
{
"code": null,
"e": 10999,
"s": 10907,
"text": "Returns a constant iterator which points to past-the-end element of the unordered_multimap."
},
{
"code": null,
"e": 11087,
"s": 10999,
"text": "Returns a constant iterator which points to past-the-end element in one of its buckets."
},
{
"code": null,
"e": 11193,
"s": 11087,
"text": "Destroys the unordered_multimap by removing all elements and sets the size of unordered_multimap to zero."
},
{
"code": null,
"e": 11252,
"s": 11193,
"text": "Returns the number of mapped values associated with key k."
},
{
"code": null,
"e": 11296,
"s": 11252,
"text": "Extends container by inserting new element."
},
{
"code": null,
"e": 11380,
"s": 11296,
"text": "Inserts a new element in a unordered_multimap using hint as a position for element."
},
{
"code": null,
"e": 11430,
"s": 11380,
"text": "Tests whether unordered_multimap is empty or not."
},
{
"code": null,
"e": 11514,
"s": 11430,
"text": "Returns an iterator which points to past-the-end element in the unordered_multimap."
},
{
"code": null,
"e": 11594,
"s": 11514,
"text": "Returns an iterator which points to past-the-end element in one of its buckets."
},
{
"code": null,
"e": 11647,
"s": 11594,
"text": "Returns range of elements that matches specific key."
},
{
"code": null,
"e": 11711,
"s": 11647,
"text": "Removes single element of the unordered_multimap from position."
},
{
"code": null,
"e": 11755,
"s": 11711,
"text": "Removes mapped value associated with key k."
},
{
"code": null,
"e": 11813,
"s": 11755,
"text": "Removes range of element from the the unordered_multimap."
},
{
"code": null,
"e": 11853,
"s": 11813,
"text": "Finds an element associated with key k."
},
{
"code": null,
"e": 11910,
"s": 11853,
"text": "Returns an allocator associated with unordered_multimap."
},
{
"code": null,
"e": 11988,
"s": 11910,
"text": "Calculates the hash function object used by the unordered_multimap container."
},
{
"code": null,
"e": 12054,
"s": 11988,
"text": "Extends container by inserting new element in unordered_multimap."
},
{
"code": null,
"e": 12107,
"s": 12054,
"text": "Extends unordered_multimap by inserting new element."
},
{
"code": null,
"e": 12173,
"s": 12107,
"text": "Extends container by inserting new element in unordered_multimap."
},
{
"code": null,
"e": 12263,
"s": 12173,
"text": "Extends container by inserting new element in unordered_multimap by using move semantics."
},
{
"code": null,
"e": 12334,
"s": 12263,
"text": "Extends container by inserting new elements in the unordered_multimap."
},
{
"code": null,
"e": 12409,
"s": 12334,
"text": "Extends unordered_multimap by inserting new element from initializer list."
},
{
"code": null,
"e": 12463,
"s": 12409,
"text": "Returns the function that compares keys for equality."
},
{
"code": null,
"e": 12532,
"s": 12463,
"text": "Returns the current load factor of the unordered_multimap container."
},
{
"code": null,
"e": 12618,
"s": 12532,
"text": "Returns the maximum number of buckets that the unordered_multimap container can have."
},
{
"code": null,
"e": 12696,
"s": 12618,
"text": "Returns the current maximum load factor for the unordered_multimap container."
},
{
"code": null,
"e": 12758,
"s": 12696,
"text": "Assigns new load factor for the unordered_multimap container."
},
{
"code": null,
"e": 12832,
"s": 12758,
"text": "Returns the maximum number of elements can be held by unordered_multimap."
},
{
"code": null,
"e": 12933,
"s": 12832,
"text": "Assigns new contents to the unordered_multimap by replacing old ones and modifies size if necessary."
},
{
"code": null,
"e": 13022,
"s": 12933,
"text": "Move the contents of one unordered_multimap into another and modifies size if necessary."
},
{
"code": null,
"e": 13081,
"s": 13022,
"text": "Copy elements from initializer list to unordered_multimap."
},
{
"code": null,
"e": 13139,
"s": 13081,
"text": "Sets the number of buckets in the container to n or more."
},
{
"code": null,
"e": 13239,
"s": 13139,
"text": "Sets the number of buckets in the container to the most appropriate to contain at least n elements."
},
{
"code": null,
"e": 13305,
"s": 13239,
"text": "Returns the number of elements present in the unordered_multimap."
},
{
"code": null,
"e": 13369,
"s": 13305,
"text": "Exchanges the content of first unordered_multimap with another."
},
{
"code": null,
"e": 13425,
"s": 13369,
"text": "Tests whether two unordered_multimaps are equal or not."
},
{
"code": null,
"e": 13481,
"s": 13425,
"text": "Tests whether two unordered_multimaps are equal or not."
},
{
"code": null,
"e": 13545,
"s": 13481,
"text": "Exchanges the content of first unordered_multimap with another."
},
{
"code": null,
"e": 13552,
"s": 13545,
"text": " Print"
},
{
"code": null,
"e": 13563,
"s": 13552,
"text": " Add Notes"
}
] |
How to Convert Pandas DataFrame into a List? - GeeksforGeeks
|
03 May, 2021
Let’s discuss how to convert Pandas dataframe to List. First, let’s create a Basic DataFrame:
Python3
import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ], 'Age': [35, 70, 45, 20] } # Creating DataFrame df = pd.DataFrame(data) # Print the dataframedf
Output :
At times, you may need to convert your pandas dataframe to List. To accomplish this task, ‘ tolist() ‘ function can be used. Below is a basic example to use this function and convert the required DataFrame into a List.
Python3
df.values.tolist()
Output :
[['Tony', 35], ['Steve', 70], ['Bruce', 45], ['Peter', 20]]
Here, Each inner list contains all the columns of a particular row.
Pandas DataFrame can be converted into lists in multiple ways. Let’s have a look at different ways of converting a DataFrame one by one.
Method #1: Converting a DataFrame to List containing all the rows of a particular column:
Python3
import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFrame df = pd.DataFrame(data) # Converting DataFrame to a list containing# all the rows of column 'Name'names = df['Name'].tolist() # Printing the converted list.print(names)
Output:
['Tony', 'Steve', 'Bruce', 'Peter']
Method #2: Converting a DataFrame to Nested List containing all the rows of all the columns:
Python3
import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFramedf = pd.DataFrame(data) # Creating an empty listres=[] # Iterating through the columns of# dataframefor column in df.columns: # Storing the rows of a column # into a temporary list li = df[column].tolist() # appending the temporary list res.append(li) # Printing the final listprint(res)
Output:
[['Tony', 'Steve', 'Bruce', 'Peter'], [35, 70, 45, 20]]
Method #3: Converting a DataFrame to a list that contains lists having all the columns of a row.
Python3
import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFramedf = pd.DataFrame(data) # Converting dataframe to listli = df.values.tolist() # Printing listprint(li)
Output :
[['Tony', 35], ['Steve', 70], ['Bruce', 45], ['Peter', 20]]
Method #4: Converting a DataFrame to a list that contains lists having all the columns of a row along with column names.
Python3
import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFramedf = pd.DataFrame(data) # Converting dataframe to listli = [df.columns.values.tolist()] + df.values.tolist() # Printing listprint(li)
Output:
[[‘Name’, ‘Age’], [‘Tony’, 35], [‘Steve’, 70], [‘Bruce’, 45], [‘Peter’, 20]]
simmytarika5
Python pandas-dataFrame
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 ?
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
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25580,
"s": 25552,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 25674,
"s": 25580,
"text": "Let’s discuss how to convert Pandas dataframe to List. First, let’s create a Basic DataFrame:"
},
{
"code": null,
"e": 25682,
"s": 25674,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ], 'Age': [35, 70, 45, 20] } # Creating DataFrame df = pd.DataFrame(data) # Print the dataframedf",
"e": 25897,
"s": 25682,
"text": null
},
{
"code": null,
"e": 25910,
"s": 25901,
"text": "Output :"
},
{
"code": null,
"e": 26133,
"s": 25914,
"text": "At times, you may need to convert your pandas dataframe to List. To accomplish this task, ‘ tolist() ‘ function can be used. Below is a basic example to use this function and convert the required DataFrame into a List."
},
{
"code": null,
"e": 26143,
"s": 26135,
"text": "Python3"
},
{
"code": "df.values.tolist()",
"e": 26162,
"s": 26143,
"text": null
},
{
"code": null,
"e": 26176,
"s": 26166,
"text": "Output : "
},
{
"code": null,
"e": 26238,
"s": 26178,
"text": "[['Tony', 35], ['Steve', 70], ['Bruce', 45], ['Peter', 20]]"
},
{
"code": null,
"e": 26309,
"s": 26240,
"text": "Here, Each inner list contains all the columns of a particular row. "
},
{
"code": null,
"e": 26448,
"s": 26311,
"text": "Pandas DataFrame can be converted into lists in multiple ways. Let’s have a look at different ways of converting a DataFrame one by one."
},
{
"code": null,
"e": 26540,
"s": 26450,
"text": "Method #1: Converting a DataFrame to List containing all the rows of a particular column:"
},
{
"code": null,
"e": 26550,
"s": 26542,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFrame df = pd.DataFrame(data) # Converting DataFrame to a list containing# all the rows of column 'Name'names = df['Name'].tolist() # Printing the converted list.print(names)",
"e": 26887,
"s": 26550,
"text": null
},
{
"code": null,
"e": 26900,
"s": 26891,
"text": "Output: "
},
{
"code": null,
"e": 26938,
"s": 26902,
"text": "['Tony', 'Steve', 'Bruce', 'Peter']"
},
{
"code": null,
"e": 27033,
"s": 26940,
"text": "Method #2: Converting a DataFrame to Nested List containing all the rows of all the columns:"
},
{
"code": null,
"e": 27043,
"s": 27035,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFramedf = pd.DataFrame(data) # Creating an empty listres=[] # Iterating through the columns of# dataframefor column in df.columns: # Storing the rows of a column # into a temporary list li = df[column].tolist() # appending the temporary list res.append(li) # Printing the final listprint(res)",
"e": 27526,
"s": 27043,
"text": null
},
{
"code": null,
"e": 27539,
"s": 27530,
"text": "Output: "
},
{
"code": null,
"e": 27597,
"s": 27541,
"text": "[['Tony', 'Steve', 'Bruce', 'Peter'], [35, 70, 45, 20]]"
},
{
"code": null,
"e": 27696,
"s": 27599,
"text": "Method #3: Converting a DataFrame to a list that contains lists having all the columns of a row."
},
{
"code": null,
"e": 27706,
"s": 27698,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFramedf = pd.DataFrame(data) # Converting dataframe to listli = df.values.tolist() # Printing listprint(li)",
"e": 27976,
"s": 27706,
"text": null
},
{
"code": null,
"e": 27989,
"s": 27980,
"text": "Output :"
},
{
"code": null,
"e": 28051,
"s": 27991,
"text": "[['Tony', 35], ['Steve', 70], ['Bruce', 45], ['Peter', 20]]"
},
{
"code": null,
"e": 28174,
"s": 28053,
"text": "Method #4: Converting a DataFrame to a list that contains lists having all the columns of a row along with column names."
},
{
"code": null,
"e": 28184,
"s": 28176,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating a dictionary to store datadata = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] , 'Age': [35, 70, 45, 20] } # Creating DataFramedf = pd.DataFrame(data) # Converting dataframe to listli = [df.columns.values.tolist()] + df.values.tolist() # Printing listprint(li)",
"e": 28485,
"s": 28184,
"text": null
},
{
"code": null,
"e": 28497,
"s": 28489,
"text": "Output:"
},
{
"code": null,
"e": 28576,
"s": 28499,
"text": "[[‘Name’, ‘Age’], [‘Tony’, 35], [‘Steve’, 70], [‘Bruce’, 45], [‘Peter’, 20]]"
},
{
"code": null,
"e": 28591,
"s": 28578,
"text": "simmytarika5"
},
{
"code": null,
"e": 28615,
"s": 28591,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28629,
"s": 28615,
"text": "Python-pandas"
},
{
"code": null,
"e": 28636,
"s": 28629,
"text": "Python"
},
{
"code": null,
"e": 28734,
"s": 28636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28766,
"s": 28734,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28808,
"s": 28766,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28850,
"s": 28808,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28906,
"s": 28850,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28933,
"s": 28906,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28964,
"s": 28933,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29003,
"s": 28964,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29032,
"s": 29003,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29054,
"s": 29032,
"text": "Defaultdict in Python"
}
] |
Select Drop-down list using select_by_index() in Selenium - Python - GeeksforGeeks
|
11 Oct, 2020
Prerequisite: Browser Automation Using Selenium
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we will be using Python.
Requirement:
You need to download install chrome driver from here Click Here and set path.
Working with Drop-down list:
Initially you have to import the Select class and afterward you have to make the case of Select class. After making the case of Select class, you can perform select strategies on that occasion to choose the choices from dropdown list.
Importing Select class:
from selenium.webdriver.support.ui import Select
For selection:
drop=Select(driver.find_element_by_id(' ')
drop.select_by_index()
Step-by-step approach:
Import webdriver from selenium module.
Python3
# Import required modulefrom selenium import webdriver
Import Select class module.
Python3
# Importing Select classfrom selenium.webdriver.support.ui import Select
Using a web page for drop down list(example: URL).
Navigate the id of option bar.
In html, index starts from 0. Here we will select index value 2 for id RESULT_RadioButton-9.
Python3
# Select by indexdrop.select_by_index(2)
Below is the complete program of the above approach:
Python3
# Import required moduleimport timefrom selenium import webdriver # Import Select classfrom selenium.webdriver.support.ui import Select # Using chrome driverdriver = webdriver.Chrome() # Web page urldriver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") # Find id of optionx = driver.find_element_by_id('RESULT_RadioButton-9')drop = Select(x) # Select by indexdrop.select_by_index(2)time.sleep(4)driver.close()
Output:
Python-selenium
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 25585,
"s": 25537,
"text": "Prerequisite: Browser Automation Using Selenium"
},
{
"code": null,
"e": 25839,
"s": 25585,
"text": "Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we will be using Python."
},
{
"code": null,
"e": 25852,
"s": 25839,
"text": "Requirement:"
},
{
"code": null,
"e": 25931,
"s": 25852,
"text": "You need to download install chrome driver from here Click Here and set path. "
},
{
"code": null,
"e": 25960,
"s": 25931,
"text": "Working with Drop-down list:"
},
{
"code": null,
"e": 26195,
"s": 25960,
"text": "Initially you have to import the Select class and afterward you have to make the case of Select class. After making the case of Select class, you can perform select strategies on that occasion to choose the choices from dropdown list."
},
{
"code": null,
"e": 26219,
"s": 26195,
"text": "Importing Select class:"
},
{
"code": null,
"e": 26269,
"s": 26219,
"text": "from selenium.webdriver.support.ui import Select\n"
},
{
"code": null,
"e": 26284,
"s": 26269,
"text": "For selection:"
},
{
"code": null,
"e": 26352,
"s": 26284,
"text": "drop=Select(driver.find_element_by_id(' ')\n\ndrop.select_by_index()\n"
},
{
"code": null,
"e": 26375,
"s": 26352,
"text": "Step-by-step approach:"
},
{
"code": null,
"e": 26414,
"s": 26375,
"text": "Import webdriver from selenium module."
},
{
"code": null,
"e": 26422,
"s": 26414,
"text": "Python3"
},
{
"code": "# Import required modulefrom selenium import webdriver",
"e": 26477,
"s": 26422,
"text": null
},
{
"code": null,
"e": 26505,
"s": 26477,
"text": "Import Select class module."
},
{
"code": null,
"e": 26513,
"s": 26505,
"text": "Python3"
},
{
"code": "# Importing Select classfrom selenium.webdriver.support.ui import Select",
"e": 26586,
"s": 26513,
"text": null
},
{
"code": null,
"e": 26637,
"s": 26586,
"text": "Using a web page for drop down list(example: URL)."
},
{
"code": null,
"e": 26668,
"s": 26637,
"text": "Navigate the id of option bar."
},
{
"code": null,
"e": 26761,
"s": 26668,
"text": "In html, index starts from 0. Here we will select index value 2 for id RESULT_RadioButton-9."
},
{
"code": null,
"e": 26769,
"s": 26761,
"text": "Python3"
},
{
"code": "# Select by indexdrop.select_by_index(2)",
"e": 26810,
"s": 26769,
"text": null
},
{
"code": null,
"e": 26863,
"s": 26810,
"text": "Below is the complete program of the above approach:"
},
{
"code": null,
"e": 26871,
"s": 26863,
"text": "Python3"
},
{
"code": "# Import required moduleimport timefrom selenium import webdriver # Import Select classfrom selenium.webdriver.support.ui import Select # Using chrome driverdriver = webdriver.Chrome() # Web page urldriver.get(\"https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407\") # Find id of optionx = driver.find_element_by_id('RESULT_RadioButton-9')drop = Select(x) # Select by indexdrop.select_by_index(2)time.sleep(4)driver.close()",
"e": 27321,
"s": 26871,
"text": null
},
{
"code": null,
"e": 27329,
"s": 27321,
"text": "Output:"
},
{
"code": null,
"e": 27345,
"s": 27329,
"text": "Python-selenium"
},
{
"code": null,
"e": 27352,
"s": 27345,
"text": "Python"
},
{
"code": null,
"e": 27450,
"s": 27352,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27482,
"s": 27450,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27524,
"s": 27482,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27566,
"s": 27524,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27593,
"s": 27566,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27649,
"s": 27593,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27671,
"s": 27649,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27710,
"s": 27671,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27741,
"s": 27710,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27770,
"s": 27741,
"text": "Create a directory in Python"
}
] |
Kotlin mutableMapOf() - GeeksforGeeks
|
17 May, 2021
Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.For using the MutableMap interface we need to use functions as shown below
mutableMapOf() or mutableMapOf <K, V>()
For declaring MutableMap Interface
interface MutableMap<K, V> : Map<K, V> (source)
Java
fun main(args: Array<String>) { val items = mutableMapOf("Box" to 12, "Books" to 18, "Table" to 13) println("Entries: " + items.entries) //Printing Entries println("Keys:" + items.keys) //Printing Keys println("Values:" + items.values) //Printing Values}
Output:
Entries: [Box=12, Books=18, Table=13]
Keys:[Box, Books, Table]
Values:[12, 18, 13]
We can determine the size of mutable map using two methods. By using the size property of the map and by using the count() method.
Java
fun main(args : Array<String>) { val ranks = mutableMapOf(1 to "India",2 to "Australia", 3 to "England",4 to "Africa") //method 1 println("The size of the mutablemap is: "+ranks.size) //method 2 println("The size of the mutablemap is: "+ranks.count())}
Output:
The size of the mutablemap is: 4
The size of the mutablemap is: 4
We can retrieve values from a mutable map using different methods discussed in the below program.
Java
fun main() { val ranks = mutableMapOf(1 to "India",2 to "Australia", 3 to "England",4 to "Africa") //method 1 println("Team having rank #1 is: "+ranks[1]) //method 2 println("Team having rank #3 is: "+ranks.getValue(3)) //method 3 println("Team having rank #4 is: "+ranks.getOrDefault(4, 0)) // method 4 val team = ranks.getOrElse(2 ,{ 0 }) println(team)}
Output:
Team having rank #1 is: India
Team having rank #3 is: England
Team having rank #4 is: Africa
Australia
The put() and putAll() function is used to add elements in the MutableMap.put() function adds single element at time while putAll() function can be used to add multiple element at a time in MutableMap.Kotlin program of using put() and putAll() function –
Java
fun main(args: Array<String>) { val mutableMap = mutableMapOf<String, String>() mutableMap.put("Name", "Geek") mutableMap.put("Country", "India") val map = mapOf<String,String>("Department" to "Computer Science", "Hobby" to "Coding") println("<----Traverse mutableMap---->") for (key in mutableMap.keys) { println("Key = "+key +", "+"Value = "+mutableMap[key]) } mutableMap.putAll(map) println("<----Traversal after putting hashmap---->") for (key in mutableMap.keys) { println("Key = "+key +", "+"Value = "+mutableMap[key]) }}
Output:
<----Traverse mutableMap---->
Key = Name, Value = Geek
Key = Country, Value = India
<----Traversal after putting hashmap---->
Key = Name, Value = Geek
Key = Country, Value = India
Key = Department, Value = Computer Science
Key = Hobby, Value = Coding
Function remove(key) is used to remove value which corresponds to its mentioned key. Function remove(key, value) is used to remove elements containing keys and valuesKotlin program to demonstrate remove() function –
Java
fun main(args: Array<String>) { val mutableMap = mutableMapOf<String, String>() mutableMap.put("Name", "Geek") mutableMap.put("Company", "GeeksforGeeks") mutableMap.put("Country", "India") for (key in mutableMap.keys) { println("Key = ${key}, Value = ${mutableMap[key]}") } println() println("Remove the Key: "+mutableMap.remove("Country")) println() println("Is pair removes from the map: " +mutableMap.remove("Company","GeeksforGeeks")) println() println("<---Traverse Again--->") for (key in mutableMap.keys) { println("Key = ${key}, Value = ${mutableMap[key]}") }}
Output:
Key = Name, Value = Geek
Key = Company, Value = GeeksforGeeks
Key = Country, Value = India
Remove the Key: India
Is pair removes from the map: true
<---Traverse Again--->
Key = Name, Value = Geek
Used to remove all the element from the mutableMap.Kotlin program of using clear() function –
Java
fun main(args: Array<String>) { val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>() mutableMap.put("Name", "Geek") mutableMap.put("Company", "GeeksforGeeks") for (key in mutableMap.keys) { println("Key = ${key}, Value = ${mutableMap[key]}") } println("mutableMap.clear()") println("Method called to clear the map: "+mutableMap.clear()) println("Map Empty: "+mutableMap)}
Output:
Key = Name, Value = Geek
Key = Company, Value = GeeksforGeeks
mutableMap.clear()
Method called to clear the map: kotlin.Unit
Map Empty: {}
Traversing means traveling through every node in the data structures like Linked List, Arrays, Trees, etc. It just means that traveling to every node at least once to display it to the user or perform an operation on it. To understand this let’s take an example below Kotlin program to demonstrate the traversal –
Java
fun main(args: Array<String>) { //Declaring function //Creating MutableMap of different types val mutableMap = mutableMapOf(1 to "Aditya", 4 to "Vilas", 2 to "Manish", 3 to "Manjot") for (key in mutableMap.keys) { println("Key = ${key}, Value = ${mutableMap[key]}") }}
Output:
Key = 1, Value = Aditya
Key = 4, Value = Vilas
Key = 2, Value = Manish
Key = 3, Value = Manjot
shubham_singh
saurabh1990aror
Kotlin Collections
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Add and Customize Back Button of Action Bar in Android?
How to Get Current Location in Android?
Kotlin Setters and Getters
How to Change the Color of Status Bar in an Android App?
Kotlin Android Tutorial
Kotlin when expression
|
[
{
"code": null,
"e": 25172,
"s": 25144,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 25534,
"s": 25172,
"text": "Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.For using the MutableMap interface we need to use functions as shown below "
},
{
"code": null,
"e": 25574,
"s": 25534,
"text": "mutableMapOf() or mutableMapOf <K, V>()"
},
{
"code": null,
"e": 25610,
"s": 25574,
"text": "For declaring MutableMap Interface "
},
{
"code": null,
"e": 25658,
"s": 25610,
"text": "interface MutableMap<K, V> : Map<K, V> (source)"
},
{
"code": null,
"e": 25667,
"s": 25662,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { val items = mutableMapOf(\"Box\" to 12, \"Books\" to 18, \"Table\" to 13) println(\"Entries: \" + items.entries) //Printing Entries println(\"Keys:\" + items.keys) //Printing Keys println(\"Values:\" + items.values) //Printing Values}",
"e": 25963,
"s": 25667,
"text": null
},
{
"code": null,
"e": 25973,
"s": 25963,
"text": "Output: "
},
{
"code": null,
"e": 26056,
"s": 25973,
"text": "Entries: [Box=12, Books=18, Table=13]\nKeys:[Box, Books, Table]\nValues:[12, 18, 13]"
},
{
"code": null,
"e": 26191,
"s": 26058,
"text": "We can determine the size of mutable map using two methods. By using the size property of the map and by using the count() method. "
},
{
"code": null,
"e": 26196,
"s": 26191,
"text": "Java"
},
{
"code": "fun main(args : Array<String>) { val ranks = mutableMapOf(1 to \"India\",2 to \"Australia\", 3 to \"England\",4 to \"Africa\") //method 1 println(\"The size of the mutablemap is: \"+ranks.size) //method 2 println(\"The size of the mutablemap is: \"+ranks.count())}",
"e": 26472,
"s": 26196,
"text": null
},
{
"code": null,
"e": 26482,
"s": 26472,
"text": "Output: "
},
{
"code": null,
"e": 26548,
"s": 26482,
"text": "The size of the mutablemap is: 4\nThe size of the mutablemap is: 4"
},
{
"code": null,
"e": 26650,
"s": 26550,
"text": "We can retrieve values from a mutable map using different methods discussed in the below program. "
},
{
"code": null,
"e": 26655,
"s": 26650,
"text": "Java"
},
{
"code": "fun main() { val ranks = mutableMapOf(1 to \"India\",2 to \"Australia\", 3 to \"England\",4 to \"Africa\") //method 1 println(\"Team having rank #1 is: \"+ranks[1]) //method 2 println(\"Team having rank #3 is: \"+ranks.getValue(3)) //method 3 println(\"Team having rank #4 is: \"+ranks.getOrDefault(4, 0)) // method 4 val team = ranks.getOrElse(2 ,{ 0 }) println(team)}",
"e": 27051,
"s": 26655,
"text": null
},
{
"code": null,
"e": 27061,
"s": 27051,
"text": "Output: "
},
{
"code": null,
"e": 27164,
"s": 27061,
"text": "Team having rank #1 is: India\nTeam having rank #3 is: England\nTeam having rank #4 is: Africa\nAustralia"
},
{
"code": null,
"e": 27423,
"s": 27166,
"text": "The put() and putAll() function is used to add elements in the MutableMap.put() function adds single element at time while putAll() function can be used to add multiple element at a time in MutableMap.Kotlin program of using put() and putAll() function – "
},
{
"code": null,
"e": 27428,
"s": 27423,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { val mutableMap = mutableMapOf<String, String>() mutableMap.put(\"Name\", \"Geek\") mutableMap.put(\"Country\", \"India\") val map = mapOf<String,String>(\"Department\" to \"Computer Science\", \"Hobby\" to \"Coding\") println(\"<----Traverse mutableMap---->\") for (key in mutableMap.keys) { println(\"Key = \"+key +\", \"+\"Value = \"+mutableMap[key]) } mutableMap.putAll(map) println(\"<----Traversal after putting hashmap---->\") for (key in mutableMap.keys) { println(\"Key = \"+key +\", \"+\"Value = \"+mutableMap[key]) }}",
"e": 28012,
"s": 27428,
"text": null
},
{
"code": null,
"e": 28022,
"s": 28012,
"text": "Output: "
},
{
"code": null,
"e": 28273,
"s": 28022,
"text": "<----Traverse mutableMap---->\nKey = Name, Value = Geek\nKey = Country, Value = India\n<----Traversal after putting hashmap---->\nKey = Name, Value = Geek\nKey = Country, Value = India\nKey = Department, Value = Computer Science\nKey = Hobby, Value = Coding"
},
{
"code": null,
"e": 28493,
"s": 28275,
"text": "Function remove(key) is used to remove value which corresponds to its mentioned key. Function remove(key, value) is used to remove elements containing keys and valuesKotlin program to demonstrate remove() function – "
},
{
"code": null,
"e": 28498,
"s": 28493,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { val mutableMap = mutableMapOf<String, String>() mutableMap.put(\"Name\", \"Geek\") mutableMap.put(\"Company\", \"GeeksforGeeks\") mutableMap.put(\"Country\", \"India\") for (key in mutableMap.keys) { println(\"Key = ${key}, Value = ${mutableMap[key]}\") } println() println(\"Remove the Key: \"+mutableMap.remove(\"Country\")) println() println(\"Is pair removes from the map: \" +mutableMap.remove(\"Company\",\"GeeksforGeeks\")) println() println(\"<---Traverse Again--->\") for (key in mutableMap.keys) { println(\"Key = ${key}, Value = ${mutableMap[key]}\") }}",
"e": 29136,
"s": 28498,
"text": null
},
{
"code": null,
"e": 29146,
"s": 29136,
"text": "Output: "
},
{
"code": null,
"e": 29345,
"s": 29146,
"text": "Key = Name, Value = Geek\nKey = Company, Value = GeeksforGeeks\nKey = Country, Value = India\n\nRemove the Key: India\n\nIs pair removes from the map: true\n\n<---Traverse Again--->\nKey = Name, Value = Geek"
},
{
"code": null,
"e": 29443,
"s": 29347,
"text": "Used to remove all the element from the mutableMap.Kotlin program of using clear() function – "
},
{
"code": null,
"e": 29448,
"s": 29443,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>() mutableMap.put(\"Name\", \"Geek\") mutableMap.put(\"Company\", \"GeeksforGeeks\") for (key in mutableMap.keys) { println(\"Key = ${key}, Value = ${mutableMap[key]}\") } println(\"mutableMap.clear()\") println(\"Method called to clear the map: \"+mutableMap.clear()) println(\"Map Empty: \"+mutableMap)}",
"e": 29877,
"s": 29448,
"text": null
},
{
"code": null,
"e": 29887,
"s": 29877,
"text": "Output: "
},
{
"code": null,
"e": 30026,
"s": 29887,
"text": "Key = Name, Value = Geek\nKey = Company, Value = GeeksforGeeks\nmutableMap.clear()\nMethod called to clear the map: kotlin.Unit\nMap Empty: {}"
},
{
"code": null,
"e": 30344,
"s": 30028,
"text": "Traversing means traveling through every node in the data structures like Linked List, Arrays, Trees, etc. It just means that traveling to every node at least once to display it to the user or perform an operation on it. To understand this let’s take an example below Kotlin program to demonstrate the traversal – "
},
{
"code": null,
"e": 30349,
"s": 30344,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { //Declaring function //Creating MutableMap of different types val mutableMap = mutableMapOf(1 to \"Aditya\", 4 to \"Vilas\", 2 to \"Manish\", 3 to \"Manjot\") for (key in mutableMap.keys) { println(\"Key = ${key}, Value = ${mutableMap[key]}\") }}",
"e": 30654,
"s": 30349,
"text": null
},
{
"code": null,
"e": 30664,
"s": 30654,
"text": "Output: "
},
{
"code": null,
"e": 30759,
"s": 30664,
"text": "Key = 1, Value = Aditya\nKey = 4, Value = Vilas\nKey = 2, Value = Manish\nKey = 3, Value = Manjot"
},
{
"code": null,
"e": 30775,
"s": 30761,
"text": "shubham_singh"
},
{
"code": null,
"e": 30791,
"s": 30775,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 30810,
"s": 30791,
"text": "Kotlin Collections"
},
{
"code": null,
"e": 30817,
"s": 30810,
"text": "Picked"
},
{
"code": null,
"e": 30824,
"s": 30817,
"text": "Kotlin"
},
{
"code": null,
"e": 30922,
"s": 30824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30965,
"s": 30922,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 30996,
"s": 30965,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 31038,
"s": 30996,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 31080,
"s": 31038,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31143,
"s": 31080,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 31183,
"s": 31143,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 31210,
"s": 31183,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 31267,
"s": 31210,
"text": "How to Change the Color of Status Bar in an Android App?"
},
{
"code": null,
"e": 31291,
"s": 31267,
"text": "Kotlin Android Tutorial"
}
] |
Merge K sorted linked lists | Set 1 - GeeksforGeeks
|
23 Feb, 2022
Given K sorted linked lists of size N each, merge them and print the sorted output.
Examples:
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL
Output: 0->1->2->3->4->5->6->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Input: k = 3, n = 3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL
Output: 1->2->3->4->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Method 1 (Simple)
Approach: A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into result in a sorted way.
C++
Java
Python3
C#
Javascript
// C++ program to merge k sorted// arrays of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // The main function that// takes an array of lists// arr[0..last] and generates// the sorted outputNode* mergeKLists(Node* arr[], int last){ // Traverse form second list to last for (int i = 1; i <= last; i++) { while (true) { // head of both the lists, // 0 and ith list. Node *head_0 = arr[0], *head_i = arr[i]; // Break if list ended if (head_i == NULL) break; // Smaller than first element if (head_0->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0; arr[0] = head_i; } else // Traverse the first list while (head_0->next != NULL) { // Smaller than next element if (head_0->next->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0->next; head_0->next = head_i; break; } // go to next node head_0 = head_0->next; // if last node if (head_0->next == NULL) { arr[i] = head_i->next; head_i->next = NULL; head_0->next = head_i; head_0->next->next = NULL; break; } } } } return arr[0];} // Utility function to create a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver program to test// above functionsint main(){ // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // an array of pointers storing the // head nodes of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}
// Java program to merge k sorted// arrays of size n eachimport java.io.*; // A Linked List nodeclass Node{ int data; Node next; // Utility function to create a new node. Node(int key) { data = key; next = null; }}class GFG { static Node head; static Node temp; /* Function to print nodes in a given linked list */ static void printList(Node node) { while(node != null) { System.out.print(node.data + " "); node = node.next; } System.out.println(); } // The main function that // takes an array of lists // arr[0..last] and generates // the sorted output static Node mergeKLists(Node arr[], int last) { // Traverse form second list to last for (int i = 1; i <= last; i++) { while(true) { // head of both the lists, // 0 and ith list. Node head_0 = arr[0]; Node head_i = arr[i]; // Break if list ended if (head_i == null) break; // Smaller than first element if(head_0.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0; arr[0] = head_i; } else { // Traverse the first list while (head_0.next != null) { // Smaller than next element if (head_0.next.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0.next; head_0.next = head_i; break; } // go to next node head_0 = head_0.next; // if last node if (head_0.next == null) { arr[i] = head_i.next; head_i.next = null; head_0.next = head_i; head_0.next.next = null; break; } } } } } return arr[0]; } // Driver program to test // above functions public static void main (String[] args) { // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // an array of pointers storing the // head nodes of the linked lists Node[] arr = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists head = mergeKLists(arr, k - 1); printList(head); }} // This code is contributed by avanitrachhadiya2155
# Python3 program to merge k# sorted arrays of size n each # A Linked List nodeclass Node: def __init__(self, x): self.data = x self.next = None # Function to print nodes in# a given linked listdef printList(node): while (node != None): print(node.data, end = " ") node = node.next # The main function that# takes an array of lists# arr[0..last] and generates# the sorted outputdef mergeKLists(arr, last): # Traverse form second # list to last for i in range(1, last + 1): while (True): # head of both the lists, # 0 and ith list. head_0 = arr[0] head_i = arr[i] # Break if list ended if (head_i == None): break # Smaller than first # element if (head_0.data >= head_i.data): arr[i] = head_i.next head_i.next = head_0 arr[0] = head_i else: # Traverse the first list while (head_0.next != None): # Smaller than next # element if (head_0.next.data >= head_i.data): arr[i] = head_i.next head_i.next = head_0.next head_0.next = head_i break # go to next node head_0 = head_0.next # if last node if (head_0.next == None): arr[i] = head_i.next head_i.next = None head_0.next = head_i head_0.next.next = None break return arr[0] # Driver codeif __name__ == '__main__': # Number of linked # lists k = 3 # Number of elements # in each list n = 4 # an array of pointers # storing the head nodes # of the linked lists arr = [None for i in range(k)] arr[0] = Node(1) arr[0].next = Node(3) arr[0].next.next = Node(5) arr[0].next.next.next = Node(7) arr[1] = Node(2) arr[1].next = Node(4) arr[1].next.next = Node(6) arr[1].next.next.next = Node(8) arr[2] = Node(0) arr[2].next = Node(9) arr[2].next.next = Node(10) arr[2].next.next.next = Node(11) # Merge all lists head = mergeKLists(arr, k - 1) printList(head) # This code is contributed by Mohit Kumar 29
// C# program to merge k sorted// arrays of size n eachusing System; // A Linked List nodepublic class Node{ public int data; public Node next; // Utility function to create a new node. public Node(int key) { data = key; next = null; }} public class GFG{ static Node head; /* Function to print nodes in a given linked list */ static void printList(Node node) { while(node != null) { Console.Write(node.data + " "); node = node.next; } Console.WriteLine(); } // The main function that // takes an array of lists // arr[0..last] and generates // the sorted output static Node mergeKLists(Node[] arr, int last) { // Traverse form second list to last for (int i = 1; i <= last; i++) { while(true) { // head of both the lists, // 0 and ith list. Node head_0 = arr[0]; Node head_i = arr[i]; // Break if list ended if (head_i == null) break; // Smaller than first element if(head_0.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0; arr[0] = head_i; } else { // Traverse the first list while (head_0.next != null) { // Smaller than next element if (head_0.next.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0.next; head_0.next = head_i; break; } // go to next node head_0 = head_0.next; // if last node if (head_0.next == null) { arr[i] = head_i.next; head_i.next = null; head_0.next = head_i; head_0.next.next = null; break; } } } } } return arr[0]; } static public void Main () { // Number of linked lists int k = 3; // an array of pointers storing the // head nodes of the linked lists Node[] arr = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists head = mergeKLists(arr, k - 1); printList(head); }} // This code is contributed by rag2127
<script>// Javascript program to merge k sorted// arrays of size n each // A Linked List node class Node { // Utility function to create a new node. constructor(key) { this.data=key; this.next=null; } } let head; let temp; /* Function to print nodes ina given linked list */function printList(node){ while(node != null) { document.write(node.data + " "); node = node.next; } document.write("<br>"); } // The main function that// takes an array of lists// arr[0..last] and generates// the sorted outputfunction mergeKLists(arr,last){ // Traverse form second list to last for (let i = 1; i <= last; i++) { while(true) { // head of both the lists, // 0 and ith list. let head_0 = arr[0]; let head_i = arr[i]; // Break if list ended if (head_i == null) break; // Smaller than first element if(head_0.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0; arr[0] = head_i; } else { // Traverse the first list while (head_0.next != null) { // Smaller than next element if (head_0.next.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0.next; head_0.next = head_i; break; } // go to next node head_0 = head_0.next; // if last node if (head_0.next == null) { arr[i] = head_i.next; head_i.next = null; head_0.next = head_i; head_0.next.next = null; break; } } } } } return arr[0];} // Driver program to test// above functions// Number of linked listslet k = 3;// Number of elements in each listlet n = 4;// an array of pointers storing the// head nodes of the linked listslet arr = new Array(k);arr[0] = new Node(1);arr[0].next = new Node(3);arr[0].next.next = new Node(5);arr[0].next.next.next = new Node(7); arr[1] = new Node(2);arr[1].next = new Node(4);arr[1].next.next = new Node(6);arr[1].next.next.next = new Node(8); arr[2] = new Node(0);arr[2].next = new Node(9);arr[2].next.next = new Node(10);arr[2].next.next.next = new Node(11); // Merge all listshead = mergeKLists(arr, k - 1);printList(head); // This code is contributed by unknown2108 </script>
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
Time complexity: O(nk2)
Auxiliary Space: O(1). As no extra space is required.
Method 2: Min Heap. A Better solution is to use Min Heap-based solution which is discussed here for arrays. The time complexity of this solution would be O(nk Log k) Method 3: Divide and Conquer. In this post, Divide and Conquer approach is discussed. This approach doesn’t require extra space for heap and works in O(nk Log k)It is known that merging of two linked lists can be done in O(n) time and O(n) space.
The idea is to pair up K lists and merge each pair in linear time using O(n) space.After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.Repeat the procedure until we have only one list left.
The idea is to pair up K lists and merge each pair in linear time using O(n) space.
After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.
Repeat the procedure until we have only one list left.
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// C++ program to merge k sorted// arrays of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(n) extra space for recursive calls, */Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; /* Base cases */ if (a == NULL) return (b); else if (b == NULL) return (a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return result;} // The main function that takes an array of lists// arr[0..last] and generates the sorted outputNode* mergeKLists(Node* arr[], int last){ // repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++, j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0];} // Utility function to create a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver program to test above functionsint main(){ int k = 3; // Number of linked lists int n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}
// Java program to merge k sorted arrays of size n eachpublic class MergeKSortedLists { /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(Log n) extra space for recursive calls, but it can be easily modified to work with same time and O(1) extra space */ public static Node SortedMerge(Node a, Node b) { Node result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.next = SortedMerge(a.next, b); } else { result = b; result.next = SortedMerge(a, b.next); } return result; } // The main function that takes an array of lists // arr[0..last] and generates the sorted output public static Node mergeKLists(Node arr[], int last) { // repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++; j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0]; } /* Function to print nodes in a given linked list */ public static void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String args[]) { int k = 3; // Number of linked lists int n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked lists Node arr[] = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists Node head = mergeKLists(arr, k - 1); printList(head); }} class Node { int data; Node next; Node(int data) { this.data = data; }}// This code is contributed by Gaurav Tiwari
# Python3 program to merge k sorted# arrays of size n each # A Linked List nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to print nodes in a# given linked listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next # Takes two lists sorted in increasing order,# and merge their nodes together to make one# big sorted list. Below function takes# O(Log n) extra space for recursive calls,# but it can be easily modified to work with# same time and O(1) extra spacedef SortedMerge(a, b): result = None # Base cases if (a == None): return(b) elif (b == None): return(a) # Pick either a or b, and recur if (a.data <= b.data): result = a result.next = SortedMerge(a.next, b) else: result = b result.next = SortedMerge(a, b.next) return result # The main function that takes an array of lists# arr[0..last] and generates the sorted outputdef mergeKLists(arr, last): # Repeat until only one list is left while (last != 0): i = 0 j = last # (i, j) forms a pair while (i < j): # Merge List i with List j and store # merged list in List i arr[i] = SortedMerge(arr[i], arr[j]) # Consider next pair i += 1 j -= 1 # If all pairs are merged, update last if (i >= j): last = j return arr[0] # Utility function to create a new node.def newNode(data): temp = Node() temp.data = data temp.next = None return temp # Driver codeif __name__=='__main__': # Number of linked lists k = 3 # Number of elements in each list n = 4 # An array of pointers storing the # head nodes of the linked lists arr = [0 for i in range(k)] arr[0] = newNode(1) arr[0].next = newNode(3) arr[0].next.next = newNode(5) arr[0].next.next.next = newNode(7) arr[1] = newNode(2) arr[1].next = newNode(4) arr[1].next.next = newNode(6) arr[1].next.next.next = newNode(8) arr[2] = newNode(0) arr[2].next = newNode(9) arr[2].next.next = newNode(10) arr[2].next.next.next = newNode(11) # Merge all lists head = mergeKLists(arr, k - 1) printList(head) # This code is contributed by rutvik_56
// C# program to merge k sorted arrays of size n eachusing System; public class MergeKSortedLists { /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(Log n) extra space for recursive calls, but it can be easily modified to work with same time and O(1) extra space */ public static Node SortedMerge(Node a, Node b) { Node result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.next = SortedMerge(a.next, b); } else { result = b; result.next = SortedMerge(a, b.next); } return result; } // The main function that takes // an array of lists arr[0..last] // and generates the sorted output public static Node mergeKLists(Node[] arr, int last) { // repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++; j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0]; } /* Function to print nodes in a given linked list */ public static void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } public static void Main() { int k = 3; // Number of linked lists //int n = 4; // Number of elements in each list // An array of pointers storing the head nodes // of the linked lists Node[] arr = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists Node head = mergeKLists(arr, k - 1); printList(head); }} public class Node { public int data; public Node next; public Node(int data) { this.data = data; }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program to merge k sorted// arrays of size n eachclass Node { constructor(val) { this.data = val; this.next = null; }} /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(Log n) extra space for * recursive calls, but it can be easily modified to work with same time and * O(1) extra space */ function SortedMerge(a, b) {var result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.next = SortedMerge(a.next, b); } else { result = b; result.next = SortedMerge(a, b.next); } return result; } // The main function that takes an array of lists // arr[0..last] and generates the sorted output function mergeKLists(arr , last) { // repeat until only one list is left while (last != 0) { var i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++; j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0]; } /* Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } var k = 3; // Number of linked lists var n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked listsvar arr = Array(k); arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all listsvar head = mergeKLists(arr, k - 1); printList(head); // This code contributed by gauravrajput1 </script>
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
Assuming N(n*k) is the total number of nodes, n is the size of each linked list, and k is the total number of linked lists.
Time Complexity: O(N*log k) or O(n*k*log k)As outer while loop in function mergeKLists() runs log k times and every time it processes n*k elements.
Auxiliary Space: O(N) or O(n*k)Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made.
Merge k sorted linked lists | Set 2 (Using Min Heap)
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Method 4: Selecting min of top element iteratively
The time complexity of this solution would be O(n*k) and the space complexity of this solution would be O(n)
Approach :
Select the minimum of top elements iteratively store that in a new node and increment the pointer of the minimum element .
Code :
C++
// C++ program to merge k sorted arrays of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node{ int data; Node* next; Node(int x) { data = x; next = NULL; }}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } cout << endl;} /*Linked list Node structure struct Node{int data;Node* next;Node(int x){ data = x; next = NULL;}};*/ class Solution{public: // Function to merge K sorted linked list. Node* mergeKLists(Node* arr[], int K) { Node* head = NULL; while (1) { int a = 0; int z; Node* curr; int min = INT_MAX; for (int i = 0; i < K; i++) { if (arr[i] != NULL) { a++; if (arr[i]->data < min) { min = arr[i]->data; z = i; } } } if (a != 0) { arr[z] = arr[z]->next; Node* temp = new Node(min); if (head == NULL) { head = temp; curr = temp; } else { curr->next = temp; curr = temp; } } else { return head; } } }}; // { Driver Code Starts. // Driver program to test above functionsint main(){ int t; cin >> t; while (t--) { int N; cin >> N; struct Node* arr[N]; for (int j = 0; j < N; j++) { int n; cin >> n; int x; cin >> x; arr[j] = new Node(x); Node* curr = arr[j]; n--; for (int i = 0; i < n; i++) { cin >> x; Node* temp = new Node(x); curr->next = temp; curr = temp; } } Solution obj; Node* res = obj.mergeKLists(arr, N); printList(res); } return 0;} // } Driver Code Ends
_Gaurav_Tiwari
princiraj1992
sachinhaldavanekar
andrew1234
mohit kumar 29
rutvik_56
avanitrachhadiya2155
rag2127
mittulmandhan
unknown2108
GauravRajput1
rohitguptaiem
simranarora5sos
singhashwani2002
Adarsh Kumar
Amazon
Merge Sort
VMWare
Heap
Linked List
VMWare
Amazon
Linked List
Heap
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Insertion and Deletion in Heaps
Max Heap in Java
Priority Queue in Python
Priority Queue using Binary Heap
Median in a stream of integers (running integers)
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
|
[
{
"code": null,
"e": 25837,
"s": 25809,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 25921,
"s": 25837,
"text": "Given K sorted linked lists of size N each, merge them and print the sorted output."
},
{
"code": null,
"e": 25932,
"s": 25921,
"text": "Examples: "
},
{
"code": null,
"e": 26385,
"s": 25932,
"text": "Input: k = 3, n = 4\nlist1 = 1->3->5->7->NULL\nlist2 = 2->4->6->8->NULL\nlist3 = 0->9->10->11->NULL\n\nOutput: 0->1->2->3->4->5->6->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element.\n\nInput: k = 3, n = 3\nlist1 = 1->3->7->NULL\nlist2 = 2->4->8->NULL\nlist3 = 9->10->11->NULL\n\nOutput: 1->2->3->4->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element."
},
{
"code": null,
"e": 26404,
"s": 26385,
"text": "Method 1 (Simple) "
},
{
"code": null,
"e": 26614,
"s": 26404,
"text": "Approach: A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into result in a sorted way. "
},
{
"code": null,
"e": 26618,
"s": 26614,
"text": "C++"
},
{
"code": null,
"e": 26623,
"s": 26618,
"text": "Java"
},
{
"code": null,
"e": 26631,
"s": 26623,
"text": "Python3"
},
{
"code": null,
"e": 26634,
"s": 26631,
"text": "C#"
},
{
"code": null,
"e": 26645,
"s": 26634,
"text": "Javascript"
},
{
"code": "// C++ program to merge k sorted// arrays of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // The main function that// takes an array of lists// arr[0..last] and generates// the sorted outputNode* mergeKLists(Node* arr[], int last){ // Traverse form second list to last for (int i = 1; i <= last; i++) { while (true) { // head of both the lists, // 0 and ith list. Node *head_0 = arr[0], *head_i = arr[i]; // Break if list ended if (head_i == NULL) break; // Smaller than first element if (head_0->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0; arr[0] = head_i; } else // Traverse the first list while (head_0->next != NULL) { // Smaller than next element if (head_0->next->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0->next; head_0->next = head_i; break; } // go to next node head_0 = head_0->next; // if last node if (head_0->next == NULL) { arr[i] = head_i->next; head_i->next = NULL; head_0->next = head_i; head_0->next->next = NULL; break; } } } } return arr[0];} // Utility function to create a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver program to test// above functionsint main(){ // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // an array of pointers storing the // head nodes of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}",
"e": 29433,
"s": 26645,
"text": null
},
{
"code": "// Java program to merge k sorted// arrays of size n eachimport java.io.*; // A Linked List nodeclass Node{ int data; Node next; // Utility function to create a new node. Node(int key) { data = key; next = null; }}class GFG { static Node head; static Node temp; /* Function to print nodes in a given linked list */ static void printList(Node node) { while(node != null) { System.out.print(node.data + \" \"); node = node.next; } System.out.println(); } // The main function that // takes an array of lists // arr[0..last] and generates // the sorted output static Node mergeKLists(Node arr[], int last) { // Traverse form second list to last for (int i = 1; i <= last; i++) { while(true) { // head of both the lists, // 0 and ith list. Node head_0 = arr[0]; Node head_i = arr[i]; // Break if list ended if (head_i == null) break; // Smaller than first element if(head_0.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0; arr[0] = head_i; } else { // Traverse the first list while (head_0.next != null) { // Smaller than next element if (head_0.next.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0.next; head_0.next = head_i; break; } // go to next node head_0 = head_0.next; // if last node if (head_0.next == null) { arr[i] = head_i.next; head_i.next = null; head_0.next = head_i; head_0.next.next = null; break; } } } } } return arr[0]; } // Driver program to test // above functions public static void main (String[] args) { // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // an array of pointers storing the // head nodes of the linked lists Node[] arr = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists head = mergeKLists(arr, k - 1); printList(head); }} // This code is contributed by avanitrachhadiya2155",
"e": 32116,
"s": 29433,
"text": null
},
{
"code": "# Python3 program to merge k# sorted arrays of size n each # A Linked List nodeclass Node: def __init__(self, x): self.data = x self.next = None # Function to print nodes in# a given linked listdef printList(node): while (node != None): print(node.data, end = \" \") node = node.next # The main function that# takes an array of lists# arr[0..last] and generates# the sorted outputdef mergeKLists(arr, last): # Traverse form second # list to last for i in range(1, last + 1): while (True): # head of both the lists, # 0 and ith list. head_0 = arr[0] head_i = arr[i] # Break if list ended if (head_i == None): break # Smaller than first # element if (head_0.data >= head_i.data): arr[i] = head_i.next head_i.next = head_0 arr[0] = head_i else: # Traverse the first list while (head_0.next != None): # Smaller than next # element if (head_0.next.data >= head_i.data): arr[i] = head_i.next head_i.next = head_0.next head_0.next = head_i break # go to next node head_0 = head_0.next # if last node if (head_0.next == None): arr[i] = head_i.next head_i.next = None head_0.next = head_i head_0.next.next = None break return arr[0] # Driver codeif __name__ == '__main__': # Number of linked # lists k = 3 # Number of elements # in each list n = 4 # an array of pointers # storing the head nodes # of the linked lists arr = [None for i in range(k)] arr[0] = Node(1) arr[0].next = Node(3) arr[0].next.next = Node(5) arr[0].next.next.next = Node(7) arr[1] = Node(2) arr[1].next = Node(4) arr[1].next.next = Node(6) arr[1].next.next.next = Node(8) arr[2] = Node(0) arr[2].next = Node(9) arr[2].next.next = Node(10) arr[2].next.next.next = Node(11) # Merge all lists head = mergeKLists(arr, k - 1) printList(head) # This code is contributed by Mohit Kumar 29",
"e": 34609,
"s": 32116,
"text": null
},
{
"code": "// C# program to merge k sorted// arrays of size n eachusing System; // A Linked List nodepublic class Node{ public int data; public Node next; // Utility function to create a new node. public Node(int key) { data = key; next = null; }} public class GFG{ static Node head; /* Function to print nodes in a given linked list */ static void printList(Node node) { while(node != null) { Console.Write(node.data + \" \"); node = node.next; } Console.WriteLine(); } // The main function that // takes an array of lists // arr[0..last] and generates // the sorted output static Node mergeKLists(Node[] arr, int last) { // Traverse form second list to last for (int i = 1; i <= last; i++) { while(true) { // head of both the lists, // 0 and ith list. Node head_0 = arr[0]; Node head_i = arr[i]; // Break if list ended if (head_i == null) break; // Smaller than first element if(head_0.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0; arr[0] = head_i; } else { // Traverse the first list while (head_0.next != null) { // Smaller than next element if (head_0.next.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0.next; head_0.next = head_i; break; } // go to next node head_0 = head_0.next; // if last node if (head_0.next == null) { arr[i] = head_i.next; head_i.next = null; head_0.next = head_i; head_0.next.next = null; break; } } } } } return arr[0]; } static public void Main () { // Number of linked lists int k = 3; // an array of pointers storing the // head nodes of the linked lists Node[] arr = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists head = mergeKLists(arr, k - 1); printList(head); }} // This code is contributed by rag2127",
"e": 37166,
"s": 34609,
"text": null
},
{
"code": "<script>// Javascript program to merge k sorted// arrays of size n each // A Linked List node class Node { // Utility function to create a new node. constructor(key) { this.data=key; this.next=null; } } let head; let temp; /* Function to print nodes ina given linked list */function printList(node){ while(node != null) { document.write(node.data + \" \"); node = node.next; } document.write(\"<br>\"); } // The main function that// takes an array of lists// arr[0..last] and generates// the sorted outputfunction mergeKLists(arr,last){ // Traverse form second list to last for (let i = 1; i <= last; i++) { while(true) { // head of both the lists, // 0 and ith list. let head_0 = arr[0]; let head_i = arr[i]; // Break if list ended if (head_i == null) break; // Smaller than first element if(head_0.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0; arr[0] = head_i; } else { // Traverse the first list while (head_0.next != null) { // Smaller than next element if (head_0.next.data >= head_i.data) { arr[i] = head_i.next; head_i.next = head_0.next; head_0.next = head_i; break; } // go to next node head_0 = head_0.next; // if last node if (head_0.next == null) { arr[i] = head_i.next; head_i.next = null; head_0.next = head_i; head_0.next.next = null; break; } } } } } return arr[0];} // Driver program to test// above functions// Number of linked listslet k = 3;// Number of elements in each listlet n = 4;// an array of pointers storing the// head nodes of the linked listslet arr = new Array(k);arr[0] = new Node(1);arr[0].next = new Node(3);arr[0].next.next = new Node(5);arr[0].next.next.next = new Node(7); arr[1] = new Node(2);arr[1].next = new Node(4);arr[1].next.next = new Node(6);arr[1].next.next.next = new Node(8); arr[2] = new Node(0);arr[2].next = new Node(9);arr[2].next.next = new Node(10);arr[2].next.next.next = new Node(11); // Merge all listshead = mergeKLists(arr, k - 1);printList(head); // This code is contributed by unknown2108 </script>",
"e": 39696,
"s": 37166,
"text": null
},
{
"code": null,
"e": 39722,
"s": 39696,
"text": "0 1 2 3 4 5 6 7 8 9 10 11"
},
{
"code": null,
"e": 39746,
"s": 39724,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 39770,
"s": 39746,
"text": "Time complexity: O(nk2)"
},
{
"code": null,
"e": 39824,
"s": 39770,
"text": "Auxiliary Space: O(1). As no extra space is required."
},
{
"code": null,
"e": 40239,
"s": 39824,
"text": "Method 2: Min Heap. A Better solution is to use Min Heap-based solution which is discussed here for arrays. The time complexity of this solution would be O(nk Log k) Method 3: Divide and Conquer. In this post, Divide and Conquer approach is discussed. This approach doesn’t require extra space for heap and works in O(nk Log k)It is known that merging of two linked lists can be done in O(n) time and O(n) space. "
},
{
"code": null,
"e": 40507,
"s": 40239,
"text": "The idea is to pair up K lists and merge each pair in linear time using O(n) space.After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.Repeat the procedure until we have only one list left."
},
{
"code": null,
"e": 40591,
"s": 40507,
"text": "The idea is to pair up K lists and merge each pair in linear time using O(n) space."
},
{
"code": null,
"e": 40722,
"s": 40591,
"text": "After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on."
},
{
"code": null,
"e": 40777,
"s": 40722,
"text": "Repeat the procedure until we have only one list left."
},
{
"code": null,
"e": 40825,
"s": 40777,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 40829,
"s": 40825,
"text": "C++"
},
{
"code": null,
"e": 40834,
"s": 40829,
"text": "Java"
},
{
"code": null,
"e": 40842,
"s": 40834,
"text": "Python3"
},
{
"code": null,
"e": 40845,
"s": 40842,
"text": "C#"
},
{
"code": null,
"e": 40856,
"s": 40845,
"text": "Javascript"
},
{
"code": "// C++ program to merge k sorted// arrays of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(n) extra space for recursive calls, */Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; /* Base cases */ if (a == NULL) return (b); else if (b == NULL) return (a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return result;} // The main function that takes an array of lists// arr[0..last] and generates the sorted outputNode* mergeKLists(Node* arr[], int last){ // repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++, j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0];} // Utility function to create a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver program to test above functionsint main(){ int k = 3; // Number of linked lists int n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}",
"e": 43277,
"s": 40856,
"text": null
},
{
"code": "// Java program to merge k sorted arrays of size n eachpublic class MergeKSortedLists { /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(Log n) extra space for recursive calls, but it can be easily modified to work with same time and O(1) extra space */ public static Node SortedMerge(Node a, Node b) { Node result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.next = SortedMerge(a.next, b); } else { result = b; result.next = SortedMerge(a, b.next); } return result; } // The main function that takes an array of lists // arr[0..last] and generates the sorted output public static Node mergeKLists(Node arr[], int last) { // repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++; j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0]; } /* Function to print nodes in a given linked list */ public static void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } public static void main(String args[]) { int k = 3; // Number of linked lists int n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked lists Node arr[] = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists Node head = mergeKLists(arr, k - 1); printList(head); }} class Node { int data; Node next; Node(int data) { this.data = data; }}// This code is contributed by Gaurav Tiwari",
"e": 45992,
"s": 43277,
"text": null
},
{
"code": "# Python3 program to merge k sorted# arrays of size n each # A Linked List nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to print nodes in a# given linked listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next # Takes two lists sorted in increasing order,# and merge their nodes together to make one# big sorted list. Below function takes# O(Log n) extra space for recursive calls,# but it can be easily modified to work with# same time and O(1) extra spacedef SortedMerge(a, b): result = None # Base cases if (a == None): return(b) elif (b == None): return(a) # Pick either a or b, and recur if (a.data <= b.data): result = a result.next = SortedMerge(a.next, b) else: result = b result.next = SortedMerge(a, b.next) return result # The main function that takes an array of lists# arr[0..last] and generates the sorted outputdef mergeKLists(arr, last): # Repeat until only one list is left while (last != 0): i = 0 j = last # (i, j) forms a pair while (i < j): # Merge List i with List j and store # merged list in List i arr[i] = SortedMerge(arr[i], arr[j]) # Consider next pair i += 1 j -= 1 # If all pairs are merged, update last if (i >= j): last = j return arr[0] # Utility function to create a new node.def newNode(data): temp = Node() temp.data = data temp.next = None return temp # Driver codeif __name__=='__main__': # Number of linked lists k = 3 # Number of elements in each list n = 4 # An array of pointers storing the # head nodes of the linked lists arr = [0 for i in range(k)] arr[0] = newNode(1) arr[0].next = newNode(3) arr[0].next.next = newNode(5) arr[0].next.next.next = newNode(7) arr[1] = newNode(2) arr[1].next = newNode(4) arr[1].next.next = newNode(6) arr[1].next.next.next = newNode(8) arr[2] = newNode(0) arr[2].next = newNode(9) arr[2].next.next = newNode(10) arr[2].next.next.next = newNode(11) # Merge all lists head = mergeKLists(arr, k - 1) printList(head) # This code is contributed by rutvik_56",
"e": 48396,
"s": 45992,
"text": null
},
{
"code": "// C# program to merge k sorted arrays of size n eachusing System; public class MergeKSortedLists { /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(Log n) extra space for recursive calls, but it can be easily modified to work with same time and O(1) extra space */ public static Node SortedMerge(Node a, Node b) { Node result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.next = SortedMerge(a.next, b); } else { result = b; result.next = SortedMerge(a, b.next); } return result; } // The main function that takes // an array of lists arr[0..last] // and generates the sorted output public static Node mergeKLists(Node[] arr, int last) { // repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++; j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0]; } /* Function to print nodes in a given linked list */ public static void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } public static void Main() { int k = 3; // Number of linked lists //int n = 4; // Number of elements in each list // An array of pointers storing the head nodes // of the linked lists Node[] arr = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists Node head = mergeKLists(arr, k - 1); printList(head); }} public class Node { public int data; public Node next; public Node(int data) { this.data = data; }} /* This code contributed by PrinciRaj1992 */",
"e": 51156,
"s": 48396,
"text": null
},
{
"code": "<script> // JavaScript program to merge k sorted// arrays of size n eachclass Node { constructor(val) { this.data = val; this.next = null; }} /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(Log n) extra space for * recursive calls, but it can be easily modified to work with same time and * O(1) extra space */ function SortedMerge(a, b) {var result = null; /* Base cases */ if (a == null) return b; else if (b == null) return a; /* Pick either a or b, and recur */ if (a.data <= b.data) { result = a; result.next = SortedMerge(a.next, b); } else { result = b; result.next = SortedMerge(a, b.next); } return result; } // The main function that takes an array of lists // arr[0..last] and generates the sorted output function mergeKLists(arr , last) { // repeat until only one list is left while (last != 0) { var i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and store // merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++; j--; // If all pairs are merged, update last if (i >= j) last = j; } } return arr[0]; } /* Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } var k = 3; // Number of linked lists var n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked listsvar arr = Array(k); arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all listsvar head = mergeKLists(arr, k - 1); printList(head); // This code contributed by gauravrajput1 </script>",
"e": 53731,
"s": 51156,
"text": null
},
{
"code": null,
"e": 53757,
"s": 53731,
"text": "0 1 2 3 4 5 6 7 8 9 10 11"
},
{
"code": null,
"e": 53781,
"s": 53759,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 53910,
"s": 53781,
"text": " Assuming N(n*k) is the total number of nodes, n is the size of each linked list, and k is the total number of linked lists."
},
{
"code": null,
"e": 54058,
"s": 53910,
"text": "Time Complexity: O(N*log k) or O(n*k*log k)As outer while loop in function mergeKLists() runs log k times and every time it processes n*k elements."
},
{
"code": null,
"e": 54215,
"s": 54058,
"text": "Auxiliary Space: O(N) or O(n*k)Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made."
},
{
"code": null,
"e": 54268,
"s": 54215,
"text": "Merge k sorted linked lists | Set 2 (Using Min Heap)"
},
{
"code": null,
"e": 54657,
"s": 54268,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 54711,
"s": 54657,
"text": " Method 4: Selecting min of top element iteratively"
},
{
"code": null,
"e": 54821,
"s": 54711,
"text": "The time complexity of this solution would be O(n*k) and the space complexity of this solution would be O(n) "
},
{
"code": null,
"e": 54832,
"s": 54821,
"text": "Approach :"
},
{
"code": null,
"e": 54955,
"s": 54832,
"text": "Select the minimum of top elements iteratively store that in a new node and increment the pointer of the minimum element ."
},
{
"code": null,
"e": 54962,
"s": 54955,
"text": "Code :"
},
{
"code": null,
"e": 54966,
"s": 54962,
"text": "C++"
},
{
"code": "// C++ program to merge k sorted arrays of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node{ int data; Node* next; Node(int x) { data = x; next = NULL; }}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } cout << endl;} /*Linked list Node structure struct Node{int data;Node* next;Node(int x){ data = x; next = NULL;}};*/ class Solution{public: // Function to merge K sorted linked list. Node* mergeKLists(Node* arr[], int K) { Node* head = NULL; while (1) { int a = 0; int z; Node* curr; int min = INT_MAX; for (int i = 0; i < K; i++) { if (arr[i] != NULL) { a++; if (arr[i]->data < min) { min = arr[i]->data; z = i; } } } if (a != 0) { arr[z] = arr[z]->next; Node* temp = new Node(min); if (head == NULL) { head = temp; curr = temp; } else { curr->next = temp; curr = temp; } } else { return head; } } }}; // { Driver Code Starts. // Driver program to test above functionsint main(){ int t; cin >> t; while (t--) { int N; cin >> N; struct Node* arr[N]; for (int j = 0; j < N; j++) { int n; cin >> n; int x; cin >> x; arr[j] = new Node(x); Node* curr = arr[j]; n--; for (int i = 0; i < n; i++) { cin >> x; Node* temp = new Node(x); curr->next = temp; curr = temp; } } Solution obj; Node* res = obj.mergeKLists(arr, N); printList(res); } return 0;} // } Driver Code Ends",
"e": 57253,
"s": 54966,
"text": null
},
{
"code": null,
"e": 57268,
"s": 57253,
"text": "_Gaurav_Tiwari"
},
{
"code": null,
"e": 57282,
"s": 57268,
"text": "princiraj1992"
},
{
"code": null,
"e": 57301,
"s": 57282,
"text": "sachinhaldavanekar"
},
{
"code": null,
"e": 57312,
"s": 57301,
"text": "andrew1234"
},
{
"code": null,
"e": 57327,
"s": 57312,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 57337,
"s": 57327,
"text": "rutvik_56"
},
{
"code": null,
"e": 57358,
"s": 57337,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 57366,
"s": 57358,
"text": "rag2127"
},
{
"code": null,
"e": 57380,
"s": 57366,
"text": "mittulmandhan"
},
{
"code": null,
"e": 57392,
"s": 57380,
"text": "unknown2108"
},
{
"code": null,
"e": 57406,
"s": 57392,
"text": "GauravRajput1"
},
{
"code": null,
"e": 57420,
"s": 57406,
"text": "rohitguptaiem"
},
{
"code": null,
"e": 57436,
"s": 57420,
"text": "simranarora5sos"
},
{
"code": null,
"e": 57453,
"s": 57436,
"text": "singhashwani2002"
},
{
"code": null,
"e": 57466,
"s": 57453,
"text": "Adarsh Kumar"
},
{
"code": null,
"e": 57473,
"s": 57466,
"text": "Amazon"
},
{
"code": null,
"e": 57484,
"s": 57473,
"text": "Merge Sort"
},
{
"code": null,
"e": 57491,
"s": 57484,
"text": "VMWare"
},
{
"code": null,
"e": 57496,
"s": 57491,
"text": "Heap"
},
{
"code": null,
"e": 57508,
"s": 57496,
"text": "Linked List"
},
{
"code": null,
"e": 57515,
"s": 57508,
"text": "VMWare"
},
{
"code": null,
"e": 57522,
"s": 57515,
"text": "Amazon"
},
{
"code": null,
"e": 57534,
"s": 57522,
"text": "Linked List"
},
{
"code": null,
"e": 57539,
"s": 57534,
"text": "Heap"
},
{
"code": null,
"e": 57550,
"s": 57539,
"text": "Merge Sort"
},
{
"code": null,
"e": 57648,
"s": 57550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 57680,
"s": 57648,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 57697,
"s": 57680,
"text": "Max Heap in Java"
},
{
"code": null,
"e": 57722,
"s": 57697,
"text": "Priority Queue in Python"
},
{
"code": null,
"e": 57755,
"s": 57722,
"text": "Priority Queue using Binary Heap"
},
{
"code": null,
"e": 57805,
"s": 57755,
"text": "Median in a stream of integers (running integers)"
},
{
"code": null,
"e": 57840,
"s": 57805,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 57879,
"s": 57840,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 57901,
"s": 57879,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 57949,
"s": 57901,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
How to find duplicate elements in a Stream in Java - GeeksforGeeks
|
12 May, 2022
Given a stream containing some elements, the task is to find the duplicate elements in this stream in Java.
Examples:
Input: Stream = {5, 13, 4, 21, 13, 27, 2, 59, 59, 34}Output: [59, 13]Explanation:The only duplicate elements in the given stream are 59 and 13.
Input: Stream = {5, 13, 4, 21, 27, 2, 59, 34}Output: []Explanation:There are no duplicate elements in the given stream, hence the output is empty.
There are many methods to find duplicate elements in a Stream:
Using Set: Since Set has the property that it cannot contain any duplicate element. So if we add the elements in a Set, it automatically discards the duplicate elements while addition itself.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, if it is not present in the set, add it. This can be done using Set.add() method.Set.add()If the element is present in the Set already, then this Set.add() returns false.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Set import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Set to store the duplicate elements Set<T> items = new HashSet<>(); // Return the set of duplicate elements return stream // Set.add() returns false // if the element was // already present in the set. // Hence filter such elements .filter(n -> !items.add(n)) // Collect duplicate elements // in the set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]
Using Collectors.groupingBy(): The groupingBy() method of Collectors class in Java groups the objects by some property. So we will pass the property of redundancy and collect the result in a Set.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, group them along with their frequency in a map, using Collectors.groupingBy() method.stream.collect(
Collectors.groupingBy(Function.identity(),
Collectors.counting()));
Then for each element in the collected map, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Collectors.groupingBy() import java.util.*;import java.util.stream.*;import java.util.function.Function; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Return the set of duplicate elements return stream // Group the elements along // with their frequency in a map .collect( Collectors.groupingBy( Function.identity(), Collectors.counting())) // Convert this map into a stream .entrySet() .stream() // Check if frequency > 1 // for duplicate elements .filter(m -> m.getValue() > 1) // Find such elements .map(Map.Entry::getKey) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]
Using Collections.frequency(): The frequency() method of Collections class in Java, counts the frequency of the specified element in the given list. So we will then find out the elements that have frequency more than 1, which are the duplicate elements.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, count the frequency of each element, using Collections.frequency() method.Collections.frequency(list, i)
Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream// using Collections.frequency() import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(List<T> list) { // Return the set of duplicate elements return // Get the stream from the list list.stream() // Count the frequency of each element // and filter the elements // with frequency > 1 .filter(i -> Collections.frequency(list, i) > 1) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream List<Integer> list = Arrays.asList(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(list)); }}Output:[59, 13]
Using Set: Since Set has the property that it cannot contain any duplicate element. So if we add the elements in a Set, it automatically discards the duplicate elements while addition itself.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, if it is not present in the set, add it. This can be done using Set.add() method.Set.add()If the element is present in the Set already, then this Set.add() returns false.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Set import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Set to store the duplicate elements Set<T> items = new HashSet<>(); // Return the set of duplicate elements return stream // Set.add() returns false // if the element was // already present in the set. // Hence filter such elements .filter(n -> !items.add(n)) // Collect duplicate elements // in the set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]
Approach:
Get the stream of elements in which the duplicates are to be found.
Traverse each element of the stream
For each element in the stream, if it is not present in the set, add it. This can be done using Set.add() method.Set.add()
Set.add()
If the element is present in the Set already, then this Set.add() returns false.
Hence we can print such elements or collect them for further process. We will print these elements in this case.
Below is the implementation of the above approach:
Example:
// Java program to find the duplicate// elements in a Stream using Set import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Set to store the duplicate elements Set<T> items = new HashSet<>(); // Return the set of duplicate elements return stream // Set.add() returns false // if the element was // already present in the set. // Hence filter such elements .filter(n -> !items.add(n)) // Collect duplicate elements // in the set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}
[59, 13]
Using Collectors.groupingBy(): The groupingBy() method of Collectors class in Java groups the objects by some property. So we will pass the property of redundancy and collect the result in a Set.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, group them along with their frequency in a map, using Collectors.groupingBy() method.stream.collect(
Collectors.groupingBy(Function.identity(),
Collectors.counting()));
Then for each element in the collected map, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Collectors.groupingBy() import java.util.*;import java.util.stream.*;import java.util.function.Function; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Return the set of duplicate elements return stream // Group the elements along // with their frequency in a map .collect( Collectors.groupingBy( Function.identity(), Collectors.counting())) // Convert this map into a stream .entrySet() .stream() // Check if frequency > 1 // for duplicate elements .filter(m -> m.getValue() > 1) // Find such elements .map(Map.Entry::getKey) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]
Approach:
Get the stream of elements in which the duplicates are to be found.
Traverse each element of the stream
For each element in the stream, group them along with their frequency in a map, using Collectors.groupingBy() method.stream.collect(
Collectors.groupingBy(Function.identity(),
Collectors.counting()));
stream.collect(
Collectors.groupingBy(Function.identity(),
Collectors.counting()));
Then for each element in the collected map, if the frequency of any element is more than one, then this element is a duplicate element.
Hence we can print such elements or collect them for further process. We will print these elements in this case.
Below is the implementation of the above approach:
Example:
// Java program to find the duplicate// elements in a Stream using Collectors.groupingBy() import java.util.*;import java.util.stream.*;import java.util.function.Function; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Return the set of duplicate elements return stream // Group the elements along // with their frequency in a map .collect( Collectors.groupingBy( Function.identity(), Collectors.counting())) // Convert this map into a stream .entrySet() .stream() // Check if frequency > 1 // for duplicate elements .filter(m -> m.getValue() > 1) // Find such elements .map(Map.Entry::getKey) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}
[59, 13]
Using Collections.frequency(): The frequency() method of Collections class in Java, counts the frequency of the specified element in the given list. So we will then find out the elements that have frequency more than 1, which are the duplicate elements.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, count the frequency of each element, using Collections.frequency() method.Collections.frequency(list, i)
Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream// using Collections.frequency() import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(List<T> list) { // Return the set of duplicate elements return // Get the stream from the list list.stream() // Count the frequency of each element // and filter the elements // with frequency > 1 .filter(i -> Collections.frequency(list, i) > 1) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream List<Integer> list = Arrays.asList(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(list)); }}Output:[59, 13]
Approach:
Get the stream of elements in which the duplicates are to be found.
Traverse each element of the stream
For each element in the stream, count the frequency of each element, using Collections.frequency() method.Collections.frequency(list, i)
Collections.frequency(list, i)
Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.
Hence we can print such elements or collect them for further process. We will print these elements in this case.
Below is the implementation of the above approach:
Example:
// Java program to find the duplicate// elements in a Stream// using Collections.frequency() import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(List<T> list) { // Return the set of duplicate elements return // Get the stream from the list list.stream() // Count the frequency of each element // and filter the elements // with frequency > 1 .filter(i -> Collections.frequency(list, i) > 1) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream List<Integer> list = Arrays.asList(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(list)); }}
[59, 13]
Java-Collections-Class
Java-Collectors
java-stream
Java-Stream-programs
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
Stream In Java
Interfaces in Java
How to iterate any Map 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": 25691,
"s": 25663,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 25799,
"s": 25691,
"text": "Given a stream containing some elements, the task is to find the duplicate elements in this stream in Java."
},
{
"code": null,
"e": 25809,
"s": 25799,
"text": "Examples:"
},
{
"code": null,
"e": 25953,
"s": 25809,
"text": "Input: Stream = {5, 13, 4, 21, 13, 27, 2, 59, 59, 34}Output: [59, 13]Explanation:The only duplicate elements in the given stream are 59 and 13."
},
{
"code": null,
"e": 26100,
"s": 25953,
"text": "Input: Stream = {5, 13, 4, 21, 27, 2, 59, 34}Output: []Explanation:There are no duplicate elements in the given stream, hence the output is empty."
},
{
"code": null,
"e": 26163,
"s": 26100,
"text": "There are many methods to find duplicate elements in a Stream:"
},
{
"code": null,
"e": 32027,
"s": 26163,
"text": "Using Set: Since Set has the property that it cannot contain any duplicate element. So if we add the elements in a Set, it automatically discards the duplicate elements while addition itself.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, if it is not present in the set, add it. This can be done using Set.add() method.Set.add()If the element is present in the Set already, then this Set.add() returns false.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Set import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Set to store the duplicate elements Set<T> items = new HashSet<>(); // Return the set of duplicate elements return stream // Set.add() returns false // if the element was // already present in the set. // Hence filter such elements .filter(n -> !items.add(n)) // Collect duplicate elements // in the set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]\nUsing Collectors.groupingBy(): The groupingBy() method of Collectors class in Java groups the objects by some property. So we will pass the property of redundancy and collect the result in a Set.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, group them along with their frequency in a map, using Collectors.groupingBy() method.stream.collect(\n Collectors.groupingBy(Function.identity(), \n Collectors.counting())); \nThen for each element in the collected map, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Collectors.groupingBy() import java.util.*;import java.util.stream.*;import java.util.function.Function; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Return the set of duplicate elements return stream // Group the elements along // with their frequency in a map .collect( Collectors.groupingBy( Function.identity(), Collectors.counting())) // Convert this map into a stream .entrySet() .stream() // Check if frequency > 1 // for duplicate elements .filter(m -> m.getValue() > 1) // Find such elements .map(Map.Entry::getKey) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]\nUsing Collections.frequency(): The frequency() method of Collections class in Java, counts the frequency of the specified element in the given list. So we will then find out the elements that have frequency more than 1, which are the duplicate elements.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, count the frequency of each element, using Collections.frequency() method.Collections.frequency(list, i) \nThen for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream// using Collections.frequency() import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(List<T> list) { // Return the set of duplicate elements return // Get the stream from the list list.stream() // Count the frequency of each element // and filter the elements // with frequency > 1 .filter(i -> Collections.frequency(list, i) > 1) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream List<Integer> list = Arrays.asList(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(list)); }}Output:[59, 13]\n"
},
{
"code": null,
"e": 33809,
"s": 32027,
"text": "Using Set: Since Set has the property that it cannot contain any duplicate element. So if we add the elements in a Set, it automatically discards the duplicate elements while addition itself.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, if it is not present in the set, add it. This can be done using Set.add() method.Set.add()If the element is present in the Set already, then this Set.add() returns false.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Set import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Set to store the duplicate elements Set<T> items = new HashSet<>(); // Return the set of duplicate elements return stream // Set.add() returns false // if the element was // already present in the set. // Hence filter such elements .filter(n -> !items.add(n)) // Collect duplicate elements // in the set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]\n"
},
{
"code": null,
"e": 33819,
"s": 33809,
"text": "Approach:"
},
{
"code": null,
"e": 33887,
"s": 33819,
"text": "Get the stream of elements in which the duplicates are to be found."
},
{
"code": null,
"e": 33923,
"s": 33887,
"text": "Traverse each element of the stream"
},
{
"code": null,
"e": 34046,
"s": 33923,
"text": "For each element in the stream, if it is not present in the set, add it. This can be done using Set.add() method.Set.add()"
},
{
"code": null,
"e": 34056,
"s": 34046,
"text": "Set.add()"
},
{
"code": null,
"e": 34137,
"s": 34056,
"text": "If the element is present in the Set already, then this Set.add() returns false."
},
{
"code": null,
"e": 34250,
"s": 34137,
"text": "Hence we can print such elements or collect them for further process. We will print these elements in this case."
},
{
"code": null,
"e": 34301,
"s": 34250,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 34310,
"s": 34301,
"text": "Example:"
},
{
"code": "// Java program to find the duplicate// elements in a Stream using Set import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Set to store the duplicate elements Set<T> items = new HashSet<>(); // Return the set of duplicate elements return stream // Set.add() returns false // if the element was // already present in the set. // Hence filter such elements .filter(n -> !items.add(n)) // Collect duplicate elements // in the set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}",
"e": 35402,
"s": 34310,
"text": null
},
{
"code": null,
"e": 35412,
"s": 35402,
"text": "[59, 13]\n"
},
{
"code": null,
"e": 37595,
"s": 35412,
"text": "Using Collectors.groupingBy(): The groupingBy() method of Collectors class in Java groups the objects by some property. So we will pass the property of redundancy and collect the result in a Set.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, group them along with their frequency in a map, using Collectors.groupingBy() method.stream.collect(\n Collectors.groupingBy(Function.identity(), \n Collectors.counting())); \nThen for each element in the collected map, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream using Collectors.groupingBy() import java.util.*;import java.util.stream.*;import java.util.function.Function; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Return the set of duplicate elements return stream // Group the elements along // with their frequency in a map .collect( Collectors.groupingBy( Function.identity(), Collectors.counting())) // Convert this map into a stream .entrySet() .stream() // Check if frequency > 1 // for duplicate elements .filter(m -> m.getValue() > 1) // Find such elements .map(Map.Entry::getKey) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}Output:[59, 13]\n"
},
{
"code": null,
"e": 37605,
"s": 37595,
"text": "Approach:"
},
{
"code": null,
"e": 37673,
"s": 37605,
"text": "Get the stream of elements in which the duplicates are to be found."
},
{
"code": null,
"e": 37709,
"s": 37673,
"text": "Traverse each element of the stream"
},
{
"code": null,
"e": 37921,
"s": 37709,
"text": "For each element in the stream, group them along with their frequency in a map, using Collectors.groupingBy() method.stream.collect(\n Collectors.groupingBy(Function.identity(), \n Collectors.counting())); \n"
},
{
"code": null,
"e": 38016,
"s": 37921,
"text": "stream.collect(\n Collectors.groupingBy(Function.identity(), \n Collectors.counting())); \n"
},
{
"code": null,
"e": 38152,
"s": 38016,
"text": "Then for each element in the collected map, if the frequency of any element is more than one, then this element is a duplicate element."
},
{
"code": null,
"e": 38265,
"s": 38152,
"text": "Hence we can print such elements or collect them for further process. We will print these elements in this case."
},
{
"code": null,
"e": 38316,
"s": 38265,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 38325,
"s": 38316,
"text": "Example:"
},
{
"code": "// Java program to find the duplicate// elements in a Stream using Collectors.groupingBy() import java.util.*;import java.util.stream.*;import java.util.function.Function; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Return the set of duplicate elements return stream // Group the elements along // with their frequency in a map .collect( Collectors.groupingBy( Function.identity(), Collectors.counting())) // Convert this map into a stream .entrySet() .stream() // Check if frequency > 1 // for duplicate elements .filter(m -> m.getValue() > 1) // Find such elements .map(Map.Entry::getKey) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); }}",
"e": 39670,
"s": 38325,
"text": null
},
{
"code": null,
"e": 39680,
"s": 39670,
"text": "[59, 13]\n"
},
{
"code": null,
"e": 41581,
"s": 39680,
"text": "Using Collections.frequency(): The frequency() method of Collections class in Java, counts the frequency of the specified element in the given list. So we will then find out the elements that have frequency more than 1, which are the duplicate elements.Approach:Get the stream of elements in which the duplicates are to be found.Traverse each element of the streamFor each element in the stream, count the frequency of each element, using Collections.frequency() method.Collections.frequency(list, i) \nThen for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.Hence we can print such elements or collect them for further process. We will print these elements in this case.Below is the implementation of the above approach:Example:// Java program to find the duplicate// elements in a Stream// using Collections.frequency() import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(List<T> list) { // Return the set of duplicate elements return // Get the stream from the list list.stream() // Count the frequency of each element // and filter the elements // with frequency > 1 .filter(i -> Collections.frequency(list, i) > 1) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream List<Integer> list = Arrays.asList(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(list)); }}Output:[59, 13]\n"
},
{
"code": null,
"e": 41591,
"s": 41581,
"text": "Approach:"
},
{
"code": null,
"e": 41659,
"s": 41591,
"text": "Get the stream of elements in which the duplicates are to be found."
},
{
"code": null,
"e": 41695,
"s": 41659,
"text": "Traverse each element of the stream"
},
{
"code": null,
"e": 41834,
"s": 41695,
"text": "For each element in the stream, count the frequency of each element, using Collections.frequency() method.Collections.frequency(list, i) \n"
},
{
"code": null,
"e": 41867,
"s": 41834,
"text": "Collections.frequency(list, i) \n"
},
{
"code": null,
"e": 42005,
"s": 41867,
"text": "Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element."
},
{
"code": null,
"e": 42118,
"s": 42005,
"text": "Hence we can print such elements or collect them for further process. We will print these elements in this case."
},
{
"code": null,
"e": 42169,
"s": 42118,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 42178,
"s": 42169,
"text": "Example:"
},
{
"code": "// Java program to find the duplicate// elements in a Stream// using Collections.frequency() import java.util.*;import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(List<T> list) { // Return the set of duplicate elements return // Get the stream from the list list.stream() // Count the frequency of each element // and filter the elements // with frequency > 1 .filter(i -> Collections.frequency(list, i) > 1) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream List<Integer> list = Arrays.asList(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(list)); }}",
"e": 43254,
"s": 42178,
"text": null
},
{
"code": null,
"e": 43264,
"s": 43254,
"text": "[59, 13]\n"
},
{
"code": null,
"e": 43287,
"s": 43264,
"text": "Java-Collections-Class"
},
{
"code": null,
"e": 43303,
"s": 43287,
"text": "Java-Collectors"
},
{
"code": null,
"e": 43315,
"s": 43303,
"text": "java-stream"
},
{
"code": null,
"e": 43336,
"s": 43315,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 43341,
"s": 43336,
"text": "Java"
},
{
"code": null,
"e": 43355,
"s": 43341,
"text": "Java Programs"
},
{
"code": null,
"e": 43360,
"s": 43355,
"text": "Java"
},
{
"code": null,
"e": 43458,
"s": 43360,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43509,
"s": 43458,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 43539,
"s": 43509,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 43554,
"s": 43539,
"text": "Stream In Java"
},
{
"code": null,
"e": 43573,
"s": 43554,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 43604,
"s": 43573,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 43632,
"s": 43604,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 43676,
"s": 43632,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 43702,
"s": 43676,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 43736,
"s": 43702,
"text": "Convert Double to Integer in Java"
}
] |
React.js Render Props - GeeksforGeeks
|
16 Mar, 2021
The Render Props is a technique in ReactJS for sharing code between React components using a prop whose value is a function. Child component takes render props as a function and calls it instead of implementing its own render logic. In brief, we pass a function from the parent component to the child component as a render props, and the child component calls that function instead of implementing its own logic.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react' class App extends React.Component { render() { return ( <div> <h1>Render Props Example</h1> <SampleRenderProps /> </div> ) }} // Child component getting render propsclass RenderPropsComponent extends React.Component { render() { return ( <div> <h2>I am Child Component</h2> {this.props.render()} </div> ) }} // Parent component sending render props to the childclass SampleRenderProps extends React.Component { render() { return ( <RenderPropsComponent // Passing render props to the child component render={() => { return ( <div> <h3> I am coming from render props </h3> </div> ) }} /> ) }} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Picked
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 26485,
"s": 26071,
"text": "The Render Props is a technique in ReactJS for sharing code between React components using a prop whose value is a function. Child component takes render props as a function and calls it instead of implementing its own render logic. In brief, we pass a function from the parent component to the child component as a render props, and the child component calls that function instead of implementing its own logic."
},
{
"code": null,
"e": 26535,
"s": 26485,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26599,
"s": 26535,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 26631,
"s": 26599,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26731,
"s": 26631,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 26745,
"s": 26731,
"text": "cd foldername"
},
{
"code": null,
"e": 26797,
"s": 26745,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 26927,
"s": 26797,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 26934,
"s": 26927,
"text": "App.js"
},
{
"code": "import React from 'react' class App extends React.Component { render() { return ( <div> <h1>Render Props Example</h1> <SampleRenderProps /> </div> ) }} // Child component getting render propsclass RenderPropsComponent extends React.Component { render() { return ( <div> <h2>I am Child Component</h2> {this.props.render()} </div> ) }} // Parent component sending render props to the childclass SampleRenderProps extends React.Component { render() { return ( <RenderPropsComponent // Passing render props to the child component render={() => { return ( <div> <h3> I am coming from render props </h3> </div> ) }} /> ) }} export default App;",
"e": 27761,
"s": 26934,
"text": null
},
{
"code": null,
"e": 27874,
"s": 27761,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27884,
"s": 27874,
"text": "npm start"
},
{
"code": null,
"e": 27983,
"s": 27884,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 27990,
"s": 27983,
"text": "Picked"
},
{
"code": null,
"e": 28005,
"s": 27990,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 28013,
"s": 28005,
"text": "ReactJS"
},
{
"code": null,
"e": 28030,
"s": 28013,
"text": "Web Technologies"
},
{
"code": null,
"e": 28128,
"s": 28030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28155,
"s": 28128,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 28197,
"s": 28155,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28235,
"s": 28197,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 28270,
"s": 28235,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28328,
"s": 28270,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28368,
"s": 28328,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28401,
"s": 28368,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28446,
"s": 28401,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28508,
"s": 28446,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
JavaScript Date parse() Method - GeeksforGeeks
|
22 Nov, 2021
Below is the example of Date parse() method.
Example:
javascript
<script> // Taking a date string as input. var date = "February 18, 2018 12:30 PM"; // Calling parse function on input date string. var msec = Date.parse(date); document.write(msec);</script>
Output:
1518937200000
The date.parse() method is used to know the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide.Syntax:
Date.parse(datestring);
Parameters: This method accept a single parameter as mentioned above and described below:
datestring: This parameter holds the date as a string.
Return Values: It returns an integer value representing the number of a millisecond between midnight January 1, 1970, and the date provided. If by any means, the machine can’t recognize the string or the input string is invalid, it will return “NaN” instead of an integer.More codes for the above method are as follows: Program 1: If the input string of date is not correct, it return NaN i.e, not a number.
javascript
<script> // Taking wrong date string as input. var date = "February 48, 2018 12:30 PM"; // calling parse function. var msec = Date.parse(date); document.write(msec); </script>
Output:
NaN
Program 2: If the input string of date is not correct, it return NaN i.e, not a number.
javascript
<script> // Taking wrong date string as input. var date = "June 22, 2012"; // Calling parse function. var msec = Date.parse(date); document.write(msec); </script>
Output:
1340303400000
Note: Once we get the millisecond count between two dates, we can easily find the number of hours, days, months, years, etc by simple maths calculation.Supported Browsers: The browsers supported by JavaScript Date parse() method are listed below:
Google Chrome 1 and above
Internet Explorer 3 and above
Mozilla Firefox 1 and above
Opera 3 and above
Safari 1 and above
kalrap615
ysachin2314
javascript-date
JavaScript-Methods
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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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": 31305,
"s": 31277,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 31352,
"s": 31305,
"text": "Below is the example of Date parse() method. "
},
{
"code": null,
"e": 31363,
"s": 31352,
"text": "Example: "
},
{
"code": null,
"e": 31374,
"s": 31363,
"text": "javascript"
},
{
"code": "<script> // Taking a date string as input. var date = \"February 18, 2018 12:30 PM\"; // Calling parse function on input date string. var msec = Date.parse(date); document.write(msec);</script> ",
"e": 31606,
"s": 31374,
"text": null
},
{
"code": null,
"e": 31616,
"s": 31606,
"text": "Output: "
},
{
"code": null,
"e": 31630,
"s": 31616,
"text": "1518937200000"
},
{
"code": null,
"e": 31788,
"s": 31630,
"text": "The date.parse() method is used to know the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide.Syntax: "
},
{
"code": null,
"e": 31812,
"s": 31788,
"text": "Date.parse(datestring);"
},
{
"code": null,
"e": 31904,
"s": 31812,
"text": "Parameters: This method accept a single parameter as mentioned above and described below: "
},
{
"code": null,
"e": 31959,
"s": 31904,
"text": "datestring: This parameter holds the date as a string."
},
{
"code": null,
"e": 32369,
"s": 31959,
"text": "Return Values: It returns an integer value representing the number of a millisecond between midnight January 1, 1970, and the date provided. If by any means, the machine can’t recognize the string or the input string is invalid, it will return “NaN” instead of an integer.More codes for the above method are as follows: Program 1: If the input string of date is not correct, it return NaN i.e, not a number. "
},
{
"code": null,
"e": 32380,
"s": 32369,
"text": "javascript"
},
{
"code": "<script> // Taking wrong date string as input. var date = \"February 48, 2018 12:30 PM\"; // calling parse function. var msec = Date.parse(date); document.write(msec); </script> ",
"e": 32600,
"s": 32380,
"text": null
},
{
"code": null,
"e": 32610,
"s": 32600,
"text": "Output: "
},
{
"code": null,
"e": 32614,
"s": 32610,
"text": "NaN"
},
{
"code": null,
"e": 32704,
"s": 32614,
"text": "Program 2: If the input string of date is not correct, it return NaN i.e, not a number. "
},
{
"code": null,
"e": 32715,
"s": 32704,
"text": "javascript"
},
{
"code": "<script> // Taking wrong date string as input. var date = \"June 22, 2012\"; // Calling parse function. var msec = Date.parse(date); document.write(msec); </script> ",
"e": 32922,
"s": 32715,
"text": null
},
{
"code": null,
"e": 32932,
"s": 32922,
"text": "Output: "
},
{
"code": null,
"e": 32946,
"s": 32932,
"text": "1340303400000"
},
{
"code": null,
"e": 33195,
"s": 32946,
"text": "Note: Once we get the millisecond count between two dates, we can easily find the number of hours, days, months, years, etc by simple maths calculation.Supported Browsers: The browsers supported by JavaScript Date parse() method are listed below: "
},
{
"code": null,
"e": 33221,
"s": 33195,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 33252,
"s": 33221,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 33280,
"s": 33252,
"text": "Mozilla Firefox 1 and above"
},
{
"code": null,
"e": 33298,
"s": 33280,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 33317,
"s": 33298,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 33329,
"s": 33319,
"text": "kalrap615"
},
{
"code": null,
"e": 33341,
"s": 33329,
"text": "ysachin2314"
},
{
"code": null,
"e": 33357,
"s": 33341,
"text": "javascript-date"
},
{
"code": null,
"e": 33376,
"s": 33357,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 33387,
"s": 33376,
"text": "JavaScript"
},
{
"code": null,
"e": 33404,
"s": 33387,
"text": "Web Technologies"
},
{
"code": null,
"e": 33502,
"s": 33404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33542,
"s": 33502,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33587,
"s": 33542,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33648,
"s": 33587,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33720,
"s": 33648,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 33789,
"s": 33720,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 33829,
"s": 33789,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33862,
"s": 33829,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33907,
"s": 33862,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33950,
"s": 33907,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Integer.numberOfTrailingZeros() Method in Java with Example - GeeksforGeeks
|
05 Dec, 2018
The Java.lang.Integer.numberOfTrailingZeros() is the method which returns the total number of zero(0) bits following the lowest-order (ie.Rightmost or least significant “1” bit)one-bit in the two’s complement binary representation of the specified integer value or we can say that it is the function which converts int value to Binary then considers the lowest one bit and return no. of zero bits following it. If the specified integer value has no one-bits in its two’s complement representation, in other words if it is equal to zero then it will returns 32.
Syntax :
public static int numberOfTrailingZeros(int a)
Parameter: The parameter a is an integer value.
Return Value: This method returns the number of zero bits following the lowest-order one-bit or set-bit in the two’s complement binary representation of the specified int value, or 32 if the value is equal to zero.
Explanation
Consider an integer a = 170
Binary Representation = 10101010
Lowest one bit = 2
Number of trailing zeros = 1
Below programs illustrate the Java.lang.Integer.numberOfTrailingZeros() method.
Program 1: For a positive number.
// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { int a = 155; System.out.println("Integral Number = " + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print("Number of Trailing Zeros = "); System.out.println(Integer.numberOfTrailingZeros(a)); a = 24; System.out.println("Integral Number = " + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print("Number of Trailing Zeros = "); System.out.println(Integer.numberOfTrailingZeros(a)); }}
Integral Number = 155
Number of Trailing Zeros = 0
Integral Number = 24
Number of Trailing Zeros = 3
Note: Here the number of trailing zeros is equal to 0 for 155 ,this is because in the binary representation 10011011 there is no zero which is following the lowest-order (ie.Rightmost or least significant “1” bit)one-bit.
Program 2: For a negative number.
// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { int a = -1; System.out.println("Integral Number = " + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print("Number of Trailing Zeros = "); System.out.println(Integer.numberOfTrailingZeros(a)); a = -90; System.out.println("Integral Number = " + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print("Number of Trailing Zeros = "); System.out.println(Integer.numberOfTrailingZeros(a)); }}
Integral Number = -1
Number of Trailing Zeros = 0
Integral Number = -90
Number of Trailing Zeros = 1
Program 3: For a decimal value.Note: It returns an error message when a decimal value is passed as an argument.
// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { System.out.println("Number of trailing zeros = "+ Integer.numberOfTrailingZeros(12.66)); }}
Output:
prog.java:10: error: incompatible types: possible lossy conversion from double to int
Integer.numberOfTrailingZeros(12.66));
^
Note: Some messages have been simplified; recompile with
-Xdiags:verbose to get full output
1 error
Program 4: For a string value.Note: It returns an error message when a string value is passed as an argument.
// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { System.out.println("Number of trailing zeros = " + Integer.numberOfTrailingZeros("12"));}}
Output:
prog.java:10: error: incompatible types: String cannot be converted to int
+ Integer.numberOfTrailingZeros("12"));
^
Note: Some messages have been simplified; recompile with
-Xdiags:verbose to get full output
1 error
Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 25786,
"s": 25225,
"text": "The Java.lang.Integer.numberOfTrailingZeros() is the method which returns the total number of zero(0) bits following the lowest-order (ie.Rightmost or least significant “1” bit)one-bit in the two’s complement binary representation of the specified integer value or we can say that it is the function which converts int value to Binary then considers the lowest one bit and return no. of zero bits following it. If the specified integer value has no one-bits in its two’s complement representation, in other words if it is equal to zero then it will returns 32."
},
{
"code": null,
"e": 25795,
"s": 25786,
"text": "Syntax :"
},
{
"code": null,
"e": 25842,
"s": 25795,
"text": "public static int numberOfTrailingZeros(int a)"
},
{
"code": null,
"e": 25890,
"s": 25842,
"text": "Parameter: The parameter a is an integer value."
},
{
"code": null,
"e": 26105,
"s": 25890,
"text": "Return Value: This method returns the number of zero bits following the lowest-order one-bit or set-bit in the two’s complement binary representation of the specified int value, or 32 if the value is equal to zero."
},
{
"code": null,
"e": 26117,
"s": 26105,
"text": "Explanation"
},
{
"code": null,
"e": 26145,
"s": 26117,
"text": "Consider an integer a = 170"
},
{
"code": null,
"e": 26178,
"s": 26145,
"text": "Binary Representation = 10101010"
},
{
"code": null,
"e": 26197,
"s": 26178,
"text": "Lowest one bit = 2"
},
{
"code": null,
"e": 26226,
"s": 26197,
"text": "Number of trailing zeros = 1"
},
{
"code": null,
"e": 26306,
"s": 26226,
"text": "Below programs illustrate the Java.lang.Integer.numberOfTrailingZeros() method."
},
{
"code": null,
"e": 26340,
"s": 26306,
"text": "Program 1: For a positive number."
},
{
"code": "// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { int a = 155; System.out.println(\"Integral Number = \" + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print(\"Number of Trailing Zeros = \"); System.out.println(Integer.numberOfTrailingZeros(a)); a = 24; System.out.println(\"Integral Number = \" + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print(\"Number of Trailing Zeros = \"); System.out.println(Integer.numberOfTrailingZeros(a)); }}",
"e": 27066,
"s": 26340,
"text": null
},
{
"code": null,
"e": 27168,
"s": 27066,
"text": "Integral Number = 155\nNumber of Trailing Zeros = 0\nIntegral Number = 24\nNumber of Trailing Zeros = 3\n"
},
{
"code": null,
"e": 27390,
"s": 27168,
"text": "Note: Here the number of trailing zeros is equal to 0 for 155 ,this is because in the binary representation 10011011 there is no zero which is following the lowest-order (ie.Rightmost or least significant “1” bit)one-bit."
},
{
"code": null,
"e": 27424,
"s": 27390,
"text": "Program 2: For a negative number."
},
{
"code": "// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { int a = -1; System.out.println(\"Integral Number = \" + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print(\"Number of Trailing Zeros = \"); System.out.println(Integer.numberOfTrailingZeros(a)); a = -90; System.out.println(\"Integral Number = \" + a); // Returns the number of zero bits following the lowest-order //rightmost one-bit System.out.print(\"Number of Trailing Zeros = \"); System.out.println(Integer.numberOfTrailingZeros(a)); }}",
"e": 28145,
"s": 27424,
"text": null
},
{
"code": null,
"e": 28247,
"s": 28145,
"text": "Integral Number = -1\nNumber of Trailing Zeros = 0\nIntegral Number = -90\nNumber of Trailing Zeros = 1\n"
},
{
"code": null,
"e": 28359,
"s": 28247,
"text": "Program 3: For a decimal value.Note: It returns an error message when a decimal value is passed as an argument."
},
{
"code": "// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { System.out.println(\"Number of trailing zeros = \"+ Integer.numberOfTrailingZeros(12.66)); }}",
"e": 28642,
"s": 28359,
"text": null
},
{
"code": null,
"e": 28650,
"s": 28642,
"text": "Output:"
},
{
"code": null,
"e": 28919,
"s": 28650,
"text": "prog.java:10: error: incompatible types: possible lossy conversion from double to int\n Integer.numberOfTrailingZeros(12.66));\n ^\nNote: Some messages have been simplified; recompile with \n-Xdiags:verbose to get full output\n1 error\n"
},
{
"code": null,
"e": 29029,
"s": 28919,
"text": "Program 4: For a string value.Note: It returns an error message when a string value is passed as an argument."
},
{
"code": "// Java program to illustrate the// Java.lang.Integer.numberOfTrailingZeros() methodimport java.lang.*; public class TrailingZeros { public static void main(String[] args) { System.out.println(\"Number of trailing zeros = \" + Integer.numberOfTrailingZeros(\"12\"));}}",
"e": 29324,
"s": 29029,
"text": null
},
{
"code": null,
"e": 29332,
"s": 29324,
"text": "Output:"
},
{
"code": null,
"e": 29637,
"s": 29332,
"text": "prog.java:10: error: incompatible types: String cannot be converted to int\n + Integer.numberOfTrailingZeros(\"12\"));\n ^\nNote: Some messages have been simplified; recompile with \n-Xdiags:verbose to get full output\n1 error\n"
},
{
"code": null,
"e": 29652,
"s": 29637,
"text": "Java-Functions"
},
{
"code": null,
"e": 29665,
"s": 29652,
"text": "Java-Integer"
},
{
"code": null,
"e": 29683,
"s": 29665,
"text": "Java-lang package"
},
{
"code": null,
"e": 29688,
"s": 29683,
"text": "Java"
},
{
"code": null,
"e": 29693,
"s": 29688,
"text": "Java"
},
{
"code": null,
"e": 29791,
"s": 29693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29806,
"s": 29791,
"text": "Stream In Java"
},
{
"code": null,
"e": 29827,
"s": 29806,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29846,
"s": 29827,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29876,
"s": 29846,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29922,
"s": 29876,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29939,
"s": 29922,
"text": "Generics in Java"
},
{
"code": null,
"e": 29960,
"s": 29939,
"text": "Introduction to Java"
},
{
"code": null,
"e": 30003,
"s": 29960,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30039,
"s": 30003,
"text": "Internal Working of HashMap in Java"
}
] |
How to Copy One HashMap to Another HashMap in Java? - GeeksforGeeks
|
22 Dec, 2021
HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass.
Given a HashMap, there are three ways one can copy the given HashMap to another:
By normally iterating and putting it to another HashMap using put(k, v) method.Using putAll() method.Using copy constructor.
By normally iterating and putting it to another HashMap using put(k, v) method.
Using putAll() method.
Using copy constructor.
Method 1: By normally iterating and putting it to another HashMap using put(k, v) Method.
A simple solution is to iterate through the map and use put(Key,Value) once for each mapping key and value in the another Map.
Java
// Java program to iterate through the// first map and put it in the second map import java.util.HashMap;import java.util.Map; class GFG { public static <K, V> Map<K, V> copyMap(Map<K, V> original) { Map<K, V> second_Map = new HashMap<>(); // Start the iteration and copy the Key and Value // for each Map to the other Map. for (Map.Entry<K, V> entry : original.entrySet()) { // using put method to copy one Map to Other second_Map.put(entry.getKey(), entry.getValue()); } return second_Map; } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); // copyMap method would copy the original // hashMap to second_Map Map<String, Integer> second_Map = copyMap(hashMap); System.out.println(second_Map); }}
{A=1, B=2, C=3}
Method 2: Using putAll(k, v) Method.
Map.putAll(k,v) method is used to copy one HashMap to another empty HashMap.
Syntax:
new_hash_map.putAll(exist_hash_map)
Parameters: The method takes one parameter exist_hash_map that refers to the existing map we want to copy from.
Return Value: The method does not return any values.
Exception: The method throws NullPointerException if the map we want to copy from is NULL.
Java
// Java program to copy hashmap to// another hashmap using putAll() method import java.util.HashMap;import java.util.Map; class GFG { public static <K, V> Map<K, V> copyMap(Map<K, V> original) { Map<K, V> second_map = new HashMap<>(); // using putAll method to copy from original Map to // second_map second_map.putAll(original); return second_map; } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); // copyMap method would copy the original // hashMap to second_Map Map<String, Integer> second_map = copyMap(hashMap); System.out.println(second_map); }}
{A=1, B=2, C=3}
Method 3: Using copy constructor.
It is one of the shortest and easiest ways to copy one HashMap to another.
We can use a copy constructor to copy a map which is a special constructor for creating a new object as a copy of an existing object.
Java
import java.util.HashMap;import java.util.Map; class GFG { // using copy constructor to return the original map // and then copy it in second_map public static <K, V> Map<K, V> copyMap(Map<K, V> original) { // constructor by passing original hashmap // in the parameter returns the new hashmap // with the copied content of the original one return new HashMap<>(original); } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); // copyMap method would copy the original // hashMap to second_Map Map<String, Integer> second_map = copyMap(hashMap); System.out.println(second_map); }}
{A=1, B=2, C=3}
prachisoda1234
rkbhola5
Java-HashMap
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class 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": 25469,
"s": 25441,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 25822,
"s": 25469,
"text": "HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass."
},
{
"code": null,
"e": 25903,
"s": 25822,
"text": "Given a HashMap, there are three ways one can copy the given HashMap to another:"
},
{
"code": null,
"e": 26028,
"s": 25903,
"text": "By normally iterating and putting it to another HashMap using put(k, v) method.Using putAll() method.Using copy constructor."
},
{
"code": null,
"e": 26108,
"s": 26028,
"text": "By normally iterating and putting it to another HashMap using put(k, v) method."
},
{
"code": null,
"e": 26131,
"s": 26108,
"text": "Using putAll() method."
},
{
"code": null,
"e": 26155,
"s": 26131,
"text": "Using copy constructor."
},
{
"code": null,
"e": 26245,
"s": 26155,
"text": "Method 1: By normally iterating and putting it to another HashMap using put(k, v) Method."
},
{
"code": null,
"e": 26372,
"s": 26245,
"text": "A simple solution is to iterate through the map and use put(Key,Value) once for each mapping key and value in the another Map."
},
{
"code": null,
"e": 26377,
"s": 26372,
"text": "Java"
},
{
"code": "// Java program to iterate through the// first map and put it in the second map import java.util.HashMap;import java.util.Map; class GFG { public static <K, V> Map<K, V> copyMap(Map<K, V> original) { Map<K, V> second_Map = new HashMap<>(); // Start the iteration and copy the Key and Value // for each Map to the other Map. for (Map.Entry<K, V> entry : original.entrySet()) { // using put method to copy one Map to Other second_Map.put(entry.getKey(), entry.getValue()); } return second_Map; } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put(\"A\", 1); hashMap.put(\"B\", 2); hashMap.put(\"C\", 3); // copyMap method would copy the original // hashMap to second_Map Map<String, Integer> second_Map = copyMap(hashMap); System.out.println(second_Map); }}",
"e": 27366,
"s": 26377,
"text": null
},
{
"code": null,
"e": 27382,
"s": 27366,
"text": "{A=1, B=2, C=3}"
},
{
"code": null,
"e": 27419,
"s": 27382,
"text": "Method 2: Using putAll(k, v) Method."
},
{
"code": null,
"e": 27496,
"s": 27419,
"text": "Map.putAll(k,v) method is used to copy one HashMap to another empty HashMap."
},
{
"code": null,
"e": 27504,
"s": 27496,
"text": "Syntax:"
},
{
"code": null,
"e": 27540,
"s": 27504,
"text": "new_hash_map.putAll(exist_hash_map)"
},
{
"code": null,
"e": 27652,
"s": 27540,
"text": "Parameters: The method takes one parameter exist_hash_map that refers to the existing map we want to copy from."
},
{
"code": null,
"e": 27705,
"s": 27652,
"text": "Return Value: The method does not return any values."
},
{
"code": null,
"e": 27796,
"s": 27705,
"text": "Exception: The method throws NullPointerException if the map we want to copy from is NULL."
},
{
"code": null,
"e": 27801,
"s": 27796,
"text": "Java"
},
{
"code": "// Java program to copy hashmap to// another hashmap using putAll() method import java.util.HashMap;import java.util.Map; class GFG { public static <K, V> Map<K, V> copyMap(Map<K, V> original) { Map<K, V> second_map = new HashMap<>(); // using putAll method to copy from original Map to // second_map second_map.putAll(original); return second_map; } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put(\"A\", 1); hashMap.put(\"B\", 2); hashMap.put(\"C\", 3); // copyMap method would copy the original // hashMap to second_Map Map<String, Integer> second_map = copyMap(hashMap); System.out.println(second_map); }}",
"e": 28584,
"s": 27801,
"text": null
},
{
"code": null,
"e": 28600,
"s": 28584,
"text": "{A=1, B=2, C=3}"
},
{
"code": null,
"e": 28634,
"s": 28600,
"text": "Method 3: Using copy constructor."
},
{
"code": null,
"e": 28709,
"s": 28634,
"text": "It is one of the shortest and easiest ways to copy one HashMap to another."
},
{
"code": null,
"e": 28843,
"s": 28709,
"text": "We can use a copy constructor to copy a map which is a special constructor for creating a new object as a copy of an existing object."
},
{
"code": null,
"e": 28848,
"s": 28843,
"text": "Java"
},
{
"code": "import java.util.HashMap;import java.util.Map; class GFG { // using copy constructor to return the original map // and then copy it in second_map public static <K, V> Map<K, V> copyMap(Map<K, V> original) { // constructor by passing original hashmap // in the parameter returns the new hashmap // with the copied content of the original one return new HashMap<>(original); } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put(\"A\", 1); hashMap.put(\"B\", 2); hashMap.put(\"C\", 3); // copyMap method would copy the original // hashMap to second_Map Map<String, Integer> second_map = copyMap(hashMap); System.out.println(second_map); }}",
"e": 29650,
"s": 28848,
"text": null
},
{
"code": null,
"e": 29666,
"s": 29650,
"text": "{A=1, B=2, C=3}"
},
{
"code": null,
"e": 29681,
"s": 29666,
"text": "prachisoda1234"
},
{
"code": null,
"e": 29690,
"s": 29681,
"text": "rkbhola5"
},
{
"code": null,
"e": 29703,
"s": 29690,
"text": "Java-HashMap"
},
{
"code": null,
"e": 29710,
"s": 29703,
"text": "Picked"
},
{
"code": null,
"e": 29734,
"s": 29710,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29739,
"s": 29734,
"text": "Java"
},
{
"code": null,
"e": 29753,
"s": 29739,
"text": "Java Programs"
},
{
"code": null,
"e": 29772,
"s": 29753,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29777,
"s": 29772,
"text": "Java"
},
{
"code": null,
"e": 29875,
"s": 29777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29890,
"s": 29875,
"text": "Stream In Java"
},
{
"code": null,
"e": 29909,
"s": 29890,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29927,
"s": 29909,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29947,
"s": 29927,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29971,
"s": 29947,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29999,
"s": 29971,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 30043,
"s": 29999,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 30069,
"s": 30043,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30103,
"s": 30069,
"text": "Convert Double to Integer in Java"
}
] |
Check whether four points make a parallelogram - GeeksforGeeks
|
14 Oct, 2017
Given four points in a 2-dimensional space we need to find out whether they make a parallelogram or not.
A parallelogram has four sides. Two opposite sides are parallel and are of same lengths.
Examples:
Points = [(0, 0), (4, 0), (1, 3), (5, 3)]
Above points make a parallelogram.
Points = [(0, 0), (2, 0), (4, 0), (2, 2)]
Above points does not make a parallelogram
as first three points itself are linear.
Problems for checking square and rectangle can be read from Square checking and Rectangle checking but in this problem, we need to check for the parallelogram. The main properties of the parallelogram are that opposite sides of parallelogram are parallel and of equal length and diagonals of parallelogram bisect each other. We use the second property to solve this problem. As there are four points, we can get total 6 midpoints by considering each pair. Now for four points to make a parallelogram, 2 of the midpoints should be equal and rest of them should be different.In below code, we have created a map, which stores pairs corresponding to each midpoint. After calculating all midpoints, we have iterated over the map and check the occurrence of each midpoint, If exactly one midpoint occurred twice and other have occurred once, then given four points make a parallelogram otherwise not.
// C++ code to test whether four points make a // parallelogram or not#include <bits/stdc++.h>using namespace std; // structure to represent a pointstruct point { double x, y; point() { } point(double x, double y) : x(x), y(y) { } // defining operator < to compare two points bool operator<(const point& other) const { if (x < other.x) { return true; } else if (x == other.x) { if (y < other.y) { return true; } } return false; }}; // Utility method to return mid point of two pointspoint getMidPoint(point points[], int i, int j){ return point((points[i].x + points[j].x) / 2.0, (points[i].y + points[j].y) / 2.0);} // method returns true if point of points array form // a parallelogrambool isParallelogram(point points[]){ map<point, vector<point> > midPointMap; // looping over all pairs of point to store their // mid points int P = 4; for (int i = 0; i < P; i++) { for (int j = i + 1; j < P; j++) { point temp = getMidPoint(points, i, j); // storing point pair, corresponding to // the mid point midPointMap[temp].push_back(point(i, j)); } } int two = 0, one = 0; // looping over (midpoint, (corresponding pairs)) // map to check the occurence of each midpoint for (auto x : midPointMap) { // updating midpoint count which occurs twice if (x.second.size() == 2) two++; // updating midpoing count which occurs once else if (x.second.size() == 1) one++; // if midpoint count is more than 2, then // parallelogram is not possible else return false; } // for parallelogram, one mid point should come // twice and other mid points should come once if (two == 1 && one == 4) return true; return false;} // Driver code to test above methodsint main(){ point points[4]; points[0] = point(0, 0); points[1] = point(4, 0); points[2] = point(1, 3); points[3] = point(5, 3); if (isParallelogram(points)) cout << "Given points form a parallelogram"; else cout << "Given points does not form a " "parallelogram"; return 0;}
Output:
Given points form a parallelogram
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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
Program to find line passing through 2 Points
Equation of circle when three points on the circle are given
Maximum Manhattan distance between a distinct pair from N coordinates
Orientation of 3 ordered points
Minimum Cost Polygon Triangulation
Quickhull Algorithm for Convex Hull
Maximum number of region in which N non-parallel lines can divide a plane
Check if a line touches or intersects a circle
|
[
{
"code": null,
"e": 26508,
"s": 26480,
"text": "\n14 Oct, 2017"
},
{
"code": null,
"e": 26613,
"s": 26508,
"text": "Given four points in a 2-dimensional space we need to find out whether they make a parallelogram or not."
},
{
"code": null,
"e": 26702,
"s": 26613,
"text": "A parallelogram has four sides. Two opposite sides are parallel and are of same lengths."
},
{
"code": null,
"e": 26712,
"s": 26702,
"text": "Examples:"
},
{
"code": null,
"e": 26921,
"s": 26712,
"text": "Points = [(0, 0), (4, 0), (1, 3), (5, 3)]\nAbove points make a parallelogram.\n\nPoints = [(0, 0), (2, 0), (4, 0), (2, 2)]\nAbove points does not make a parallelogram \nas first three points itself are linear.\n"
},
{
"code": null,
"e": 27817,
"s": 26921,
"text": "Problems for checking square and rectangle can be read from Square checking and Rectangle checking but in this problem, we need to check for the parallelogram. The main properties of the parallelogram are that opposite sides of parallelogram are parallel and of equal length and diagonals of parallelogram bisect each other. We use the second property to solve this problem. As there are four points, we can get total 6 midpoints by considering each pair. Now for four points to make a parallelogram, 2 of the midpoints should be equal and rest of them should be different.In below code, we have created a map, which stores pairs corresponding to each midpoint. After calculating all midpoints, we have iterated over the map and check the occurrence of each midpoint, If exactly one midpoint occurred twice and other have occurred once, then given four points make a parallelogram otherwise not."
},
{
"code": "// C++ code to test whether four points make a // parallelogram or not#include <bits/stdc++.h>using namespace std; // structure to represent a pointstruct point { double x, y; point() { } point(double x, double y) : x(x), y(y) { } // defining operator < to compare two points bool operator<(const point& other) const { if (x < other.x) { return true; } else if (x == other.x) { if (y < other.y) { return true; } } return false; }}; // Utility method to return mid point of two pointspoint getMidPoint(point points[], int i, int j){ return point((points[i].x + points[j].x) / 2.0, (points[i].y + points[j].y) / 2.0);} // method returns true if point of points array form // a parallelogrambool isParallelogram(point points[]){ map<point, vector<point> > midPointMap; // looping over all pairs of point to store their // mid points int P = 4; for (int i = 0; i < P; i++) { for (int j = i + 1; j < P; j++) { point temp = getMidPoint(points, i, j); // storing point pair, corresponding to // the mid point midPointMap[temp].push_back(point(i, j)); } } int two = 0, one = 0; // looping over (midpoint, (corresponding pairs)) // map to check the occurence of each midpoint for (auto x : midPointMap) { // updating midpoint count which occurs twice if (x.second.size() == 2) two++; // updating midpoing count which occurs once else if (x.second.size() == 1) one++; // if midpoint count is more than 2, then // parallelogram is not possible else return false; } // for parallelogram, one mid point should come // twice and other mid points should come once if (two == 1 && one == 4) return true; return false;} // Driver code to test above methodsint main(){ point points[4]; points[0] = point(0, 0); points[1] = point(4, 0); points[2] = point(1, 3); points[3] = point(5, 3); if (isParallelogram(points)) cout << \"Given points form a parallelogram\"; else cout << \"Given points does not form a \" \"parallelogram\"; return 0;}",
"e": 30169,
"s": 27817,
"text": null
},
{
"code": null,
"e": 30177,
"s": 30169,
"text": "Output:"
},
{
"code": null,
"e": 30212,
"s": 30177,
"text": "Given points form a parallelogram\n"
},
{
"code": null,
"e": 30515,
"s": 30212,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30640,
"s": 30515,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30650,
"s": 30640,
"text": "Geometric"
},
{
"code": null,
"e": 30660,
"s": 30650,
"text": "Geometric"
},
{
"code": null,
"e": 30758,
"s": 30660,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30824,
"s": 30758,
"text": "Haversine formula to find distance between two points on a sphere"
},
{
"code": null,
"e": 30856,
"s": 30824,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 30902,
"s": 30856,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 30963,
"s": 30902,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 31033,
"s": 30963,
"text": "Maximum Manhattan distance between a distinct pair from N coordinates"
},
{
"code": null,
"e": 31065,
"s": 31033,
"text": "Orientation of 3 ordered points"
},
{
"code": null,
"e": 31100,
"s": 31065,
"text": "Minimum Cost Polygon Triangulation"
},
{
"code": null,
"e": 31136,
"s": 31100,
"text": "Quickhull Algorithm for Convex Hull"
},
{
"code": null,
"e": 31210,
"s": 31136,
"text": "Maximum number of region in which N non-parallel lines can divide a plane"
}
] |
How to Delete a Specific Row from SQLite Table using Python ? - GeeksforGeeks
|
28 Apr, 2021
In this article, we will discuss how to delete of a specific row from the SQLite table using Python.
In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause.
Syntax:
DELETE FROM table_name
WHERE condition;
We are going to create a table and then perform deletion operations in it.
Python3
# importing sqlite moduleimport sqlite3 # create connection to the database # my_databaseconnection = sqlite3.connect('my_database.db') # create table named address of customers # with 4 columns id,name age and addressconnection.execute('''CREATE TABLE ship (ship_id INT, ship_name \TEXT NOT NULL, ship_destination CHAR(50) NOT NULL); ''') print("Ship table created successfully") # close the connectionconnection.close()
Output:
Ship table created successfully
Example 1:
Python program to insert data and delete data where 2 is ship id.
Python3
# import sqlite module databaseimport sqlite3 # create connection to the database# my_databaseconnection = sqlite3.connect('my_database.db') # insert query to insert valuesconnection.execute("INSERT INTO ship VALUES (1, 'tata-hitachi','noida' )")connection.execute("INSERT INTO ship VALUES (2, 'tata-mumbai','mumbai' )")connection.execute("INSERT INTO ship VALUES (3, 'tata-express','hyderabad' )") # query to display all data in the tablecursor = connection.execute("SELECT * from ship")print("Actual data") # display row by rowfor row in cursor: print(row) # query to delete all data where ship_id = 2connection.execute("DELETE from ship where ship_id=2") print("After deleting ship id = 2 row") # display row by rowcursor = connection.execute("SELECT * from ship")for row in cursor: print(row) # close the connectionconnection.close()
Output:
Example 2:
In this example delete data where the ship address is hyderabad on the same table.
Python3
# import sqlite module databaseimport sqlite3 # create connection to the database# my_databaseconnection = sqlite3.connect('my_database.db') # insert query to insert valuesconnection.execute("INSERT INTO ship VALUES (1, 'tata-hitachi','noida' )")connection.execute("INSERT INTO ship VALUES (2, 'tata-mumbai','mumbai' )")connection.execute("INSERT INTO ship VALUES (3, 'tata-express','hyderabad' )") # query to display all data in the tablecursor = connection.execute("SELECT * from ship")print("Actual data") # display row by rowfor row in cursor: print(row) # query to delete all data where ship_id = 2connection.execute("DELETE from ship where ship_destination='hyderabad'") print("After deleting ship address = hyderabad row") # display row by rowcursor = connection.execute("SELECT * from ship")for row in cursor: print(row) # close the connectionconnection.close()
Output:
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25799,
"s": 25771,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 25900,
"s": 25799,
"text": "In this article, we will discuss how to delete of a specific row from the SQLite table using Python."
},
{
"code": null,
"e": 26168,
"s": 25900,
"text": "In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause."
},
{
"code": null,
"e": 26176,
"s": 26168,
"text": "Syntax:"
},
{
"code": null,
"e": 26199,
"s": 26176,
"text": "DELETE FROM table_name"
},
{
"code": null,
"e": 26216,
"s": 26199,
"text": "WHERE condition;"
},
{
"code": null,
"e": 26291,
"s": 26216,
"text": "We are going to create a table and then perform deletion operations in it."
},
{
"code": null,
"e": 26299,
"s": 26291,
"text": "Python3"
},
{
"code": "# importing sqlite moduleimport sqlite3 # create connection to the database # my_databaseconnection = sqlite3.connect('my_database.db') # create table named address of customers # with 4 columns id,name age and addressconnection.execute('''CREATE TABLE ship (ship_id INT, ship_name \\TEXT NOT NULL, ship_destination CHAR(50) NOT NULL); ''') print(\"Ship table created successfully\") # close the connectionconnection.close()",
"e": 26725,
"s": 26299,
"text": null
},
{
"code": null,
"e": 26733,
"s": 26725,
"text": "Output:"
},
{
"code": null,
"e": 26765,
"s": 26733,
"text": "Ship table created successfully"
},
{
"code": null,
"e": 26776,
"s": 26765,
"text": "Example 1:"
},
{
"code": null,
"e": 26842,
"s": 26776,
"text": "Python program to insert data and delete data where 2 is ship id."
},
{
"code": null,
"e": 26850,
"s": 26842,
"text": "Python3"
},
{
"code": "# import sqlite module databaseimport sqlite3 # create connection to the database# my_databaseconnection = sqlite3.connect('my_database.db') # insert query to insert valuesconnection.execute(\"INSERT INTO ship VALUES (1, 'tata-hitachi','noida' )\")connection.execute(\"INSERT INTO ship VALUES (2, 'tata-mumbai','mumbai' )\")connection.execute(\"INSERT INTO ship VALUES (3, 'tata-express','hyderabad' )\") # query to display all data in the tablecursor = connection.execute(\"SELECT * from ship\")print(\"Actual data\") # display row by rowfor row in cursor: print(row) # query to delete all data where ship_id = 2connection.execute(\"DELETE from ship where ship_id=2\") print(\"After deleting ship id = 2 row\") # display row by rowcursor = connection.execute(\"SELECT * from ship\")for row in cursor: print(row) # close the connectionconnection.close()",
"e": 27706,
"s": 26850,
"text": null
},
{
"code": null,
"e": 27714,
"s": 27706,
"text": "Output:"
},
{
"code": null,
"e": 27725,
"s": 27714,
"text": "Example 2:"
},
{
"code": null,
"e": 27808,
"s": 27725,
"text": "In this example delete data where the ship address is hyderabad on the same table."
},
{
"code": null,
"e": 27816,
"s": 27808,
"text": "Python3"
},
{
"code": "# import sqlite module databaseimport sqlite3 # create connection to the database# my_databaseconnection = sqlite3.connect('my_database.db') # insert query to insert valuesconnection.execute(\"INSERT INTO ship VALUES (1, 'tata-hitachi','noida' )\")connection.execute(\"INSERT INTO ship VALUES (2, 'tata-mumbai','mumbai' )\")connection.execute(\"INSERT INTO ship VALUES (3, 'tata-express','hyderabad' )\") # query to display all data in the tablecursor = connection.execute(\"SELECT * from ship\")print(\"Actual data\") # display row by rowfor row in cursor: print(row) # query to delete all data where ship_id = 2connection.execute(\"DELETE from ship where ship_destination='hyderabad'\") print(\"After deleting ship address = hyderabad row\") # display row by rowcursor = connection.execute(\"SELECT * from ship\")for row in cursor: print(row) # close the connectionconnection.close()",
"e": 28704,
"s": 27816,
"text": null
},
{
"code": null,
"e": 28712,
"s": 28704,
"text": "Output:"
},
{
"code": null,
"e": 28719,
"s": 28712,
"text": "Picked"
},
{
"code": null,
"e": 28733,
"s": 28719,
"text": "Python-SQLite"
},
{
"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": 28856,
"s": 28838,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28888,
"s": 28856,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28910,
"s": 28888,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28952,
"s": 28910,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28978,
"s": 28952,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29022,
"s": 28978,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29051,
"s": 29022,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29087,
"s": 29051,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29124,
"s": 29087,
"text": "Create a Pandas DataFrame from Lists"
}
] |
C# | How to get the Standard Input Stream through Console - GeeksforGeeks
|
28 Jan, 2019
Given a normal console, the task is to get the Standard Input Stream through this Console in C#.
Approach: This can be done using the In property in the Console class of the System package in C#.
Program: Getting the Standard Input Stream
// C# program to illustrate the// Console.In 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 Standard Input Stream Console.WriteLine("Standard Input Stream: {0}", Console.In); } }}
Output:
Note: The TextReader represents a reader that can read a sequential series of characters.
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Arrays
|
[
{
"code": null,
"e": 25355,
"s": 25327,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 25452,
"s": 25355,
"text": "Given a normal console, the task is to get the Standard Input Stream through this Console in C#."
},
{
"code": null,
"e": 25551,
"s": 25452,
"text": "Approach: This can be done using the In property in the Console class of the System package in C#."
},
{
"code": null,
"e": 25594,
"s": 25551,
"text": "Program: Getting the Standard Input Stream"
},
{
"code": "// C# program to illustrate the// Console.In 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 Standard Input Stream Console.WriteLine(\"Standard Input Stream: {0}\", Console.In); } }}",
"e": 25994,
"s": 25594,
"text": null
},
{
"code": null,
"e": 26002,
"s": 25994,
"text": "Output:"
},
{
"code": null,
"e": 26092,
"s": 26002,
"text": "Note: The TextReader represents a reader that can read a sequential series of characters."
},
{
"code": null,
"e": 26113,
"s": 26092,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 26116,
"s": 26113,
"text": "C#"
},
{
"code": null,
"e": 26214,
"s": 26116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26229,
"s": 26214,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26251,
"s": 26229,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 26297,
"s": 26251,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26320,
"s": 26297,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26342,
"s": 26320,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26360,
"s": 26342,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26382,
"s": 26360,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 26422,
"s": 26382,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 26453,
"s": 26422,
"text": "Introduction to .NET Framework"
}
] |
CSS | margin-inline Property - GeeksforGeeks
|
19 Feb, 2021
The margin-inline property is used to define the logical inline start and end margin of an element. This property helps to place margin depending on the element’s writing mode, directionality, and text orientation.Syntax:
margin-inline: length | auto | initial | inherit | unset;
Property values:
length: It sets a fixed value defined in px, cm, pt. Negative values are also allowed. 0px is the default value.
auto: It is used when it is desired that the browser determines the width of the left margin.
initial: It is used to set the value of the margin-left property to its default value.
inherit: It is used when it is desired that the element inherit the margin-left property of its parent as its own.
unset: It is used unset the default margin-block.
Below examples illustrate the margin-inline property in CSS:Example 1:
html
<!DOCTYPE html><html> <head> <title>CSS | margin-inline Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 110px; } .geek { background-color: purple; writing-mode: vertical-rl; margin-inline: 25px 10px; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-inline Property</b> <br><br> <div> <b class="geek">Cascading Stylesheet</b> </div> </center></body> </html>
Output:
Example 2:
html
<!DOCTYPE html><html> <head> <title>CSS | margin-inline Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 110px; } .geek { background-color: purple; writing-mode: vertical-rl; margin-inline: auto; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-inline Property</b> <br><br> <div> <b class="geek">Cascading Stylesheet</b> </div> </center></body> </html>
Output:
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/margin-inline Supported Browsers: The browser supported by margin-inline property are listed below:
Internet Explorer
Mozilla Firefox
arorakashish0911
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
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": 26621,
"s": 26593,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 26845,
"s": 26621,
"text": "The margin-inline property is used to define the logical inline start and end margin of an element. This property helps to place margin depending on the element’s writing mode, directionality, and text orientation.Syntax: "
},
{
"code": null,
"e": 26903,
"s": 26845,
"text": "margin-inline: length | auto | initial | inherit | unset;"
},
{
"code": null,
"e": 26922,
"s": 26903,
"text": "Property values: "
},
{
"code": null,
"e": 27035,
"s": 26922,
"text": "length: It sets a fixed value defined in px, cm, pt. Negative values are also allowed. 0px is the default value."
},
{
"code": null,
"e": 27129,
"s": 27035,
"text": "auto: It is used when it is desired that the browser determines the width of the left margin."
},
{
"code": null,
"e": 27216,
"s": 27129,
"text": "initial: It is used to set the value of the margin-left property to its default value."
},
{
"code": null,
"e": 27331,
"s": 27216,
"text": "inherit: It is used when it is desired that the element inherit the margin-left property of its parent as its own."
},
{
"code": null,
"e": 27381,
"s": 27331,
"text": "unset: It is used unset the default margin-block."
},
{
"code": null,
"e": 27454,
"s": 27381,
"text": "Below examples illustrate the margin-inline property in CSS:Example 1: "
},
{
"code": null,
"e": 27459,
"s": 27454,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | margin-inline Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 110px; } .geek { background-color: purple; writing-mode: vertical-rl; margin-inline: 25px 10px; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-inline Property</b> <br><br> <div> <b class=\"geek\">Cascading Stylesheet</b> </div> </center></body> </html> ",
"e": 28101,
"s": 27459,
"text": null
},
{
"code": null,
"e": 28111,
"s": 28101,
"text": "Output: "
},
{
"code": null,
"e": 28124,
"s": 28111,
"text": "Example 2: "
},
{
"code": null,
"e": 28129,
"s": 28124,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | margin-inline Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 110px; } .geek { background-color: purple; writing-mode: vertical-rl; margin-inline: auto; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-inline Property</b> <br><br> <div> <b class=\"geek\">Cascading Stylesheet</b> </div> </center></body> </html> ",
"e": 28774,
"s": 28129,
"text": null
},
{
"code": null,
"e": 28784,
"s": 28774,
"text": "Output: "
},
{
"code": null,
"e": 28946,
"s": 28784,
"text": "Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/margin-inline Supported Browsers: The browser supported by margin-inline property are listed below: "
},
{
"code": null,
"e": 28964,
"s": 28946,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28980,
"s": 28964,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 28999,
"s": 28982,
"text": "arorakashish0911"
},
{
"code": null,
"e": 29014,
"s": 28999,
"text": "CSS-Properties"
},
{
"code": null,
"e": 29018,
"s": 29014,
"text": "CSS"
},
{
"code": null,
"e": 29035,
"s": 29018,
"text": "Web Technologies"
},
{
"code": null,
"e": 29133,
"s": 29035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29172,
"s": 29133,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29209,
"s": 29172,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29238,
"s": 29209,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29280,
"s": 29238,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29315,
"s": 29280,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 29355,
"s": 29315,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29388,
"s": 29355,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29433,
"s": 29388,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29476,
"s": 29433,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
get_log driver method - Selenium Python - GeeksforGeeks
|
03 Dec, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around get_log driver method in Selenium. get_log method is used to get the log for a given log type.
Syntax –
driver.get_log(log_type)
Example – Now one can use get_log method as a driver method as below –
driver.get("https://www.geeksforgeeks.org/")
driver.get_log("browser")
To demonstrate, get_log method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. let’s get log of type browser
Program –
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get browser logdriver.get_log("browser")
Output – Screenshot of log –
Akanksha_Rai
Python-selenium
selenium
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 26277,
"s": 25537,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. "
},
{
"code": null,
"e": 26401,
"s": 26277,
"text": "This article revolves around get_log driver method in Selenium. get_log method is used to get the log for a given log type."
},
{
"code": null,
"e": 26411,
"s": 26401,
"text": "Syntax – "
},
{
"code": null,
"e": 26436,
"s": 26411,
"text": "driver.get_log(log_type)"
},
{
"code": null,
"e": 26508,
"s": 26436,
"text": "Example – Now one can use get_log method as a driver method as below – "
},
{
"code": null,
"e": 26579,
"s": 26508,
"text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_log(\"browser\")"
},
{
"code": null,
"e": 26747,
"s": 26579,
"text": "To demonstrate, get_log method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. let’s get log of type browser"
},
{
"code": null,
"e": 26758,
"s": 26747,
"text": "Program – "
},
{
"code": null,
"e": 26766,
"s": 26758,
"text": "Python3"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get browser logdriver.get_log(\"browser\")",
"e": 26980,
"s": 26766,
"text": null
},
{
"code": null,
"e": 27011,
"s": 26980,
"text": "Output – Screenshot of log – "
},
{
"code": null,
"e": 27026,
"s": 27013,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27042,
"s": 27026,
"text": "Python-selenium"
},
{
"code": null,
"e": 27051,
"s": 27042,
"text": "selenium"
},
{
"code": null,
"e": 27058,
"s": 27051,
"text": "Python"
},
{
"code": null,
"e": 27156,
"s": 27058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27188,
"s": 27156,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27230,
"s": 27188,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27272,
"s": 27230,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27299,
"s": 27272,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27355,
"s": 27299,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27377,
"s": 27355,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27416,
"s": 27377,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27447,
"s": 27416,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27476,
"s": 27447,
"text": "Create a directory in Python"
}
] |
wcsncpy() function in C++ with example - GeeksforGeeks
|
05 Oct, 2018
The wcsncpy() function is defined in cwchar.h header file. The wcsncpy() function copies a specified number of wide characters from source to destination.
Syntax:
wchar_t *wcsncpy(wchar_t *dest,
const wchar_t *src,
size_t n);
Parameters: This method accepts the following three parameters:
dest: specifies the pointer to the destination array.
src: specifies the pointer to the source array.
n: represents the number of character to copy.
Return Value: This function returns the modified destination.
Below programs illustrate the above function:-
Example 1:
// c++ program to demonstrate// example of wcsncpy() function. #include <bits/stdc++.h>using namespace std; int main(){ // initialize the source string wchar_t src[] = L"A Computer Science portal for geeks"; // maximum length of the destination string wchar_t dest[40]; // copy the source to destination using wcsncpy wcsncpy(dest, src, 19); // Print the copied destination wcout << "Destination string is : " << dest; return 0;}
Destination string is : A Computer Science
Example 2:-
// c++ program to demonstrate// example of wcsncpy() function. #include <bits/stdc++.h>using namespace std; int main(){ // initialize the source string wchar_t src[] = L"GeeksforGeeks"; // maximum length of the destination string wchar_t dest[40]; // copy the source to destination using wcsncpy wcsncpy(dest, src, 5); // Print the copied destination wcout << "Destination string is : " << dest; return 0;}
Destination string is : Geeks
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n05 Oct, 2018"
},
{
"code": null,
"e": 25498,
"s": 25343,
"text": "The wcsncpy() function is defined in cwchar.h header file. The wcsncpy() function copies a specified number of wide characters from source to destination."
},
{
"code": null,
"e": 25506,
"s": 25498,
"text": "Syntax:"
},
{
"code": null,
"e": 25606,
"s": 25506,
"text": "wchar_t *wcsncpy(wchar_t *dest, \n const wchar_t *src, \n size_t n);\n"
},
{
"code": null,
"e": 25670,
"s": 25606,
"text": "Parameters: This method accepts the following three parameters:"
},
{
"code": null,
"e": 25724,
"s": 25670,
"text": "dest: specifies the pointer to the destination array."
},
{
"code": null,
"e": 25772,
"s": 25724,
"text": "src: specifies the pointer to the source array."
},
{
"code": null,
"e": 25819,
"s": 25772,
"text": "n: represents the number of character to copy."
},
{
"code": null,
"e": 25881,
"s": 25819,
"text": "Return Value: This function returns the modified destination."
},
{
"code": null,
"e": 25928,
"s": 25881,
"text": "Below programs illustrate the above function:-"
},
{
"code": null,
"e": 25939,
"s": 25928,
"text": "Example 1:"
},
{
"code": "// c++ program to demonstrate// example of wcsncpy() function. #include <bits/stdc++.h>using namespace std; int main(){ // initialize the source string wchar_t src[] = L\"A Computer Science portal for geeks\"; // maximum length of the destination string wchar_t dest[40]; // copy the source to destination using wcsncpy wcsncpy(dest, src, 19); // Print the copied destination wcout << \"Destination string is : \" << dest; return 0;}",
"e": 26406,
"s": 25939,
"text": null
},
{
"code": null,
"e": 26450,
"s": 26406,
"text": "Destination string is : A Computer Science\n"
},
{
"code": null,
"e": 26462,
"s": 26450,
"text": "Example 2:-"
},
{
"code": "// c++ program to demonstrate// example of wcsncpy() function. #include <bits/stdc++.h>using namespace std; int main(){ // initialize the source string wchar_t src[] = L\"GeeksforGeeks\"; // maximum length of the destination string wchar_t dest[40]; // copy the source to destination using wcsncpy wcsncpy(dest, src, 5); // Print the copied destination wcout << \"Destination string is : \" << dest; return 0;}",
"e": 26906,
"s": 26462,
"text": null
},
{
"code": null,
"e": 26937,
"s": 26906,
"text": "Destination string is : Geeks\n"
},
{
"code": null,
"e": 26949,
"s": 26937,
"text": "CPP-Library"
},
{
"code": null,
"e": 26953,
"s": 26949,
"text": "C++"
},
{
"code": null,
"e": 26957,
"s": 26953,
"text": "CPP"
},
{
"code": null,
"e": 27055,
"s": 26957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27083,
"s": 27055,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27103,
"s": 27083,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27136,
"s": 27103,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27160,
"s": 27136,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27185,
"s": 27160,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27209,
"s": 27185,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27253,
"s": 27209,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27306,
"s": 27253,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 27342,
"s": 27306,
"text": "Convert string to char array in C++"
}
] |
MoviePy – Iterating frames of Video File Clip - GeeksforGeeks
|
18 Oct, 2021
In this article we will see how we can iterate frames of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. A video is basically combination of lots of frame for each time there is a specific frame, in order to get the frame at given time we use get_frame method. Iterating frames means to traversing the frame a frame is represented in the form of numpy ndarray.
In order to do this we will use iter_frames method with the VideoFileClip objectSyntax : clip.iter_frames()Argument : It takes no argumentReturn : It returns Clip.iter_frames
Below is the implementation
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.mp4") # getting only first 5 secondsclip = clip.subclip(0, 5) # iterating framesframes = clip.iter_frames() # counter to count the framescounter = 0 # using loop to transverse the framesfor value in frames: # incrementing the counter counter += 1 # printing the value of the counterprint("Counter Value ", end = " : ")print(counter) # showing clipclip.ipython_display(width = 360)
Output :
Counter Value : 150
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting only first 5 secondsclip = clip.subclip(0, 5) # iterating framesframes = clip.iter_frames() # counter to count the framescounter = 0 # using loop to transverse the framesfor value in frames: # incrementing the counter counter += 1 # printing the value of the counterprint("Counter Value ", end = " : ")print(counter) # showing clipclip.ipython_display(width = 360)
Output :
Counter Value : 300
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
MoviePy - Done.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
gabaa406
Python-MoviePy
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": "\n18 Oct, 2021"
},
{
"code": null,
"e": 25989,
"s": 25537,
"text": "In this article we will see how we can iterate frames of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. A video is basically combination of lots of frame for each time there is a specific frame, in order to get the frame at given time we use get_frame method. Iterating frames means to traversing the frame a frame is represented in the form of numpy ndarray. "
},
{
"code": null,
"e": 26165,
"s": 25989,
"text": "In order to do this we will use iter_frames method with the VideoFileClip objectSyntax : clip.iter_frames()Argument : It takes no argumentReturn : It returns Clip.iter_frames "
},
{
"code": null,
"e": 26195,
"s": 26165,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26203,
"s": 26195,
"text": "Python3"
},
{
"code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip(\"dsa_geek.mp4\") # getting only first 5 secondsclip = clip.subclip(0, 5) # iterating framesframes = clip.iter_frames() # counter to count the framescounter = 0 # using loop to transverse the framesfor value in frames: # incrementing the counter counter += 1 # printing the value of the counterprint(\"Counter Value \", end = \" : \")print(counter) # showing clipclip.ipython_display(width = 360)",
"e": 26757,
"s": 26203,
"text": null
},
{
"code": null,
"e": 26768,
"s": 26757,
"text": "Output : "
},
{
"code": null,
"e": 27038,
"s": 26768,
"text": "Counter Value : 150\nMoviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4"
},
{
"code": null,
"e": 27058,
"s": 27040,
"text": "Another example "
},
{
"code": null,
"e": 27066,
"s": 27058,
"text": "Python3"
},
{
"code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting only first 5 secondsclip = clip.subclip(0, 5) # iterating framesframes = clip.iter_frames() # counter to count the framescounter = 0 # using loop to transverse the framesfor value in frames: # incrementing the counter counter += 1 # printing the value of the counterprint(\"Counter Value \", end = \" : \")print(counter) # showing clipclip.ipython_display(width = 360)",
"e": 27586,
"s": 27066,
"text": null
},
{
"code": null,
"e": 27597,
"s": 27586,
"text": "Output : "
},
{
"code": null,
"e": 28059,
"s": 27597,
"text": "Counter Value : 300\nMoviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4"
},
{
"code": null,
"e": 28072,
"s": 28063,
"text": "gabaa406"
},
{
"code": null,
"e": 28087,
"s": 28072,
"text": "Python-MoviePy"
},
{
"code": null,
"e": 28094,
"s": 28087,
"text": "Python"
},
{
"code": null,
"e": 28192,
"s": 28094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28224,
"s": 28192,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28266,
"s": 28224,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28308,
"s": 28266,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28364,
"s": 28308,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28391,
"s": 28364,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28430,
"s": 28391,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28461,
"s": 28430,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28483,
"s": 28461,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28512,
"s": 28483,
"text": "Create a directory in Python"
}
] |
Distance Vector Routing (DVR) Protocol - GeeksforGeeks
|
06 Nov, 2019
A distance-vector routing (DVR) protocol requires that a router inform its neighbors of topology changes periodically. Historically known as the old ARPANET routing algorithm (or known as Bellman-Ford algorithm).
Bellman Ford Basics – Each router maintains a Distance Vector table containing the distance between itself and ALL possible destination nodes. Distances,based on a chosen metric, are computed using information from the neighbors’ distance vectors.
Information kept by DV router -
Each router has an IDAssociated with each link connected to a router,
there is a link cost (static or dynamic).Intermediate hops
Distance Vector Table Initialization -Distance to itself = 0Distance to ALL other routers = infinity number.
Each router has an ID
Associated with each link connected to a router,
there is a link cost (static or dynamic).
Intermediate hops
Distance to itself = 0
Distance to ALL other routers = infinity number.
Distance Vector Algorithm –
A router transmits its distance vector to each of its neighbors in a routing packet.Each router receives and saves the most recently received distance vector from each of its neighbors.A router recalculates its distance vector when:It receives a distance vector from a neighbor containing different information than before.It discovers that a link to a neighbor has gone down.
A router transmits its distance vector to each of its neighbors in a routing packet.
Each router receives and saves the most recently received distance vector from each of its neighbors.
A router recalculates its distance vector when:It receives a distance vector from a neighbor containing different information than before.It discovers that a link to a neighbor has gone down.
It receives a distance vector from a neighbor containing different information than before.
It discovers that a link to a neighbor has gone down.
The DV calculation is based on minimizing the cost to each destination
Dx(y) = Estimate of least cost from x to y
C(x,v) = Node x knows cost to each neighbor v
Dx = [Dx(y): y ∈ N ] = Node x maintains distance vector
Node x also maintains its neighbors' distance vectors
– For each neighbor v, x maintains Dv = [Dv(y): y ∈ N ]
Note –
From time-to-time, each node sends its own distance vector estimate to neighbors.
When a node x receives new DV estimate from any neighbor v, it saves v’s distance vector and it updates its own DV using B-F equation:Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y ∈ N
Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y ∈ N
Example – Consider 3-routers X, Y and Z as shown in figure. Each router have their routing table. Every routing table will contain distance to the destination nodes.Consider router X , X will share it routing table to neighbors and neighbors will share it routing table to it to X and distance from node X to destination will be calculated using bellmen- ford equation.
Dx(y) = min { C(x,v) + Dv(y)} for each node y ∈ N
As we can see that distance will be less going from X to Z when Y is intermediate node(hop) so it will be update in routing table X.Similarly for Z also –
Finally the routing table for all –Advantages of Distance Vector routing –
It is simpler to configure and maintain than link state routing.Disadvantages of Distance Vector routing –It is slower to converge than link state.It is at risk from the count-to-infinity problem.It creates more traffic than link state since a hop count change must be propagated to all routers and processed on each router. Hop count updates take place on a periodic basis, even if there are no changes in the network topology, so bandwidth-wasting broadcasts still occur.For larger networks, distance vector routing results in larger routing tables than link state since each router must know about all other routers. This can also lead to congestion on WAN links.Note – Distance Vector routing uses UDP(User datagram protocol) for transportation.GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.GATE CS 2011, Question 52GATE CS 2011, Question 53GATE CS 2010, Question 54GATE CS 2010, Question 55GATE IT 2005, Question 28GATE CS 2014 (Set 1), Question 33GATE IT 2008, Question 65GATE CS 2014 (Set 2), Question 65References –Distance vector routing – wikipediawww.eecs.yorku.caThis article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
Disadvantages of Distance Vector routing –
It is slower to converge than link state.
It is at risk from the count-to-infinity problem.
It creates more traffic than link state since a hop count change must be propagated to all routers and processed on each router. Hop count updates take place on a periodic basis, even if there are no changes in the network topology, so bandwidth-wasting broadcasts still occur.
For larger networks, distance vector routing results in larger routing tables than link state since each router must know about all other routers. This can also lead to congestion on WAN links.
Note – Distance Vector routing uses UDP(User datagram protocol) for transportation.
GATE CS Corner Questions
Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.
GATE CS 2011, Question 52GATE CS 2011, Question 53GATE CS 2010, Question 54GATE CS 2010, Question 55GATE IT 2005, Question 28GATE CS 2014 (Set 1), Question 33GATE IT 2008, Question 65GATE CS 2014 (Set 2), Question 65
GATE CS 2011, Question 52
GATE CS 2011, Question 53
GATE CS 2010, Question 54
GATE CS 2010, Question 55
GATE IT 2005, Question 28
GATE CS 2014 (Set 1), Question 33
GATE IT 2008, Question 65
GATE CS 2014 (Set 2), Question 65
References –
Distance vector routing – wikipediawww.eecs.yorku.ca
This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
HarshithPvs
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Caesar Cipher in Cryptography
UDP Server-Client implementation in C
Socket Programming in Java
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Cache Memory in Computer Organization
|
[
{
"code": null,
"e": 37839,
"s": 37811,
"text": "\n06 Nov, 2019"
},
{
"code": null,
"e": 38052,
"s": 37839,
"text": "A distance-vector routing (DVR) protocol requires that a router inform its neighbors of topology changes periodically. Historically known as the old ARPANET routing algorithm (or known as Bellman-Ford algorithm)."
},
{
"code": null,
"e": 38300,
"s": 38052,
"text": "Bellman Ford Basics – Each router maintains a Distance Vector table containing the distance between itself and ALL possible destination nodes. Distances,based on a chosen metric, are computed using information from the neighbors’ distance vectors."
},
{
"code": null,
"e": 38572,
"s": 38300,
"text": "Information kept by DV router -\nEach router has an IDAssociated with each link connected to a router, \nthere is a link cost (static or dynamic).Intermediate hops\nDistance Vector Table Initialization -Distance to itself = 0Distance to ALL other routers = infinity number.\n"
},
{
"code": null,
"e": 38594,
"s": 38572,
"text": "Each router has an ID"
},
{
"code": null,
"e": 38686,
"s": 38594,
"text": "Associated with each link connected to a router, \nthere is a link cost (static or dynamic)."
},
{
"code": null,
"e": 38704,
"s": 38686,
"text": "Intermediate hops"
},
{
"code": null,
"e": 38727,
"s": 38704,
"text": "Distance to itself = 0"
},
{
"code": null,
"e": 38776,
"s": 38727,
"text": "Distance to ALL other routers = infinity number."
},
{
"code": null,
"e": 38804,
"s": 38776,
"text": "Distance Vector Algorithm –"
},
{
"code": null,
"e": 39181,
"s": 38804,
"text": "A router transmits its distance vector to each of its neighbors in a routing packet.Each router receives and saves the most recently received distance vector from each of its neighbors.A router recalculates its distance vector when:It receives a distance vector from a neighbor containing different information than before.It discovers that a link to a neighbor has gone down."
},
{
"code": null,
"e": 39266,
"s": 39181,
"text": "A router transmits its distance vector to each of its neighbors in a routing packet."
},
{
"code": null,
"e": 39368,
"s": 39266,
"text": "Each router receives and saves the most recently received distance vector from each of its neighbors."
},
{
"code": null,
"e": 39560,
"s": 39368,
"text": "A router recalculates its distance vector when:It receives a distance vector from a neighbor containing different information than before.It discovers that a link to a neighbor has gone down."
},
{
"code": null,
"e": 39652,
"s": 39560,
"text": "It receives a distance vector from a neighbor containing different information than before."
},
{
"code": null,
"e": 39706,
"s": 39652,
"text": "It discovers that a link to a neighbor has gone down."
},
{
"code": null,
"e": 39777,
"s": 39706,
"text": "The DV calculation is based on minimizing the cost to each destination"
},
{
"code": null,
"e": 40038,
"s": 39777,
"text": "Dx(y) = Estimate of least cost from x to y \nC(x,v) = Node x knows cost to each neighbor v\nDx = [Dx(y): y ∈ N ] = Node x maintains distance vector\nNode x also maintains its neighbors' distance vectors\n– For each neighbor v, x maintains Dv = [Dv(y): y ∈ N ]\n"
},
{
"code": null,
"e": 40045,
"s": 40038,
"text": "Note –"
},
{
"code": null,
"e": 40127,
"s": 40045,
"text": "From time-to-time, each node sends its own distance vector estimate to neighbors."
},
{
"code": null,
"e": 40320,
"s": 40127,
"text": "When a node x receives new DV estimate from any neighbor v, it saves v’s distance vector and it updates its own DV using B-F equation:Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y ∈ N\n"
},
{
"code": null,
"e": 40379,
"s": 40320,
"text": "Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y ∈ N\n"
},
{
"code": null,
"e": 40749,
"s": 40379,
"text": "Example – Consider 3-routers X, Y and Z as shown in figure. Each router have their routing table. Every routing table will contain distance to the destination nodes.Consider router X , X will share it routing table to neighbors and neighbors will share it routing table to it to X and distance from node X to destination will be calculated using bellmen- ford equation."
},
{
"code": null,
"e": 40801,
"s": 40749,
"text": " Dx(y) = min { C(x,v) + Dv(y)} for each node y ∈ N\n"
},
{
"code": null,
"e": 40956,
"s": 40801,
"text": "As we can see that distance will be less going from X to Z when Y is intermediate node(hop) so it will be update in routing table X.Similarly for Z also –"
},
{
"code": null,
"e": 41031,
"s": 40956,
"text": "Finally the routing table for all –Advantages of Distance Vector routing –"
},
{
"code": null,
"e": 42740,
"s": 41031,
"text": "It is simpler to configure and maintain than link state routing.Disadvantages of Distance Vector routing –It is slower to converge than link state.It is at risk from the count-to-infinity problem.It creates more traffic than link state since a hop count change must be propagated to all routers and processed on each router. Hop count updates take place on a periodic basis, even if there are no changes in the network topology, so bandwidth-wasting broadcasts still occur.For larger networks, distance vector routing results in larger routing tables than link state since each router must know about all other routers. This can also lead to congestion on WAN links.Note – Distance Vector routing uses UDP(User datagram protocol) for transportation.GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.GATE CS 2011, Question 52GATE CS 2011, Question 53GATE CS 2010, Question 54GATE CS 2010, Question 55GATE IT 2005, Question 28GATE CS 2014 (Set 1), Question 33GATE IT 2008, Question 65GATE CS 2014 (Set 2), Question 65References –Distance vector routing – wikipediawww.eecs.yorku.caThis article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 42783,
"s": 42740,
"text": "Disadvantages of Distance Vector routing –"
},
{
"code": null,
"e": 42825,
"s": 42783,
"text": "It is slower to converge than link state."
},
{
"code": null,
"e": 42875,
"s": 42825,
"text": "It is at risk from the count-to-infinity problem."
},
{
"code": null,
"e": 43153,
"s": 42875,
"text": "It creates more traffic than link state since a hop count change must be propagated to all routers and processed on each router. Hop count updates take place on a periodic basis, even if there are no changes in the network topology, so bandwidth-wasting broadcasts still occur."
},
{
"code": null,
"e": 43347,
"s": 43153,
"text": "For larger networks, distance vector routing results in larger routing tables than link state since each router must know about all other routers. This can also lead to congestion on WAN links."
},
{
"code": null,
"e": 43431,
"s": 43347,
"text": "Note – Distance Vector routing uses UDP(User datagram protocol) for transportation."
},
{
"code": null,
"e": 43456,
"s": 43431,
"text": "GATE CS Corner Questions"
},
{
"code": null,
"e": 43654,
"s": 43456,
"text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them."
},
{
"code": null,
"e": 43871,
"s": 43654,
"text": "GATE CS 2011, Question 52GATE CS 2011, Question 53GATE CS 2010, Question 54GATE CS 2010, Question 55GATE IT 2005, Question 28GATE CS 2014 (Set 1), Question 33GATE IT 2008, Question 65GATE CS 2014 (Set 2), Question 65"
},
{
"code": null,
"e": 43897,
"s": 43871,
"text": "GATE CS 2011, Question 52"
},
{
"code": null,
"e": 43923,
"s": 43897,
"text": "GATE CS 2011, Question 53"
},
{
"code": null,
"e": 43949,
"s": 43923,
"text": "GATE CS 2010, Question 54"
},
{
"code": null,
"e": 43975,
"s": 43949,
"text": "GATE CS 2010, Question 55"
},
{
"code": null,
"e": 44001,
"s": 43975,
"text": "GATE IT 2005, Question 28"
},
{
"code": null,
"e": 44035,
"s": 44001,
"text": "GATE CS 2014 (Set 1), Question 33"
},
{
"code": null,
"e": 44061,
"s": 44035,
"text": "GATE IT 2008, Question 65"
},
{
"code": null,
"e": 44095,
"s": 44061,
"text": "GATE CS 2014 (Set 2), Question 65"
},
{
"code": null,
"e": 44108,
"s": 44095,
"text": "References –"
},
{
"code": null,
"e": 44161,
"s": 44108,
"text": "Distance vector routing – wikipediawww.eecs.yorku.ca"
},
{
"code": null,
"e": 44461,
"s": 44161,
"text": "This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 44586,
"s": 44461,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 44598,
"s": 44586,
"text": "HarshithPvs"
},
{
"code": null,
"e": 44616,
"s": 44598,
"text": "Computer Networks"
},
{
"code": null,
"e": 44624,
"s": 44616,
"text": "GATE CS"
},
{
"code": null,
"e": 44642,
"s": 44624,
"text": "Computer Networks"
},
{
"code": null,
"e": 44740,
"s": 44642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44774,
"s": 44740,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 44803,
"s": 44774,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 44833,
"s": 44803,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 44871,
"s": 44833,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 44898,
"s": 44871,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 44922,
"s": 44898,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 44949,
"s": 44922,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 44970,
"s": 44949,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 45019,
"s": 44970,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
How to make transparent web page using CSS ? - GeeksforGeeks
|
02 Sep, 2021
You can easily make a transparent web page using the opacity property in HTML. You simply need to adjust the opacity value between 0.0 to 1.0 where a low value represents high transparency and a high value represents low transparency.
In order to make any element transparent, you need to add CSS opacity property to the parent of an element.
You can make a transparent web page using two ways.
transparency box: Using opacity to add transparency to the background of an element, makes all of its child elements inherit the same transparency.
transparency using RGBA value: The opacity property is applied to add transparency only to the background of an element.
Example 1: In the following example, when adding opacity to the transparency box, its child elements also end up having transparency, but when using transparency using rgba, it adds transparency only to the background element. So let’s add the transparency property to our web page.
HTML
<!DOCTYPE html><html> <head> <style> h1 { color: green; } .box { opacity: 0.6; background-color: green; height: 40px; width: 200px } .rgba { opacity: 0.8; background-color: green; background: rgba(76, 175, 80, 0.6); height: 40px; width: 200px } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <div class="box"> <p>Transparency Box</p> </div> <div class="rgba"> <p>Transparency Using RGBA value</p> </div> </center></body> </html>
Output:
transparency using opacity property values
Example 2: Follow the steps to create a transparent web page like making a transparent login form.
Step 1:Adding HTML. Add an input for email, password, and login button. Wrap a “form” element around them to process the input.
Step 2: Add a required CSS to design a transparent login page using RGBA value for login form as explained above. CSS properties like linear-gradient and box-shadow to achieve the desired result.
HTML
<!DOCTYPE html><html> <head> <style> h1 { color: green; } body { background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59); } .form { width: 300px; height: 300px; display: grid; place-content: center; /* Add a transparency to the background using rgba value */ background: rgba(255, 255, 255, 0.1); /* Add a transparency to shadow */ box-shadow: 0 26px 42px rgba(0, 0, 0, 0.1); } input, button { box-sizing: border-box; width: 100%; margin: 20px auto; padding: 12px 20px; border: none; background: rgba(255, 255, 255, 0.1); box-shadow: 0 13px 21px rgba(0, 0, 0, 0.05); } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <form class="form"> <input type="text" placeholder="xyz@gmail.com" /><br> <input type="password" placeholder="Enter Password" /> <br> <button type="submit">Login</button> </form> </center></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
simmytarika5
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26645,
"s": 26617,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 26881,
"s": 26645,
"text": "You can easily make a transparent web page using the opacity property in HTML. You simply need to adjust the opacity value between 0.0 to 1.0 where a low value represents high transparency and a high value represents low transparency. "
},
{
"code": null,
"e": 26989,
"s": 26881,
"text": "In order to make any element transparent, you need to add CSS opacity property to the parent of an element."
},
{
"code": null,
"e": 27041,
"s": 26989,
"text": "You can make a transparent web page using two ways."
},
{
"code": null,
"e": 27190,
"s": 27041,
"text": "transparency box: Using opacity to add transparency to the background of an element, makes all of its child elements inherit the same transparency."
},
{
"code": null,
"e": 27311,
"s": 27190,
"text": "transparency using RGBA value: The opacity property is applied to add transparency only to the background of an element."
},
{
"code": null,
"e": 27594,
"s": 27311,
"text": "Example 1: In the following example, when adding opacity to the transparency box, its child elements also end up having transparency, but when using transparency using rgba, it adds transparency only to the background element. So let’s add the transparency property to our web page."
},
{
"code": null,
"e": 27599,
"s": 27594,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color: green; } .box { opacity: 0.6; background-color: green; height: 40px; width: 200px } .rgba { opacity: 0.8; background-color: green; background: rgba(76, 175, 80, 0.6); height: 40px; width: 200px } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <div class=\"box\"> <p>Transparency Box</p> </div> <div class=\"rgba\"> <p>Transparency Using RGBA value</p> </div> </center></body> </html> ",
"e": 28315,
"s": 27599,
"text": null
},
{
"code": null,
"e": 28323,
"s": 28315,
"text": "Output:"
},
{
"code": null,
"e": 28366,
"s": 28323,
"text": "transparency using opacity property values"
},
{
"code": null,
"e": 28465,
"s": 28366,
"text": "Example 2: Follow the steps to create a transparent web page like making a transparent login form."
},
{
"code": null,
"e": 28593,
"s": 28465,
"text": "Step 1:Adding HTML. Add an input for email, password, and login button. Wrap a “form” element around them to process the input."
},
{
"code": null,
"e": 28790,
"s": 28593,
"text": "Step 2: Add a required CSS to design a transparent login page using RGBA value for login form as explained above. CSS properties like linear-gradient and box-shadow to achieve the desired result. "
},
{
"code": null,
"e": 28795,
"s": 28790,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color: green; } body { background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59); } .form { width: 300px; height: 300px; display: grid; place-content: center; /* Add a transparency to the background using rgba value */ background: rgba(255, 255, 255, 0.1); /* Add a transparency to shadow */ box-shadow: 0 26px 42px rgba(0, 0, 0, 0.1); } input, button { box-sizing: border-box; width: 100%; margin: 20px auto; padding: 12px 20px; border: none; background: rgba(255, 255, 255, 0.1); box-shadow: 0 13px 21px rgba(0, 0, 0, 0.05); } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <form class=\"form\"> <input type=\"text\" placeholder=\"xyz@gmail.com\" /><br> <input type=\"password\" placeholder=\"Enter Password\" /> <br> <button type=\"submit\">Login</button> </form> </center></body> </html>",
"e": 30018,
"s": 28795,
"text": null
},
{
"code": null,
"e": 30026,
"s": 30018,
"text": "Output:"
},
{
"code": null,
"e": 30163,
"s": 30026,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 30176,
"s": 30163,
"text": "simmytarika5"
},
{
"code": null,
"e": 30191,
"s": 30176,
"text": "CSS-Properties"
},
{
"code": null,
"e": 30205,
"s": 30191,
"text": "CSS-Questions"
},
{
"code": null,
"e": 30220,
"s": 30205,
"text": "HTML-Questions"
},
{
"code": null,
"e": 30227,
"s": 30220,
"text": "Picked"
},
{
"code": null,
"e": 30231,
"s": 30227,
"text": "CSS"
},
{
"code": null,
"e": 30236,
"s": 30231,
"text": "HTML"
},
{
"code": null,
"e": 30253,
"s": 30236,
"text": "Web Technologies"
},
{
"code": null,
"e": 30258,
"s": 30253,
"text": "HTML"
},
{
"code": null,
"e": 30356,
"s": 30258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30393,
"s": 30356,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30432,
"s": 30393,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30461,
"s": 30432,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30503,
"s": 30461,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30538,
"s": 30503,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 30598,
"s": 30538,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30651,
"s": 30598,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30712,
"s": 30651,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30736,
"s": 30712,
"text": "REST API (Introduction)"
}
] |
numpy.real() function - Python - GeeksforGeeks
|
11 Jun, 2020
numpy.real() function return the real part of the complex argument.
Syntax : numpy.real(arr)
Parameters :arr : [array_like] Input array.
Return : [ndarray or scalar] The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.
Code #1 :
# Python program explaining# numpy.real() function # importing numpy as geek import numpy as geek arr = geek.array([1 + 3j, 5 + 7j, 9 + 11j]) gfg = arr.real print (gfg)
Output :
[1. 5. 9.]
Code #2 :
# Python program explaining# numpy.real() function # importing numpy as geek import numpy as geek arr = geek.array([2 + 3j, 5 + 6j, 8 + 9j]) gfg = arr.real print (gfg)
Output :
[2. 5. 8.]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 25605,
"s": 25537,
"text": "numpy.real() function return the real part of the complex argument."
},
{
"code": null,
"e": 25630,
"s": 25605,
"text": "Syntax : numpy.real(arr)"
},
{
"code": null,
"e": 25674,
"s": 25630,
"text": "Parameters :arr : [array_like] Input array."
},
{
"code": null,
"e": 25860,
"s": 25674,
"text": "Return : [ndarray or scalar] The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float."
},
{
"code": null,
"e": 25870,
"s": 25860,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.real() function # importing numpy as geek import numpy as geek arr = geek.array([1 + 3j, 5 + 7j, 9 + 11j]) gfg = arr.real print (gfg)",
"e": 26052,
"s": 25870,
"text": null
},
{
"code": null,
"e": 26061,
"s": 26052,
"text": "Output :"
},
{
"code": null,
"e": 26073,
"s": 26061,
"text": "[1. 5. 9.]\n"
},
{
"code": null,
"e": 26084,
"s": 26073,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.real() function # importing numpy as geek import numpy as geek arr = geek.array([2 + 3j, 5 + 6j, 8 + 9j]) gfg = arr.real print (gfg)",
"e": 26265,
"s": 26084,
"text": null
},
{
"code": null,
"e": 26274,
"s": 26265,
"text": "Output :"
},
{
"code": null,
"e": 26286,
"s": 26274,
"text": "[2. 5. 8.]\n"
},
{
"code": null,
"e": 26299,
"s": 26286,
"text": "Python-numpy"
},
{
"code": null,
"e": 26306,
"s": 26299,
"text": "Python"
},
{
"code": null,
"e": 26404,
"s": 26306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26436,
"s": 26404,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26478,
"s": 26436,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26520,
"s": 26478,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26576,
"s": 26520,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26603,
"s": 26576,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26642,
"s": 26603,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26673,
"s": 26642,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26702,
"s": 26673,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26724,
"s": 26702,
"text": "Defaultdict in Python"
}
] |
Product of all the pairs from the given array - GeeksforGeeks
|
14 May, 2021
Given an array arr[] of N integers, the task is to find the product of all the pairs possible from the given array such as:
(arr[i], arr[i]) is also considered as a valid pair.
(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.
Print the resultant answer modulus 10^9+7.
Examples:
Input: arr[] = {1, 2} Output: 16 Explanation: All valid pairs are (1, 1), (1, 2), (2, 1) and (2, 2). Hence, 1 * 1 * 1 * 2 * 2 * 1 * 2 * 2 = 16
Input: arr[] = {1, 2, 3} Output: 46656 Explanation: All valid pairs are (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2) and (3, 3). Hence the product is 1*1*1**2*1*3*2*1*2*2*2*3*3*1*3*2*3*3 = 46656
Naive Approach: To solve the problem mentioned above the naive method is to find all the possible pairs and calculate the product of the elements of each pair.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// product of all the pairs from// the given array #include <bits/stdc++.h>using namespace std;#define mod 1000000007 // Function to return the product of// the elements of all possible pairs// from the arrayint productPairs(int arr[], int n){ // To store the required product int product = 1; // Nested loop to calculate all // possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Multiply the product of // the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the final result return product % mod;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << productPairs(arr, n); return 0;}
// Java implementation to find the// product of all the pairs from// the given arrayimport java.util.*; class GFG{ static final int mod = 1000000007; // Function to return the product of// the elements of all possible pairs// from the arraystatic int productPairs(int arr[], int n){ // To store the required product int product = 1; // Nested loop to calculate all // possible pairs for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // Multiply the product // of the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the final result return product % mod;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.print(productPairs(arr, n));}} // This code is contributed by sapnasingh4991
# Python3 implementation to find the# product of all the pairs from# the given arraymod = 1000000007; # Function to return the product of# the elements of all possible pairs# from the arraydef productPairs(arr, n): # To store the required product product = 1; # Nested loop to calculate all # possible pairs for i in range(n): for j in range(n): # Multiply the product # of the elements of the # current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; # Return the final result return product % mod; # Driver codeif __name__ == '__main__': arr = [1, 2, 3]; n = len(arr); print(productPairs(arr, n)); # This code is contributed by 29AjayKumar
// C# implementation to find the// product of all the pairs from// the given arrayusing System;class GFG{ static readonly int mod = 1000000007; // Function to return the product of// the elements of all possible pairs// from the arraystatic int productPairs(int []arr, int n){ // To store the required product int product = 1; // Nested loop to calculate all // possible pairs for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // Multiply the product // of the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the readonly result return product % mod;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3 }; int n = arr.Length; Console.Write(productPairs(arr, n));}} // This code is contributed by sapnasingh4991
<script> //Javascript implementation to find the// product of all the pairs from// the given array mod = 1000000007 // Function to return the product of// the elements of all possible pairs// from the arrayfunction productPairs(arr, n){ // To store the required product let product = 1; // Nested loop to calculate all // possible pairs for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Multiply the product of // the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the final result return product % mod;} // Driver code let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(productPairs(arr, n)); // This code is contributed by Mayank Tyagi </script>
Time Complexity: O(N2)
Efficient approach: We can observe that each element appears exactly (2 * N) times as one of the elements of a pair (X, Y). Exactly N times as X and exactly N times as Y.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to Find the product// of all the pairs from the given array#include <bits/stdc++.h>using namespace std;#define mod 1000000007#define ll long long int // Function to calculate// (x^y)%1000000007int power(int x, unsigned int y){ int p = 1000000007; // Initialize result int res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arrayll productPairs(ll arr[], ll n){ // To store the required product ll product = 1; // Iterate for every element // of the array for (int i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * (int)power( arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver codeint main(){ ll arr[] = { 1, 2, 3 }; ll n = sizeof(arr) / sizeof(arr[0]); cout << productPairs(arr, n); return 0;}
// Java implementation to Find the product// of all the pairs from the given arrayimport java.util.*; class GFG{static final int mod = 1000000007; // Function to calculate// (x^y)%1000000007static int power(int x, int y){ int p = 1000000007; // Initialize result int res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arraystatic int productPairs(int arr[], int n){ // To store the required product int product = 1; // Iterate for every element // of the array for (int i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * (int)power(arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.print(productPairs(arr, n));}} // This code is contributed by amal kumar choubey
# Python3 implementation to Find the product# of all the pairs from the given arraymod = 1000000007 # Function to calculate# (x^y)%1000000007def power(x, y): p = 1000000007 # Initialize result res = 1 # Update x if it is more than # or equal to p x = x % p while (y > 0): # If y is odd, multiply x # with result if ((y & 1) != 0): res = (res * x) % p y = y >> 1 x = (x * x) % p # Return the final result return res # Function to return the product# of the elements of all possible# pairs from the arraydef productPairs(arr, n): # To store the required product product = 1 # Iterate for every element # of the array for i in range(n): # Each element appears (2 * n) times product = (product % mod * (int)(power(arr[i], (2 * n))) % mod) % mod return (product % mod) # Driver codearr = [ 1, 2, 3 ]n = len(arr) print(productPairs(arr, n)) # This code is contributed by divyeshrabadiya07
// C# implementation to Find the product// of all the pairs from the given arrayusing System;class GFG{const int mod = 1000000007; // Function to calculate// (x^y)%1000000007static int power(int x, int y){ int p = 1000000007; // Initialize result int res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arraystatic int productPairs(int []arr, int n){ // To store the required product int product = 1; // Iterate for every element // of the array for (int i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * (int)power(arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver codepublic static void Main(){ int []arr = { 1, 2, 3 }; int n = arr.Length; Console.Write(productPairs(arr, n));}} // This code is contributed by Code_Mech
<script> // Javascript implementation to Find the product// of all the pairs from the given array let mod = 1000000007; // Function to calculate// (x^y)%1000000007function power(x, y){ let p = 1000000007; // Initialize result let res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arrayfunction productPairs(arr, n){ // To store the required product let product = 1; // Iterate for every element // of the array for (let i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * power(arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver Code let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(productPairs(arr, n)); </script>
Time Complexity: O(N)
sapnasingh4991
Amal Kumar Choubey
Code_Mech
29AjayKumar
divyeshrabadiya07
mayanktyagi1709
susmitakundugoaldanga
Arrays
Mathematical
School Programming
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 26103,
"s": 26075,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 26228,
"s": 26103,
"text": "Given an array arr[] of N integers, the task is to find the product of all the pairs possible from the given array such as: "
},
{
"code": null,
"e": 26281,
"s": 26228,
"text": "(arr[i], arr[i]) is also considered as a valid pair."
},
{
"code": null,
"e": 26358,
"s": 26281,
"text": "(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs."
},
{
"code": null,
"e": 26401,
"s": 26358,
"text": "Print the resultant answer modulus 10^9+7."
},
{
"code": null,
"e": 26413,
"s": 26401,
"text": "Examples: "
},
{
"code": null,
"e": 26556,
"s": 26413,
"text": "Input: arr[] = {1, 2} Output: 16 Explanation: All valid pairs are (1, 1), (1, 2), (2, 1) and (2, 2). Hence, 1 * 1 * 1 * 2 * 2 * 1 * 2 * 2 = 16"
},
{
"code": null,
"e": 26770,
"s": 26556,
"text": "Input: arr[] = {1, 2, 3} Output: 46656 Explanation: All valid pairs are (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2) and (3, 3). Hence the product is 1*1*1**2*1*3*2*1*2*2*2*3*3*1*3*2*3*3 = 46656 "
},
{
"code": null,
"e": 26930,
"s": 26770,
"text": "Naive Approach: To solve the problem mentioned above the naive method is to find all the possible pairs and calculate the product of the elements of each pair."
},
{
"code": null,
"e": 26983,
"s": 26930,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26987,
"s": 26983,
"text": "C++"
},
{
"code": null,
"e": 26992,
"s": 26987,
"text": "Java"
},
{
"code": null,
"e": 27000,
"s": 26992,
"text": "Python3"
},
{
"code": null,
"e": 27003,
"s": 27000,
"text": "C#"
},
{
"code": null,
"e": 27014,
"s": 27003,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// product of all the pairs from// the given array #include <bits/stdc++.h>using namespace std;#define mod 1000000007 // Function to return the product of// the elements of all possible pairs// from the arrayint productPairs(int arr[], int n){ // To store the required product int product = 1; // Nested loop to calculate all // possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Multiply the product of // the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the final result return product % mod;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << productPairs(arr, n); return 0;}",
"e": 27931,
"s": 27014,
"text": null
},
{
"code": "// Java implementation to find the// product of all the pairs from// the given arrayimport java.util.*; class GFG{ static final int mod = 1000000007; // Function to return the product of// the elements of all possible pairs// from the arraystatic int productPairs(int arr[], int n){ // To store the required product int product = 1; // Nested loop to calculate all // possible pairs for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // Multiply the product // of the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the final result return product % mod;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.print(productPairs(arr, n));}} // This code is contributed by sapnasingh4991",
"e": 28891,
"s": 27931,
"text": null
},
{
"code": "# Python3 implementation to find the# product of all the pairs from# the given arraymod = 1000000007; # Function to return the product of# the elements of all possible pairs# from the arraydef productPairs(arr, n): # To store the required product product = 1; # Nested loop to calculate all # possible pairs for i in range(n): for j in range(n): # Multiply the product # of the elements of the # current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; # Return the final result return product % mod; # Driver codeif __name__ == '__main__': arr = [1, 2, 3]; n = len(arr); print(productPairs(arr, n)); # This code is contributed by 29AjayKumar",
"e": 29695,
"s": 28891,
"text": null
},
{
"code": "// C# implementation to find the// product of all the pairs from// the given arrayusing System;class GFG{ static readonly int mod = 1000000007; // Function to return the product of// the elements of all possible pairs// from the arraystatic int productPairs(int []arr, int n){ // To store the required product int product = 1; // Nested loop to calculate all // possible pairs for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // Multiply the product // of the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the readonly result return product % mod;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3 }; int n = arr.Length; Console.Write(productPairs(arr, n));}} // This code is contributed by sapnasingh4991",
"e": 30670,
"s": 29695,
"text": null
},
{
"code": "<script> //Javascript implementation to find the// product of all the pairs from// the given array mod = 1000000007 // Function to return the product of// the elements of all possible pairs// from the arrayfunction productPairs(arr, n){ // To store the required product let product = 1; // Nested loop to calculate all // possible pairs for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Multiply the product of // the elements of the // current pair product *= (arr[i] % mod * arr[j] % mod) % mod; product = product % mod; } } // Return the final result return product % mod;} // Driver code let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(productPairs(arr, n)); // This code is contributed by Mayank Tyagi </script>",
"e": 31560,
"s": 30670,
"text": null
},
{
"code": null,
"e": 31583,
"s": 31560,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 31754,
"s": 31583,
"text": "Efficient approach: We can observe that each element appears exactly (2 * N) times as one of the elements of a pair (X, Y). Exactly N times as X and exactly N times as Y."
},
{
"code": null,
"e": 31807,
"s": 31754,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31811,
"s": 31807,
"text": "C++"
},
{
"code": null,
"e": 31816,
"s": 31811,
"text": "Java"
},
{
"code": null,
"e": 31824,
"s": 31816,
"text": "Python3"
},
{
"code": null,
"e": 31827,
"s": 31824,
"text": "C#"
},
{
"code": null,
"e": 31838,
"s": 31827,
"text": "Javascript"
},
{
"code": "// C++ implementation to Find the product// of all the pairs from the given array#include <bits/stdc++.h>using namespace std;#define mod 1000000007#define ll long long int // Function to calculate// (x^y)%1000000007int power(int x, unsigned int y){ int p = 1000000007; // Initialize result int res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arrayll productPairs(ll arr[], ll n){ // To store the required product ll product = 1; // Iterate for every element // of the array for (int i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * (int)power( arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver codeint main(){ ll arr[] = { 1, 2, 3 }; ll n = sizeof(arr) / sizeof(arr[0]); cout << productPairs(arr, n); return 0;}",
"e": 33089,
"s": 31838,
"text": null
},
{
"code": "// Java implementation to Find the product// of all the pairs from the given arrayimport java.util.*; class GFG{static final int mod = 1000000007; // Function to calculate// (x^y)%1000000007static int power(int x, int y){ int p = 1000000007; // Initialize result int res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arraystatic int productPairs(int arr[], int n){ // To store the required product int product = 1; // Iterate for every element // of the array for (int i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * (int)power(arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.print(productPairs(arr, n));}} // This code is contributed by amal kumar choubey",
"e": 34360,
"s": 33089,
"text": null
},
{
"code": "# Python3 implementation to Find the product# of all the pairs from the given arraymod = 1000000007 # Function to calculate# (x^y)%1000000007def power(x, y): p = 1000000007 # Initialize result res = 1 # Update x if it is more than # or equal to p x = x % p while (y > 0): # If y is odd, multiply x # with result if ((y & 1) != 0): res = (res * x) % p y = y >> 1 x = (x * x) % p # Return the final result return res # Function to return the product# of the elements of all possible# pairs from the arraydef productPairs(arr, n): # To store the required product product = 1 # Iterate for every element # of the array for i in range(n): # Each element appears (2 * n) times product = (product % mod * (int)(power(arr[i], (2 * n))) % mod) % mod return (product % mod) # Driver codearr = [ 1, 2, 3 ]n = len(arr) print(productPairs(arr, n)) # This code is contributed by divyeshrabadiya07",
"e": 35407,
"s": 34360,
"text": null
},
{
"code": "// C# implementation to Find the product// of all the pairs from the given arrayusing System;class GFG{const int mod = 1000000007; // Function to calculate// (x^y)%1000000007static int power(int x, int y){ int p = 1000000007; // Initialize result int res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arraystatic int productPairs(int []arr, int n){ // To store the required product int product = 1; // Iterate for every element // of the array for (int i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * (int)power(arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver codepublic static void Main(){ int []arr = { 1, 2, 3 }; int n = arr.Length; Console.Write(productPairs(arr, n));}} // This code is contributed by Code_Mech",
"e": 36637,
"s": 35407,
"text": null
},
{
"code": "<script> // Javascript implementation to Find the product// of all the pairs from the given array let mod = 1000000007; // Function to calculate// (x^y)%1000000007function power(x, y){ let p = 1000000007; // Initialize result let res = 1; // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } // Return the final result return res;} // Function to return the product// of the elements of all possible// pairs from the arrayfunction productPairs(arr, n){ // To store the required product let product = 1; // Iterate for every element // of the array for (let i = 0; i < n; i++) { // Each element appears (2 * n) times product = (product % mod * power(arr[i], (2 * n)) % mod) % mod; } return product % mod;} // Driver Code let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(productPairs(arr, n)); </script>",
"e": 37794,
"s": 36637,
"text": null
},
{
"code": null,
"e": 37817,
"s": 37794,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 37832,
"s": 37817,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 37851,
"s": 37832,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 37861,
"s": 37851,
"text": "Code_Mech"
},
{
"code": null,
"e": 37873,
"s": 37861,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37891,
"s": 37873,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 37907,
"s": 37891,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 37929,
"s": 37907,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 37936,
"s": 37929,
"text": "Arrays"
},
{
"code": null,
"e": 37949,
"s": 37936,
"text": "Mathematical"
},
{
"code": null,
"e": 37968,
"s": 37949,
"text": "School Programming"
},
{
"code": null,
"e": 37975,
"s": 37968,
"text": "Arrays"
},
{
"code": null,
"e": 37988,
"s": 37975,
"text": "Mathematical"
},
{
"code": null,
"e": 38086,
"s": 37988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38154,
"s": 38086,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 38198,
"s": 38154,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 38246,
"s": 38198,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 38269,
"s": 38246,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 38301,
"s": 38269,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 38331,
"s": 38301,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38346,
"s": 38331,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38389,
"s": 38346,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 38408,
"s": 38389,
"text": "Coin Change | DP-7"
}
] |
PHP | Basic Syntax - GeeksforGeeks
|
25 Jun, 2021
The structure which defines PHP computer language is called PHP syntax.
The PHP script is executed on the server and the HTML result is sent to the browser. It can normally have HTML and PHP tags. PHP or Hypertext Preprocessor is a widely used open-source general-purpose scripting language and can be embedded with HTML. PHP files are saved with the “.php” extension. PHP scripts can be written anywhere in the document within PHP tags along with normal HTML.
Escaping To PHP:
Writing the PHP code inside <?php ....?> is called Escaping to PHP.
The mechanism of separating a normal HTML from PHP code is called the mechanism of Escaping To PHP. There are various ways in which this can be done. Few methods are already set by default but in order to use few others like Short-open or ASP-style tags, we need to change the configuration of the php.ini file. These tags are also used for embedding PHP within HTML. There are 4 such tags available for this purpose.
Canonical PHP Tags: The script starts with <?php and ends with ?>. These tags are also called ‘Canonical PHP tags’. Everything outside of a pair of opening and closing tags is ignored by the PHP parser. The open and closing tags are called delimiters. Every PHP command ends with a semi-colon (;). Let’s look at the hello world program in PHP.
PHP
<?php# Here echo command is used to printecho "Hello, world!";?>
Output:
Hello, world!
SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The script starts with <? and ends with ?>. This will only work by setting the short_open_tag setting in the php.ini file to ‘on’.
Example:
PHP
<?# Here echo command will only work if# setting is done as said beforeecho "Hello, world!";?>
Output:
Hello, world!
HTML Script Tags: These are implemented using script tags. This syntax is removed in PHP 7.0.0. So its no more used.
Example:
PHP
<script language="php">echo "hello world!";</script>
Output:
hello world!
ASP Style Tags: To use this we need to set the configuration of the php.ini file. These are used by Active Server Pages to describe code blocks. These tags start with <% and end with %>.
Example:
PHP
<%# Can only be written if setting is turned on# to allow %echo "hello world";%>
Output:
hello world
Constants:
Constants can be defined using the const keyword or define() function.
There is some difference between constants and variables.
Constants do not have $ in front of them like variables have.
Constants can be accessed from anywhere without regard to variable scoping rules.
Comments in PHP:
Comments help in reminding the developer about the code if it’s re-visited after a period of time.
A comment is something that is ignored and not read or executed by the PHP engine or the language as part of a program and is written to make the code more readable and understandable. These are used to help other users and developers to describe the code and what it is trying to do. It can also be used in documenting a set of codes or parts of a program. You must have noticed this in the above sample programs. PHP supports two types of comment:
Single Line Comment: As the name suggests these are single line or short relevant explanations that one can add to their code. To add this, we need to begin the line with (//) or (#).
Example:
PHP
<?php// This is a single line comment// These cannot be extended to more lines echo "hello world!!!"; # This is also a single line comment?>
Output:
hello world!!!
Multi-line or Multiple line Comment: These are used to accommodate multiple lines with a single tag and can be extended to many lines as required by the user. To add this, we need to begin and end the line with (/*...*/)
PHP
<?php/* This is a multi line comment In PHP variables are written by adding a $ sign at the beginning.*/ $geek = "hello world!";echo $geek;?>
Output:
hello world!
Case Sensitivity in PHP:
PHP is insensitive to whitespace. This includes all types of spaces that are invisible on the screen including tabs, spaces, and carriage returns. Even one space is equal to any number of spaces or carriage returns. This means that PHP will ignore all the spaces or tabs in a single row or carriage return in multiple rows. Unless a semi-colon is encountered, PHP treats multiple lines as a single command.
Example:
PHP
<?php// PHP code illustrate the whitespace insensitivity$var1 = 15;$var2 =30;$sum = $var1+$var2; // "\n" for new lineecho $sum, "\n"; $sum1 = $var1 + $var2;echo $sum1;?>
Output:
45
45
Both of them show the same results without any errors.
PHP is case-sensitive. All the keywords, functions, and class names in PHP (while, if, echo, else, etc) are NOT case-sensitive except variables. Only variables with different cases are treated differently. Let’s look at this example:
PHP
<?php// Here we can see that all echo// statements are executed in the same manner $variable = 25;echo $variable;ECHO $variable;EcHo $variable; // but this line will show RUNTIME ERROR as// "Undefined Variable"echo $VARIABLE?>
Output:
25
25
25
Blocks in PHP:
In PHP, multiple statements can be executed simultaneously (under a single condition or loop) by using curly-braces ({}). This forms a block of statements that gets executed simultaneously.
PHP
<?php$var = 50;if ($var>0){ echo ("Positive as \n"); echo ("greater than 0");}?>
Output:
Positive as
greater than 0
This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
geetanjali16
adnanirshad158
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 ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key 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 ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 42163,
"s": 42135,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 42235,
"s": 42163,
"text": "The structure which defines PHP computer language is called PHP syntax."
},
{
"code": null,
"e": 42626,
"s": 42235,
"text": "The PHP script is executed on the server and the HTML result is sent to the browser. It can normally have HTML and PHP tags. PHP or Hypertext Preprocessor is a widely used open-source general-purpose scripting language and can be embedded with HTML. PHP files are saved with the “.php” extension. PHP scripts can be written anywhere in the document within PHP tags along with normal HTML. "
},
{
"code": null,
"e": 42643,
"s": 42626,
"text": "Escaping To PHP:"
},
{
"code": null,
"e": 42711,
"s": 42643,
"text": "Writing the PHP code inside <?php ....?> is called Escaping to PHP."
},
{
"code": null,
"e": 43129,
"s": 42711,
"text": "The mechanism of separating a normal HTML from PHP code is called the mechanism of Escaping To PHP. There are various ways in which this can be done. Few methods are already set by default but in order to use few others like Short-open or ASP-style tags, we need to change the configuration of the php.ini file. These tags are also used for embedding PHP within HTML. There are 4 such tags available for this purpose."
},
{
"code": null,
"e": 43475,
"s": 43129,
"text": "Canonical PHP Tags: The script starts with <?php and ends with ?>. These tags are also called ‘Canonical PHP tags’. Everything outside of a pair of opening and closing tags is ignored by the PHP parser. The open and closing tags are called delimiters. Every PHP command ends with a semi-colon (;). Let’s look at the hello world program in PHP. "
},
{
"code": null,
"e": 43479,
"s": 43475,
"text": "PHP"
},
{
"code": "<?php# Here echo command is used to printecho \"Hello, world!\";?>",
"e": 43544,
"s": 43479,
"text": null
},
{
"code": null,
"e": 43553,
"s": 43544,
"text": "Output: "
},
{
"code": null,
"e": 43567,
"s": 43553,
"text": "Hello, world!"
},
{
"code": null,
"e": 43781,
"s": 43567,
"text": "SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The script starts with <? and ends with ?>. This will only work by setting the short_open_tag setting in the php.ini file to ‘on’. "
},
{
"code": null,
"e": 43792,
"s": 43781,
"text": "Example: "
},
{
"code": null,
"e": 43796,
"s": 43792,
"text": "PHP"
},
{
"code": "<?# Here echo command will only work if# setting is done as said beforeecho \"Hello, world!\";?>",
"e": 43891,
"s": 43796,
"text": null
},
{
"code": null,
"e": 43899,
"s": 43891,
"text": "Output:"
},
{
"code": null,
"e": 43913,
"s": 43899,
"text": "Hello, world!"
},
{
"code": null,
"e": 44033,
"s": 43913,
"text": "HTML Script Tags: These are implemented using script tags. This syntax is removed in PHP 7.0.0. So its no more used. "
},
{
"code": null,
"e": 44044,
"s": 44033,
"text": "Example: "
},
{
"code": null,
"e": 44048,
"s": 44044,
"text": "PHP"
},
{
"code": "<script language=\"php\">echo \"hello world!\";</script>",
"e": 44101,
"s": 44048,
"text": null
},
{
"code": null,
"e": 44110,
"s": 44101,
"text": " Output:"
},
{
"code": null,
"e": 44123,
"s": 44110,
"text": "hello world!"
},
{
"code": null,
"e": 44311,
"s": 44123,
"text": "ASP Style Tags: To use this we need to set the configuration of the php.ini file. These are used by Active Server Pages to describe code blocks. These tags start with <% and end with %>. "
},
{
"code": null,
"e": 44322,
"s": 44311,
"text": "Example: "
},
{
"code": null,
"e": 44326,
"s": 44322,
"text": "PHP"
},
{
"code": "<%# Can only be written if setting is turned on# to allow %echo \"hello world\";%>",
"e": 44407,
"s": 44326,
"text": null
},
{
"code": null,
"e": 44415,
"s": 44407,
"text": "Output:"
},
{
"code": null,
"e": 44427,
"s": 44415,
"text": "hello world"
},
{
"code": null,
"e": 44438,
"s": 44427,
"text": "Constants:"
},
{
"code": null,
"e": 44509,
"s": 44438,
"text": "Constants can be defined using the const keyword or define() function."
},
{
"code": null,
"e": 44567,
"s": 44509,
"text": "There is some difference between constants and variables."
},
{
"code": null,
"e": 44629,
"s": 44567,
"text": "Constants do not have $ in front of them like variables have."
},
{
"code": null,
"e": 44711,
"s": 44629,
"text": "Constants can be accessed from anywhere without regard to variable scoping rules."
},
{
"code": null,
"e": 44728,
"s": 44711,
"text": "Comments in PHP:"
},
{
"code": null,
"e": 44827,
"s": 44728,
"text": "Comments help in reminding the developer about the code if it’s re-visited after a period of time."
},
{
"code": null,
"e": 45279,
"s": 44827,
"text": "A comment is something that is ignored and not read or executed by the PHP engine or the language as part of a program and is written to make the code more readable and understandable. These are used to help other users and developers to describe the code and what it is trying to do. It can also be used in documenting a set of codes or parts of a program. You must have noticed this in the above sample programs. PHP supports two types of comment: "
},
{
"code": null,
"e": 45463,
"s": 45279,
"text": "Single Line Comment: As the name suggests these are single line or short relevant explanations that one can add to their code. To add this, we need to begin the line with (//) or (#)."
},
{
"code": null,
"e": 45474,
"s": 45463,
"text": "Example: "
},
{
"code": null,
"e": 45478,
"s": 45474,
"text": "PHP"
},
{
"code": "<?php// This is a single line comment// These cannot be extended to more lines echo \"hello world!!!\"; # This is also a single line comment?>",
"e": 45619,
"s": 45478,
"text": null
},
{
"code": null,
"e": 45629,
"s": 45619,
"text": "Output: "
},
{
"code": null,
"e": 45644,
"s": 45629,
"text": "hello world!!!"
},
{
"code": null,
"e": 45867,
"s": 45644,
"text": "Multi-line or Multiple line Comment: These are used to accommodate multiple lines with a single tag and can be extended to many lines as required by the user. To add this, we need to begin and end the line with (/*...*/) "
},
{
"code": null,
"e": 45871,
"s": 45867,
"text": "PHP"
},
{
"code": "<?php/* This is a multi line comment In PHP variables are written by adding a $ sign at the beginning.*/ $geek = \"hello world!\";echo $geek;?>",
"e": 46019,
"s": 45871,
"text": null
},
{
"code": null,
"e": 46028,
"s": 46019,
"text": "Output: "
},
{
"code": null,
"e": 46041,
"s": 46028,
"text": "hello world!"
},
{
"code": null,
"e": 46066,
"s": 46041,
"text": "Case Sensitivity in PHP:"
},
{
"code": null,
"e": 46473,
"s": 46066,
"text": "PHP is insensitive to whitespace. This includes all types of spaces that are invisible on the screen including tabs, spaces, and carriage returns. Even one space is equal to any number of spaces or carriage returns. This means that PHP will ignore all the spaces or tabs in a single row or carriage return in multiple rows. Unless a semi-colon is encountered, PHP treats multiple lines as a single command."
},
{
"code": null,
"e": 46484,
"s": 46473,
"text": "Example: "
},
{
"code": null,
"e": 46488,
"s": 46484,
"text": "PHP"
},
{
"code": "<?php// PHP code illustrate the whitespace insensitivity$var1 = 15;$var2 =30;$sum = $var1+$var2; // \"\\n\" for new lineecho $sum, \"\\n\"; $sum1 = $var1 + $var2;echo $sum1;?>",
"e": 46670,
"s": 46488,
"text": null
},
{
"code": null,
"e": 46678,
"s": 46670,
"text": "Output:"
},
{
"code": null,
"e": 46684,
"s": 46678,
"text": "45\n45"
},
{
"code": null,
"e": 46739,
"s": 46684,
"text": "Both of them show the same results without any errors."
},
{
"code": null,
"e": 46975,
"s": 46739,
"text": "PHP is case-sensitive. All the keywords, functions, and class names in PHP (while, if, echo, else, etc) are NOT case-sensitive except variables. Only variables with different cases are treated differently. Let’s look at this example: "
},
{
"code": null,
"e": 46979,
"s": 46975,
"text": "PHP"
},
{
"code": "<?php// Here we can see that all echo// statements are executed in the same manner $variable = 25;echo $variable;ECHO $variable;EcHo $variable; // but this line will show RUNTIME ERROR as// \"Undefined Variable\"echo $VARIABLE?>",
"e": 47207,
"s": 46979,
"text": null
},
{
"code": null,
"e": 47217,
"s": 47207,
"text": "Output: "
},
{
"code": null,
"e": 47226,
"s": 47217,
"text": "25\n25\n25"
},
{
"code": null,
"e": 47241,
"s": 47226,
"text": "Blocks in PHP:"
},
{
"code": null,
"e": 47433,
"s": 47241,
"text": "In PHP, multiple statements can be executed simultaneously (under a single condition or loop) by using curly-braces ({}). This forms a block of statements that gets executed simultaneously. "
},
{
"code": null,
"e": 47437,
"s": 47433,
"text": "PHP"
},
{
"code": "<?php$var = 50;if ($var>0){ echo (\"Positive as \\n\"); echo (\"greater than 0\");}?>",
"e": 47524,
"s": 47437,
"text": null
},
{
"code": null,
"e": 47534,
"s": 47524,
"text": "Output: "
},
{
"code": null,
"e": 47561,
"s": 47534,
"text": "Positive as\ngreater than 0"
},
{
"code": null,
"e": 47983,
"s": 47561,
"text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 47996,
"s": 47983,
"text": "geetanjali16"
},
{
"code": null,
"e": 48011,
"s": 47996,
"text": "adnanirshad158"
},
{
"code": null,
"e": 48022,
"s": 48011,
"text": "PHP-basics"
},
{
"code": null,
"e": 48026,
"s": 48022,
"text": "PHP"
},
{
"code": null,
"e": 48043,
"s": 48026,
"text": "Web Technologies"
},
{
"code": null,
"e": 48047,
"s": 48043,
"text": "PHP"
},
{
"code": null,
"e": 48145,
"s": 48047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48190,
"s": 48145,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 48240,
"s": 48190,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 48264,
"s": 48240,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 48304,
"s": 48264,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 48356,
"s": 48304,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 48396,
"s": 48356,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 48429,
"s": 48396,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 48474,
"s": 48429,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 48517,
"s": 48474,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Dynamic TextView in Kotlin - GeeksforGeeks
|
18 Feb, 2021
Android TextView is an user interface that is used to display some text to the user.
In this article we will be discussing how to programmatically create a TextView in Kotlin .
Let’s start by first creating a project in Android Studio. To do so, follow these instructions:
Click on File, then New and then New Project and give name whatever you like
Then, select Kotlin language Support and click next button.
Select minimum SDK, whatever you need.
Select Empty activity and then click finish.
Second step is to design our layout page. Here, we will use the RelativeLayout to get the TextView from the Kotlin file.
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root" tools:context=".MainActivity"> </RelativeLayout>
Open app/src/main/java/yourPackageName/MainActivity.kt. In this file, we declare a variable TextView to create the TextView widget like this:
val textView = TextView(this)
//setting height and width
textView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
then add the widget in layout using this:
// Add TextView to LinearLayout
layout?.addView(textView)
package com.geeksforgeeks.myfirstKotlinapp import android.graphics.Colorimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.TypedValueimport android.view.ViewGroupimport android.widget.RelativeLayoutimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val layout = findViewById<RelativeLayout>(R.id.root) // Create TextView programmatically. val textView = TextView(this) // setting height and width textView.layoutParams= RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) // setting text textView.setText("GEEKSFORGEEKS") textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40f) textView.setTextColor(Color.MAGENTA) // onClick the text a message will be displayed "HELLO GEEK" textView.setOnClickListener() { Toast.makeText(this@MainActivity, "HELLO GEEK", Toast.LENGTH_LONG).show() } // Add TextView to LinearLayout layout ?.addView(textView) }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="i.apps.textview"> <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>
Android-View
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Resource Raw Folder in Android Studio
Broadcast Receiver in Android With Example
Services in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Kotlin Array
Android UI Layouts
Services in Android with Example
Android RecyclerView in Kotlin
|
[
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 25322,
"s": 25237,
"text": "Android TextView is an user interface that is used to display some text to the user."
},
{
"code": null,
"e": 25414,
"s": 25322,
"text": "In this article we will be discussing how to programmatically create a TextView in Kotlin ."
},
{
"code": null,
"e": 25510,
"s": 25414,
"text": "Let’s start by first creating a project in Android Studio. To do so, follow these instructions:"
},
{
"code": null,
"e": 25587,
"s": 25510,
"text": "Click on File, then New and then New Project and give name whatever you like"
},
{
"code": null,
"e": 25647,
"s": 25587,
"text": "Then, select Kotlin language Support and click next button."
},
{
"code": null,
"e": 25686,
"s": 25647,
"text": "Select minimum SDK, whatever you need."
},
{
"code": null,
"e": 25731,
"s": 25686,
"text": "Select Empty activity and then click finish."
},
{
"code": null,
"e": 25852,
"s": 25731,
"text": "Second step is to design our layout page. Here, we will use the RelativeLayout to get the TextView from the Kotlin file."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/root\" tools:context=\".MainActivity\"> </RelativeLayout>",
"e": 26261,
"s": 25852,
"text": null
},
{
"code": null,
"e": 26403,
"s": 26261,
"text": "Open app/src/main/java/yourPackageName/MainActivity.kt. In this file, we declare a variable TextView to create the TextView widget like this:"
},
{
"code": null,
"e": 26599,
"s": 26403,
"text": " val textView = TextView(this)\n //setting height and width\n textView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)\n"
},
{
"code": null,
"e": 26641,
"s": 26599,
"text": "then add the widget in layout using this:"
},
{
"code": null,
"e": 26718,
"s": 26641,
"text": " \n // Add TextView to LinearLayout\n layout?.addView(textView)\n"
},
{
"code": "package com.geeksforgeeks.myfirstKotlinapp import android.graphics.Colorimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.TypedValueimport android.view.ViewGroupimport android.widget.RelativeLayoutimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val layout = findViewById<RelativeLayout>(R.id.root) // Create TextView programmatically. val textView = TextView(this) // setting height and width textView.layoutParams= RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) // setting text textView.setText(\"GEEKSFORGEEKS\") textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40f) textView.setTextColor(Color.MAGENTA) // onClick the text a message will be displayed \"HELLO GEEK\" textView.setOnClickListener() { Toast.makeText(this@MainActivity, \"HELLO GEEK\", Toast.LENGTH_LONG).show() } // Add TextView to LinearLayout layout ?.addView(textView) }}",
"e": 28020,
"s": 26718,
"text": null
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"i.apps.textview\"> <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": 28744,
"s": 28020,
"text": null
},
{
"code": null,
"e": 28757,
"s": 28744,
"text": "Android-View"
},
{
"code": null,
"e": 28772,
"s": 28757,
"text": "Kotlin Android"
},
{
"code": null,
"e": 28779,
"s": 28772,
"text": "Picked"
},
{
"code": null,
"e": 28787,
"s": 28779,
"text": "Android"
},
{
"code": null,
"e": 28794,
"s": 28787,
"text": "Kotlin"
},
{
"code": null,
"e": 28802,
"s": 28794,
"text": "Android"
},
{
"code": null,
"e": 28900,
"s": 28802,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28958,
"s": 28900,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 28996,
"s": 28958,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 29039,
"s": 28996,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29072,
"s": 29039,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 29103,
"s": 29072,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 29146,
"s": 29103,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29159,
"s": 29146,
"text": "Kotlin Array"
},
{
"code": null,
"e": 29178,
"s": 29159,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 29211,
"s": 29178,
"text": "Services in Android with Example"
}
] |
What is the use of next() function in Express.js ? - GeeksforGeeks
|
18 Dec, 2021
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js.
There are lots of middleware functions in Express.js like the Express.js app.use() function, and many more. The app.use() middleware is basically used to define the handler of the particular request made by the client.
Syntax:
app.use(path,(req,res,next))
Parameters: It accepts the two parameters as mentioned above and described below:
path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths.
callback: It is the callback function that contains the request object, response object, and next() function to call the next middleware function if the response of the current middleware is not terminated. In the second parameter, we can also pass the function name of the middleware.
Installing Module: Install the express module using the following command.
npm install express
Project structure: It will look like this.
Example 1: Server without next() function
Filename: index.js
Javascript
// Importing the express moduleconst express = require("express");const app = express() // Creating First Middlewareapp.use("/", (req, res, next) => { console.log("Hello"); // There is no next() function calls here}) // Creating second middlewareapp.get("/", (req, res, next) => { console.log("Get Request")}) // Execution the serverapp.listen(3000, () => { console.log("Server is Running")})
Run index.js file using below command:
node index.js
Output: Without the next() function the middleware doesn’t call the next middleware even they request a path of the same
Server is Running
Hello
Example 2: Server with next() function
Filename: index.js
Javascript
// Importing the express moduleconst express = require("express");const app = express() // Creating First Middlewareapp.use("/", (req, res, next) => { console.log("Hello"); // The next() function called next();}) // Creating second middlewareapp.get("/", (req, res, next) => { console.log("Get Request")}) // Execution the serverapp.listen(3000, () => { console.log("Server is Running")})
Run index.js file using the below command:
node index.js
Output:
Server is Running
Hello
Get Request
simmytarika5
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n18 Dec, 2021"
},
{
"code": null,
"e": 26559,
"s": 26267,
"text": "Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js."
},
{
"code": null,
"e": 26778,
"s": 26559,
"text": "There are lots of middleware functions in Express.js like the Express.js app.use() function, and many more. The app.use() middleware is basically used to define the handler of the particular request made by the client."
},
{
"code": null,
"e": 26786,
"s": 26778,
"text": "Syntax:"
},
{
"code": null,
"e": 26815,
"s": 26786,
"text": "app.use(path,(req,res,next))"
},
{
"code": null,
"e": 26897,
"s": 26815,
"text": "Parameters: It accepts the two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 27076,
"s": 26897,
"text": "path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths."
},
{
"code": null,
"e": 27362,
"s": 27076,
"text": "callback: It is the callback function that contains the request object, response object, and next() function to call the next middleware function if the response of the current middleware is not terminated. In the second parameter, we can also pass the function name of the middleware."
},
{
"code": null,
"e": 27437,
"s": 27362,
"text": "Installing Module: Install the express module using the following command."
},
{
"code": null,
"e": 27457,
"s": 27437,
"text": "npm install express"
},
{
"code": null,
"e": 27500,
"s": 27457,
"text": "Project structure: It will look like this."
},
{
"code": null,
"e": 27542,
"s": 27500,
"text": "Example 1: Server without next() function"
},
{
"code": null,
"e": 27561,
"s": 27542,
"text": "Filename: index.js"
},
{
"code": null,
"e": 27572,
"s": 27561,
"text": "Javascript"
},
{
"code": "// Importing the express moduleconst express = require(\"express\");const app = express() // Creating First Middlewareapp.use(\"/\", (req, res, next) => { console.log(\"Hello\"); // There is no next() function calls here}) // Creating second middlewareapp.get(\"/\", (req, res, next) => { console.log(\"Get Request\")}) // Execution the serverapp.listen(3000, () => { console.log(\"Server is Running\")})",
"e": 27977,
"s": 27572,
"text": null
},
{
"code": null,
"e": 28016,
"s": 27977,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 28030,
"s": 28016,
"text": "node index.js"
},
{
"code": null,
"e": 28151,
"s": 28030,
"text": "Output: Without the next() function the middleware doesn’t call the next middleware even they request a path of the same"
},
{
"code": null,
"e": 28175,
"s": 28151,
"text": "Server is Running\nHello"
},
{
"code": null,
"e": 28214,
"s": 28175,
"text": "Example 2: Server with next() function"
},
{
"code": null,
"e": 28233,
"s": 28214,
"text": "Filename: index.js"
},
{
"code": null,
"e": 28244,
"s": 28233,
"text": "Javascript"
},
{
"code": "// Importing the express moduleconst express = require(\"express\");const app = express() // Creating First Middlewareapp.use(\"/\", (req, res, next) => { console.log(\"Hello\"); // The next() function called next();}) // Creating second middlewareapp.get(\"/\", (req, res, next) => { console.log(\"Get Request\")}) // Execution the serverapp.listen(3000, () => { console.log(\"Server is Running\")})",
"e": 28648,
"s": 28244,
"text": null
},
{
"code": null,
"e": 28691,
"s": 28648,
"text": "Run index.js file using the below command:"
},
{
"code": null,
"e": 28705,
"s": 28691,
"text": "node index.js"
},
{
"code": null,
"e": 28713,
"s": 28705,
"text": "Output:"
},
{
"code": null,
"e": 28749,
"s": 28713,
"text": "Server is Running\nHello\nGet Request"
},
{
"code": null,
"e": 28764,
"s": 28751,
"text": "simmytarika5"
},
{
"code": null,
"e": 28775,
"s": 28764,
"text": "Express.js"
},
{
"code": null,
"e": 28792,
"s": 28775,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 28799,
"s": 28792,
"text": "Picked"
},
{
"code": null,
"e": 28807,
"s": 28799,
"text": "Node.js"
},
{
"code": null,
"e": 28824,
"s": 28807,
"text": "Web Technologies"
},
{
"code": null,
"e": 28922,
"s": 28824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28992,
"s": 28922,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 29031,
"s": 28992,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 29053,
"s": 29031,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 29078,
"s": 29053,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 29105,
"s": 29078,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29145,
"s": 29105,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29190,
"s": 29145,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29233,
"s": 29190,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29283,
"s": 29233,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Perl | Creating Excel Files - GeeksforGeeks
|
07 May, 2019
Excel files are the most commonly used office application to communicate between computers. It is used to create rows and columns of text, numbers, and formulas for calculations. It is a good way to send reports. This demonstration works on Linux, Windows and other platforms as well. In excel, rows are numbered from 1 to n... and columns are marked by letters from A, B, C and so on.. hence, A1 refers to the top left corner. For creating excel files with Perl you can use padre IDE, we will also use Excel::Writer::XLSX module.Perl uses write() function to add content to the excel file.
Syntax: write(cell_address, content)
Parameters:cell_address: Address of the cell where content is to be added.content: which is to be added to the worksheet.
Excel Files can be created using Perl command line but first we need to load Excel::Writer::XLSX module.
#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); $Excelsheet->write( "A1", "Hello!" );$Excelsheet->write( "A2", "GeeksForGeeks" );$Excelsheet->write( "B1", "Next_Column" ); $Excelbook->close;
Output:
Here is how the Program works:Step 1: Load the module Excel::Writer::XLSX.Step 2: Create an object $Excelbook which represents the whole Excel File.Step 3: Call write() method to add data to the worksheet.Step 4: Now, save the file with .pl extension.Step 5: Run your .pl file on command line and Excelsheet will be created.
Excel provides the use of various Mathematical Formulae for the ease of calculations on the excelsheets like balance sheet, business records, etc.Here is the description of two basic formulas of Excel:
Addition:Excel provides a method ‘SUM’ for the addition of values on specific cells.Syntax: =SUM(Start, End)Parameter:Start: Address of the starting cellEnd: Address of the Ending cellReturns: the summation of values between the Starting and Ending cell.#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values at A1 and A2$Excelsheet->write( "A1", 55 );$Excelsheet->write( "A2", 47 ); # Adding without use of SUM method$Excelsheet->write( "A3", "= A1 + A2" ); # Addition of a Range of cells$Excelsheet->write( "A4", " =SUM(A1:A3)" );Output:
Syntax: =SUM(Start, End)
Parameter:Start: Address of the starting cellEnd: Address of the Ending cell
Returns: the summation of values between the Starting and Ending cell.
#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values at A1 and A2$Excelsheet->write( "A1", 55 );$Excelsheet->write( "A2", 47 ); # Adding without use of SUM method$Excelsheet->write( "A3", "= A1 + A2" ); # Addition of a Range of cells$Excelsheet->write( "A4", " =SUM(A1:A3)" );
Output:
Count:This function in Excel is used to count all the cells in the given range which contain only numeric value.Syntax: =COUNT(Start, End)Returns: count of all cells containing numeric value#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values$Excelsheet->write( "A1", 5 );$Excelsheet->write( "A2", 40 );$Excelsheet->write( "A3", "Hello" );$Excelsheet->write( "A4", 10 ); # Addition of a Range of cells$Excelsheet->write( "A5", "Count =");$Excelsheet->write( "B5", "=COUNT(A1:A4)" );Output:
Syntax: =COUNT(Start, End)Returns: count of all cells containing numeric value
#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values$Excelsheet->write( "A1", 5 );$Excelsheet->write( "A2", 40 );$Excelsheet->write( "A3", "Hello" );$Excelsheet->write( "A4", 10 ); # Addition of a Range of cells$Excelsheet->write( "A5", "Count =");$Excelsheet->write( "B5", "=COUNT(A1:A4)" );
Output:
Colors can be used in ExcelSheets to mark specific values separately. These colors are specified with the use of add_format() method.
Syntax: add_format(color=> ‘color_name’)
#!/usr/bin/perluse Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Setting value of colormy $color1 = $Excelbook->add_format(color=> 'blue',);my $color2 = $Excelbook->add_format(color=> 'red',);my $color3 = $Excelbook->add_format(color=> 'green',); $Excelsheet->write( "A2", "Geeks", $color1 );$Excelsheet->write( "B2", "For", $color2 );$Excelsheet->write( "C2", "Geeks", $color3 );$Excelbook->close;
Output:
Values can be added at specific coordinates by providing address of cells at which value is to be added.
Syntax: write(R,C, “value”)Parameters:R and C are the coordinates of the Row and Column respectively.
#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); $Excelsheet->write( 0, 0, "Hello!" );$Excelsheet->write( 1, 0, "GeeksForGeeks" );$Excelsheet->write( 3, 2, "Welcome!!!" ); $Excelbook->close;
Output:
Perl-files
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | grep() Function
Perl | Regular Expressions
Perl | Polymorphism in OOPs
Perl Tutorial - Learn Perl With Examples
Perl | length() Function
Perl | Basic Syntax of a Perl Program
Perl | substitution Operator
Perl | Boolean Values
Perl | Regex Cheat Sheet
Perl | sleep() Function
|
[
{
"code": null,
"e": 25227,
"s": 25199,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 25818,
"s": 25227,
"text": "Excel files are the most commonly used office application to communicate between computers. It is used to create rows and columns of text, numbers, and formulas for calculations. It is a good way to send reports. This demonstration works on Linux, Windows and other platforms as well. In excel, rows are numbered from 1 to n... and columns are marked by letters from A, B, C and so on.. hence, A1 refers to the top left corner. For creating excel files with Perl you can use padre IDE, we will also use Excel::Writer::XLSX module.Perl uses write() function to add content to the excel file."
},
{
"code": null,
"e": 25855,
"s": 25818,
"text": "Syntax: write(cell_address, content)"
},
{
"code": null,
"e": 25977,
"s": 25855,
"text": "Parameters:cell_address: Address of the cell where content is to be added.content: which is to be added to the worksheet."
},
{
"code": null,
"e": 26083,
"s": 25977,
"text": " Excel Files can be created using Perl command line but first we need to load Excel::Writer::XLSX module."
},
{
"code": "#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); $Excelsheet->write( \"A1\", \"Hello!\" );$Excelsheet->write( \"A2\", \"GeeksForGeeks\" );$Excelsheet->write( \"B1\", \"Next_Column\" ); $Excelbook->close;",
"e": 26378,
"s": 26083,
"text": null
},
{
"code": null,
"e": 26386,
"s": 26378,
"text": "Output:"
},
{
"code": null,
"e": 26712,
"s": 26386,
"text": "Here is how the Program works:Step 1: Load the module Excel::Writer::XLSX.Step 2: Create an object $Excelbook which represents the whole Excel File.Step 3: Call write() method to add data to the worksheet.Step 4: Now, save the file with .pl extension.Step 5: Run your .pl file on command line and Excelsheet will be created. "
},
{
"code": null,
"e": 26915,
"s": 26712,
"text": " Excel provides the use of various Mathematical Formulae for the ease of calculations on the excelsheets like balance sheet, business records, etc.Here is the description of two basic formulas of Excel:"
},
{
"code": null,
"e": 27570,
"s": 26915,
"text": "Addition:Excel provides a method ‘SUM’ for the addition of values on specific cells.Syntax: =SUM(Start, End)Parameter:Start: Address of the starting cellEnd: Address of the Ending cellReturns: the summation of values between the Starting and Ending cell.#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values at A1 and A2$Excelsheet->write( \"A1\", 55 );$Excelsheet->write( \"A2\", 47 ); # Adding without use of SUM method$Excelsheet->write( \"A3\", \"= A1 + A2\" ); # Addition of a Range of cells$Excelsheet->write( \"A4\", \" =SUM(A1:A3)\" );Output:"
},
{
"code": null,
"e": 27595,
"s": 27570,
"text": "Syntax: =SUM(Start, End)"
},
{
"code": null,
"e": 27672,
"s": 27595,
"text": "Parameter:Start: Address of the starting cellEnd: Address of the Ending cell"
},
{
"code": null,
"e": 27743,
"s": 27672,
"text": "Returns: the summation of values between the Starting and Ending cell."
},
{
"code": "#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values at A1 and A2$Excelsheet->write( \"A1\", 55 );$Excelsheet->write( \"A2\", 47 ); # Adding without use of SUM method$Excelsheet->write( \"A3\", \"= A1 + A2\" ); # Addition of a Range of cells$Excelsheet->write( \"A4\", \" =SUM(A1:A3)\" );",
"e": 28137,
"s": 27743,
"text": null
},
{
"code": null,
"e": 28145,
"s": 28137,
"text": "Output:"
},
{
"code": null,
"e": 28751,
"s": 28145,
"text": "Count:This function in Excel is used to count all the cells in the given range which contain only numeric value.Syntax: =COUNT(Start, End)Returns: count of all cells containing numeric value#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values$Excelsheet->write( \"A1\", 5 );$Excelsheet->write( \"A2\", 40 );$Excelsheet->write( \"A3\", \"Hello\" );$Excelsheet->write( \"A4\", 10 ); # Addition of a Range of cells$Excelsheet->write( \"A5\", \"Count =\");$Excelsheet->write( \"B5\", \"=COUNT(A1:A4)\" );Output:"
},
{
"code": null,
"e": 28830,
"s": 28751,
"text": "Syntax: =COUNT(Start, End)Returns: count of all cells containing numeric value"
},
{
"code": "#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Writing values$Excelsheet->write( \"A1\", 5 );$Excelsheet->write( \"A2\", 40 );$Excelsheet->write( \"A3\", \"Hello\" );$Excelsheet->write( \"A4\", 10 ); # Addition of a Range of cells$Excelsheet->write( \"A5\", \"Count =\");$Excelsheet->write( \"B5\", \"=COUNT(A1:A4)\" );",
"e": 29239,
"s": 28830,
"text": null
},
{
"code": null,
"e": 29247,
"s": 29239,
"text": "Output:"
},
{
"code": null,
"e": 29382,
"s": 29247,
"text": " Colors can be used in ExcelSheets to mark specific values separately. These colors are specified with the use of add_format() method."
},
{
"code": null,
"e": 29423,
"s": 29382,
"text": "Syntax: add_format(color=> ‘color_name’)"
},
{
"code": "#!/usr/bin/perluse Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); # Setting value of colormy $color1 = $Excelbook->add_format(color=> 'blue',);my $color2 = $Excelbook->add_format(color=> 'red',);my $color3 = $Excelbook->add_format(color=> 'green',); $Excelsheet->write( \"A2\", \"Geeks\", $color1 );$Excelsheet->write( \"B2\", \"For\", $color2 );$Excelsheet->write( \"C2\", \"Geeks\", $color3 );$Excelbook->close;",
"e": 29910,
"s": 29423,
"text": null
},
{
"code": null,
"e": 29918,
"s": 29910,
"text": "Output:"
},
{
"code": null,
"e": 30024,
"s": 29918,
"text": " Values can be added at specific coordinates by providing address of cells at which value is to be added."
},
{
"code": null,
"e": 30126,
"s": 30024,
"text": "Syntax: write(R,C, “value”)Parameters:R and C are the coordinates of the Row and Column respectively."
},
{
"code": "#!/usr/bin/perl use Excel::Writer::XLSX; my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );my $Excelsheet = $Excelbook->add_worksheet(); $Excelsheet->write( 0, 0, \"Hello!\" );$Excelsheet->write( 1, 0, \"GeeksForGeeks\" );$Excelsheet->write( 3, 2, \"Welcome!!!\" ); $Excelbook->close;",
"e": 30420,
"s": 30126,
"text": null
},
{
"code": null,
"e": 30428,
"s": 30420,
"text": "Output:"
},
{
"code": null,
"e": 30439,
"s": 30428,
"text": "Perl-files"
},
{
"code": null,
"e": 30446,
"s": 30439,
"text": "Picked"
},
{
"code": null,
"e": 30451,
"s": 30446,
"text": "Perl"
},
{
"code": null,
"e": 30456,
"s": 30451,
"text": "Perl"
},
{
"code": null,
"e": 30554,
"s": 30456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30577,
"s": 30554,
"text": "Perl | grep() Function"
},
{
"code": null,
"e": 30604,
"s": 30577,
"text": "Perl | Regular Expressions"
},
{
"code": null,
"e": 30632,
"s": 30604,
"text": "Perl | Polymorphism in OOPs"
},
{
"code": null,
"e": 30673,
"s": 30632,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 30698,
"s": 30673,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 30736,
"s": 30698,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 30765,
"s": 30736,
"text": "Perl | substitution Operator"
},
{
"code": null,
"e": 30787,
"s": 30765,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 30812,
"s": 30787,
"text": "Perl | Regex Cheat Sheet"
}
] |
Python - Convert Delimiter separated list to Number - GeeksforGeeks
|
05 Jul, 2021
Given a String with delimiter separated numbers, concatenate to form integer after removing delimiter.
Input : test_str = “1@6@7@8”, delim = ‘@’ Output : 1678 Explanation : Joined elements after removing delim “@”Input : test_str = “1!6!7!8”, delim = ‘!’ Output : 1678 Explanation : Joined elements after removing delim “!”
Method #1 : Using loop + split() + int()
This is one of the ways in which this task can be performed. In this, we split the string on delimiter and then run a loop to concat, at end result is converted to int().
Python3
# Python3 code to demonstrate working of# Convert Delimiter separated list to Number# Using loop + split() + join() # initializing stringtest_str = "1@6@7@8@5@8@9" # printing original stringprint("The original string is : " + str(test_str)) # initializing Delimiterdelim = "@" # spliting to get list of string numberstemp = test_str.split(delim)res = ''for ele in temp: res = res + ele # converting result into integerres = int(res) # printing resultprint("Constructed integer : " + str(res))
The original string is : 1@6@7@8@5@8@9
Constructed integer : 1678589
Method #2 : Using join() + split() + int()
This is one another way in which this task can be performed. In this, we perform final concatenation using join() and int() to get final result.
Python3
# Python3 code to demonstrate working of# Convert Delimiter separated list to Number# Using join() + split() + int() # initializing stringtest_str = "1@6@7@8@5@8@9" # printing original stringprint("The original string is : " + str(test_str)) # initializing Delimiterdelim = "@" # join used over splitted result# final result casted using int()res = int("".join(test_str.split(delim))) # printing resultprint("Constructed integer : " + str(res))
The original string is : 1@6@7@8@5@8@9
Constructed integer : 1678589
gabaa406
Python string-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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
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": "\n05 Jul, 2021"
},
{
"code": null,
"e": 25640,
"s": 25537,
"text": "Given a String with delimiter separated numbers, concatenate to form integer after removing delimiter."
},
{
"code": null,
"e": 25863,
"s": 25640,
"text": "Input : test_str = “1@6@7@8”, delim = ‘@’ Output : 1678 Explanation : Joined elements after removing delim “@”Input : test_str = “1!6!7!8”, delim = ‘!’ Output : 1678 Explanation : Joined elements after removing delim “!” "
},
{
"code": null,
"e": 25904,
"s": 25863,
"text": "Method #1 : Using loop + split() + int()"
},
{
"code": null,
"e": 26075,
"s": 25904,
"text": "This is one of the ways in which this task can be performed. In this, we split the string on delimiter and then run a loop to concat, at end result is converted to int()."
},
{
"code": null,
"e": 26083,
"s": 26075,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert Delimiter separated list to Number# Using loop + split() + join() # initializing stringtest_str = \"1@6@7@8@5@8@9\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing Delimiterdelim = \"@\" # spliting to get list of string numberstemp = test_str.split(delim)res = ''for ele in temp: res = res + ele # converting result into integerres = int(res) # printing resultprint(\"Constructed integer : \" + str(res))",
"e": 26579,
"s": 26083,
"text": null
},
{
"code": null,
"e": 26648,
"s": 26579,
"text": "The original string is : 1@6@7@8@5@8@9\nConstructed integer : 1678589"
},
{
"code": null,
"e": 26691,
"s": 26648,
"text": "Method #2 : Using join() + split() + int()"
},
{
"code": null,
"e": 26836,
"s": 26691,
"text": "This is one another way in which this task can be performed. In this, we perform final concatenation using join() and int() to get final result."
},
{
"code": null,
"e": 26844,
"s": 26836,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert Delimiter separated list to Number# Using join() + split() + int() # initializing stringtest_str = \"1@6@7@8@5@8@9\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing Delimiterdelim = \"@\" # join used over splitted result# final result casted using int()res = int(\"\".join(test_str.split(delim))) # printing resultprint(\"Constructed integer : \" + str(res))",
"e": 27289,
"s": 26844,
"text": null
},
{
"code": null,
"e": 27358,
"s": 27289,
"text": "The original string is : 1@6@7@8@5@8@9\nConstructed integer : 1678589"
},
{
"code": null,
"e": 27367,
"s": 27358,
"text": "gabaa406"
},
{
"code": null,
"e": 27390,
"s": 27367,
"text": "Python string-programs"
},
{
"code": null,
"e": 27397,
"s": 27390,
"text": "Python"
},
{
"code": null,
"e": 27413,
"s": 27397,
"text": "Python Programs"
},
{
"code": null,
"e": 27511,
"s": 27413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27543,
"s": 27511,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27585,
"s": 27543,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27627,
"s": 27585,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27654,
"s": 27627,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27710,
"s": 27654,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27732,
"s": 27710,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27771,
"s": 27732,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27817,
"s": 27771,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27855,
"s": 27817,
"text": "Python | Convert a list to dictionary"
}
] |
SQL | SELECT TOP Clause - GeeksforGeeks
|
09 Jan, 2019
SELECT TOP clause is used to fetch limited number of rows from a database. This clause is very useful while dealing with large databases.
Basic Syntax:SELECT TOP value column1,column2 FROM table_name;
value: number of rows to return from top
column1 , column2: fields in the table
table_name: name of table
SELECT TOP value column1,column2 FROM table_name;
value: number of rows to return from top
column1 , column2: fields in the table
table_name: name of table
Syntax using PercentSELECT TOP value PERCENT column1,column2 FROM table_name;
value: percentage of number of rows to return from top
column1 , column2: fields in the table
table_name: name of table
SELECT TOP value PERCENT column1,column2 FROM table_name;
value: percentage of number of rows to return from top
column1 , column2: fields in the table
table_name: name of table
Queries
To fetch first two data set from Student table.SELECT TOP 2 * FROM Student;
Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18
To fetch first two data set from Student table.SELECT TOP 2 * FROM Student;
Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18
To fetch first two data set from Student table.SELECT TOP 2 * FROM Student;
Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18
To fetch first two data set from Student table.SELECT TOP 2 * FROM Student;
Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18
SELECT TOP 2 * FROM Student;
Output:
To fetch 50 percent of the total records from Student table.SELECT TOP 50 PERCENT * FROM Student;
Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX20
To fetch 50 percent of the total records from Student table.SELECT TOP 50 PERCENT * FROM Student;
Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX20
To fetch 50 percent of the total records from Student table.SELECT TOP 50 PERCENT * FROM Student;
Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX20
SELECT TOP 50 PERCENT * FROM Student;
Output:
NOTE: To get the same functionality on MySQL and Oracle databases there is a bit of difference in the basic syntax;
Equivalent Syntaxes are as follows:For MySQL databases:SELECT column1,column2 FROM table_name LIMIT value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
For Oracle databases:SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
Equivalent Syntaxes are as follows:For MySQL databases:SELECT column1,column2 FROM table_name LIMIT value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
For Oracle databases:SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
For MySQL databases:SELECT column1,column2 FROM table_name LIMIT value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
SELECT column1,column2 FROM table_name LIMIT value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
For Oracle databases:SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Class and Object
Difference between Min Heap and Max Heap
SQL | WITH clause
ACID Properties in DBMS
SQL query to find second highest salary?
Normal Forms in DBMS
Introduction of B-Tree
|
[
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n09 Jan, 2019"
},
{
"code": null,
"e": 25803,
"s": 25665,
"text": "SELECT TOP clause is used to fetch limited number of rows from a database. This clause is very useful while dealing with large databases."
},
{
"code": null,
"e": 25973,
"s": 25803,
"text": "Basic Syntax:SELECT TOP value column1,column2 FROM table_name;\nvalue: number of rows to return from top\ncolumn1 , column2: fields in the table\ntable_name: name of table\n"
},
{
"code": null,
"e": 26130,
"s": 25973,
"text": "SELECT TOP value column1,column2 FROM table_name;\nvalue: number of rows to return from top\ncolumn1 , column2: fields in the table\ntable_name: name of table\n"
},
{
"code": null,
"e": 26329,
"s": 26130,
"text": "Syntax using PercentSELECT TOP value PERCENT column1,column2 FROM table_name;\nvalue: percentage of number of rows to return from top\ncolumn1 , column2: fields in the table\ntable_name: name of table\n"
},
{
"code": null,
"e": 26508,
"s": 26329,
"text": "SELECT TOP value PERCENT column1,column2 FROM table_name;\nvalue: percentage of number of rows to return from top\ncolumn1 , column2: fields in the table\ntable_name: name of table\n"
},
{
"code": null,
"e": 26516,
"s": 26508,
"text": "Queries"
},
{
"code": null,
"e": 26674,
"s": 26516,
"text": "To fetch first two data set from Student table.SELECT TOP 2 * FROM Student; \nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18"
},
{
"code": null,
"e": 26832,
"s": 26674,
"text": "To fetch first two data set from Student table.SELECT TOP 2 * FROM Student; \nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18"
},
{
"code": null,
"e": 26990,
"s": 26832,
"text": "To fetch first two data set from Student table.SELECT TOP 2 * FROM Student; \nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18"
},
{
"code": null,
"e": 27148,
"s": 26990,
"text": "To fetch first two data set from Student table.SELECT TOP 2 * FROM Student; \nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18"
},
{
"code": null,
"e": 27179,
"s": 27148,
"text": "SELECT TOP 2 * FROM Student; \n"
},
{
"code": null,
"e": 27187,
"s": 27179,
"text": "Output:"
},
{
"code": null,
"e": 27393,
"s": 27189,
"text": "To fetch 50 percent of the total records from Student table.SELECT TOP 50 PERCENT * FROM Student; \nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX20"
},
{
"code": null,
"e": 27597,
"s": 27393,
"text": "To fetch 50 percent of the total records from Student table.SELECT TOP 50 PERCENT * FROM Student; \nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX20"
},
{
"code": null,
"e": 27801,
"s": 27597,
"text": "To fetch 50 percent of the total records from Student table.SELECT TOP 50 PERCENT * FROM Student; \nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX20"
},
{
"code": null,
"e": 27841,
"s": 27801,
"text": "SELECT TOP 50 PERCENT * FROM Student; \n"
},
{
"code": null,
"e": 27849,
"s": 27841,
"text": "Output:"
},
{
"code": null,
"e": 27965,
"s": 27849,
"text": "NOTE: To get the same functionality on MySQL and Oracle databases there is a bit of difference in the basic syntax;"
},
{
"code": null,
"e": 28370,
"s": 27965,
"text": "Equivalent Syntaxes are as follows:For MySQL databases:SELECT column1,column2 FROM table_name LIMIT value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\nFor Oracle databases:SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\n"
},
{
"code": null,
"e": 28775,
"s": 28370,
"text": "Equivalent Syntaxes are as follows:For MySQL databases:SELECT column1,column2 FROM table_name LIMIT value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\nFor Oracle databases:SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\n"
},
{
"code": null,
"e": 28955,
"s": 28775,
"text": "For MySQL databases:SELECT column1,column2 FROM table_name LIMIT value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\n"
},
{
"code": null,
"e": 29115,
"s": 28955,
"text": "SELECT column1,column2 FROM table_name LIMIT value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\n"
},
{
"code": null,
"e": 29306,
"s": 29115,
"text": "For Oracle databases:SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\n"
},
{
"code": null,
"e": 29476,
"s": 29306,
"text": "SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;\ncolumn1 , column2: fields int the table\ntable_name: name of table\nvalue: number of rows to return from top\n"
},
{
"code": null,
"e": 29778,
"s": 29476,
"text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29903,
"s": 29778,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29925,
"s": 29903,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 29934,
"s": 29925,
"text": "Articles"
},
{
"code": null,
"e": 29939,
"s": 29934,
"text": "DBMS"
},
{
"code": null,
"e": 29943,
"s": 29939,
"text": "SQL"
},
{
"code": null,
"e": 29948,
"s": 29943,
"text": "DBMS"
},
{
"code": null,
"e": 29952,
"s": 29948,
"text": "SQL"
},
{
"code": null,
"e": 30050,
"s": 29952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30087,
"s": 30050,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30113,
"s": 30087,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 30160,
"s": 30113,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 30196,
"s": 30160,
"text": "Difference between Class and Object"
},
{
"code": null,
"e": 30237,
"s": 30196,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 30255,
"s": 30237,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 30279,
"s": 30255,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 30320,
"s": 30279,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 30341,
"s": 30320,
"text": "Normal Forms in DBMS"
}
] |
PostgreSQL - Autovacuum - GeeksforGeeks
|
29 Jun, 2021
Sometime in the 2000s the developers of PostgreSQL found a major loophole in the design of their relational database management system with respect to storage space and transaction speed. It turned out that the UPDATE query was becoming an expensive routine. UPDATE was duplicating the old row and rewriting new data in, which meant that the size of the database or the tables were not bound to any limit! Additionally, deleting a row only MARKED the row deleted while the actual data remained untouched – data forensics supported later.
This may sound familiar since it is what present-day file systems and data recovery software rely on i.e., data, when deleted, remains intact on the magnetic disk in its raw form, but is hidden on the interface. However, keeping old data was important for older transactions as well. So technically, it wasn’t right to compromise on transactional integrity. This being sufficient stimulus, the Postgres team soon introduced the ‘vacuum’ feature which literally vacuumed the deleted rows. However, this was a manual process and due to the several parameters involved in the function, it wasn’t desirable. Hence, autovacuum was developed.
Autovacuum is a daemon or background utility process offered by PostgreSQL to users to issue a regular clean-up of redundant data in the database and server. It does not require the user to manually issue the vacuuming and instead, is defined in the postgresql.conf file. In order to access this file, simply direct yourself to the following directory on your terminal and then open the file in a suitable editor.
>> cd C:\Program Files\PostgreSQL\13\data
>> "postgresql.conf"
When implemented on command prompt:
The autovacuum utility goes about reallocating the deleted block of data (blocks which were marked deleted) to new transactions by first removing the dead/outdated tuples and then informing the queued transactions where any updates or insertions may be placed in the table. This is in stark contrast to the old and former procedure where a transaction would blindly insert a new row of data with the same identifying elements and updated attributes. The benefits of autovacuuming are quite evident:
Storage space is well-used.
Free-space map visibility is improved. An FSM is a map of multiple binary trees that indicate available spaces in the relations/tables.
Unlike manual vacuums, they are not time and resource-intensive.
They do not place exclusive locks on tables (FULL vacuums place locks on transactions wanting to access tables).
Table bloating is prevented. Bloating is a process by which the size of a table reaches enormous values with unnecessary and invalid data.
One way of monitoring data sizes before and after transactions is simply by executing the following lines of code in the Shell after connecting to a specific database:
postgresql=# SELECT pg_size_pretty(pg_relation_size('table_name');
Consider a table storing the accounts of customers at a Toll booth:
The size of this table is then given by:
If transactions ensue, this query may be dealt out again to demonstrate the change in size of the table. Disproportionate changes in size would suggest failed autovacuuming (if the size doesn’t change even though transactions have no use for the outdated state of rows).
Since autovacuum is a background utility, it is turned on by default. However, keep in mind that it was developed quite a while back and therefore the parameters set were conservative i.e., parameters were set according to the availability of hardware and version of the software. Modern applications call for reviewing these parameters and adjusting them proportionately. We shall have a quick look at the nodal parameters:
The AUTOVACUUM section in the postgresql.conf file.
autovacuum: It is set to ‘on’ by default so it may not be declared exclusively in the shell or terminal.
autovacuum_naptime: This parameter is set to 1min or 60s which indicates the duration between consecutive autovacuum calls or wakeups.
autovacuum_max_workers: This indicates the number of processes is vacuumed every time the function is woken up after ‘naptime’.
autovacuum_vacuum_scale_factor: usually set to 0.2, it means that autovacuum conducts a clean-up only if 20% of the relation/table has been changed/updated.
autovacuum_vacuum_threshold: A precautionary measure, this parameter ensures that autovacuuming happens only if a set number of changes are made to the table (50 by default).
autovacuum_analyze_scale_factor: this is the analyzing utility that creates regular statistics of tables during transactions. If set to 0.1, analysis is done only if 10% of the table observes updates (deletes, updates, inserts, alters, etc.).
autovacuum_analyze_threshold: similar to autovacuum_vacuum_threshold, although here the action performed is analysis. The analysis is performed only if a minimum of 50 changes has been made by the transactions.
These parameters are modified based on the frequency at which transactions affect the database and how large the database is or is expected to grow. So, if transactions seem to be occurring at faster rates, autovacuum_max_workers may be increased or autovacuum_vacuum_scale_factor may be decreased if transactions aren’t expected to demand older data. Additionally, the developer may adjust the analysis parameters to formulate better query techniques.
This brings us to question the idea behind analyzing tables so often.
Analysis may be performed manually or simply by keeping autovacuum turned on. Analysis provides specific statistical information regarding the database which helps developers enhance efficiency. Essentially, analysis provides the following information:
A list of the most common values in a specific column of a relation/table. In some cases, this isn’t required as the column might be the unique identifier – unique identifiers cannot be expected to repeat in a table.A histogram of the data distribution. This may include the sizes of data respective to columns or which columns are subject to the highest and lowest updates from transactions.
A list of the most common values in a specific column of a relation/table. In some cases, this isn’t required as the column might be the unique identifier – unique identifiers cannot be expected to repeat in a table.
A histogram of the data distribution. This may include the sizes of data respective to columns or which columns are subject to the highest and lowest updates from transactions.
Now answering the pertinent question — which tables actually require analysis. By the means of autovacuum, most tables are subjected to analysis. Nevertheless, in the likely case that the explicit ANALYZE function is issued, it is done due to the following reasons:
Used when UPDATE activities don’t seem to directly affect certain columns. It might so happen that the statistics of certain columns are required which are not changed by ongoing transactions. Hence, the automatic analysis may be insignificant.
Analysis may be important to keep a tab on tables in which the rate at which updates occur is relevant.
To understand which aspects of the data are least prone to changes to establish a pattern.
Yet another question that may be posed is – How to shortlist tables on which analysis daemon must be separately issued?
There exists a simple rule of thumb: analysis on tables makes sense as long as the minimum or maximum values of the columns are prone to changes. For example, a table showing speeds of vehicles measured by a velocity gun is bound to have its maximum values change. Therefore, the analysis will yield something conclusive.
Picked
postgreSQL-administration
DBMS
PostgreSQL
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
What is Temporary Table in SQL?
PostgreSQL - DELETE
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - Data Types
PostgreSQL - Date Data Type
|
[
{
"code": null,
"e": 25549,
"s": 25521,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 26087,
"s": 25549,
"text": "Sometime in the 2000s the developers of PostgreSQL found a major loophole in the design of their relational database management system with respect to storage space and transaction speed. It turned out that the UPDATE query was becoming an expensive routine. UPDATE was duplicating the old row and rewriting new data in, which meant that the size of the database or the tables were not bound to any limit! Additionally, deleting a row only MARKED the row deleted while the actual data remained untouched – data forensics supported later."
},
{
"code": null,
"e": 26724,
"s": 26087,
"text": "This may sound familiar since it is what present-day file systems and data recovery software rely on i.e., data, when deleted, remains intact on the magnetic disk in its raw form, but is hidden on the interface. However, keeping old data was important for older transactions as well. So technically, it wasn’t right to compromise on transactional integrity. This being sufficient stimulus, the Postgres team soon introduced the ‘vacuum’ feature which literally vacuumed the deleted rows. However, this was a manual process and due to the several parameters involved in the function, it wasn’t desirable. Hence, autovacuum was developed."
},
{
"code": null,
"e": 27138,
"s": 26724,
"text": "Autovacuum is a daemon or background utility process offered by PostgreSQL to users to issue a regular clean-up of redundant data in the database and server. It does not require the user to manually issue the vacuuming and instead, is defined in the postgresql.conf file. In order to access this file, simply direct yourself to the following directory on your terminal and then open the file in a suitable editor."
},
{
"code": null,
"e": 27201,
"s": 27138,
"text": ">> cd C:\\Program Files\\PostgreSQL\\13\\data\n>> \"postgresql.conf\""
},
{
"code": null,
"e": 27237,
"s": 27201,
"text": "When implemented on command prompt:"
},
{
"code": null,
"e": 27736,
"s": 27237,
"text": "The autovacuum utility goes about reallocating the deleted block of data (blocks which were marked deleted) to new transactions by first removing the dead/outdated tuples and then informing the queued transactions where any updates or insertions may be placed in the table. This is in stark contrast to the old and former procedure where a transaction would blindly insert a new row of data with the same identifying elements and updated attributes. The benefits of autovacuuming are quite evident:"
},
{
"code": null,
"e": 27764,
"s": 27736,
"text": "Storage space is well-used."
},
{
"code": null,
"e": 27900,
"s": 27764,
"text": "Free-space map visibility is improved. An FSM is a map of multiple binary trees that indicate available spaces in the relations/tables."
},
{
"code": null,
"e": 27965,
"s": 27900,
"text": "Unlike manual vacuums, they are not time and resource-intensive."
},
{
"code": null,
"e": 28078,
"s": 27965,
"text": "They do not place exclusive locks on tables (FULL vacuums place locks on transactions wanting to access tables)."
},
{
"code": null,
"e": 28217,
"s": 28078,
"text": "Table bloating is prevented. Bloating is a process by which the size of a table reaches enormous values with unnecessary and invalid data."
},
{
"code": null,
"e": 28385,
"s": 28217,
"text": "One way of monitoring data sizes before and after transactions is simply by executing the following lines of code in the Shell after connecting to a specific database:"
},
{
"code": null,
"e": 28452,
"s": 28385,
"text": "postgresql=# SELECT pg_size_pretty(pg_relation_size('table_name');"
},
{
"code": null,
"e": 28520,
"s": 28452,
"text": "Consider a table storing the accounts of customers at a Toll booth:"
},
{
"code": null,
"e": 28562,
"s": 28520,
"text": "The size of this table is then given by: "
},
{
"code": null,
"e": 28835,
"s": 28562,
"text": "If transactions ensue, this query may be dealt out again to demonstrate the change in size of the table. Disproportionate changes in size would suggest failed autovacuuming (if the size doesn’t change even though transactions have no use for the outdated state of rows). "
},
{
"code": null,
"e": 29260,
"s": 28835,
"text": "Since autovacuum is a background utility, it is turned on by default. However, keep in mind that it was developed quite a while back and therefore the parameters set were conservative i.e., parameters were set according to the availability of hardware and version of the software. Modern applications call for reviewing these parameters and adjusting them proportionately. We shall have a quick look at the nodal parameters:"
},
{
"code": null,
"e": 29312,
"s": 29260,
"text": "The AUTOVACUUM section in the postgresql.conf file."
},
{
"code": null,
"e": 29417,
"s": 29312,
"text": "autovacuum: It is set to ‘on’ by default so it may not be declared exclusively in the shell or terminal."
},
{
"code": null,
"e": 29552,
"s": 29417,
"text": "autovacuum_naptime: This parameter is set to 1min or 60s which indicates the duration between consecutive autovacuum calls or wakeups."
},
{
"code": null,
"e": 29680,
"s": 29552,
"text": "autovacuum_max_workers: This indicates the number of processes is vacuumed every time the function is woken up after ‘naptime’."
},
{
"code": null,
"e": 29837,
"s": 29680,
"text": "autovacuum_vacuum_scale_factor: usually set to 0.2, it means that autovacuum conducts a clean-up only if 20% of the relation/table has been changed/updated."
},
{
"code": null,
"e": 30012,
"s": 29837,
"text": "autovacuum_vacuum_threshold: A precautionary measure, this parameter ensures that autovacuuming happens only if a set number of changes are made to the table (50 by default)."
},
{
"code": null,
"e": 30255,
"s": 30012,
"text": "autovacuum_analyze_scale_factor: this is the analyzing utility that creates regular statistics of tables during transactions. If set to 0.1, analysis is done only if 10% of the table observes updates (deletes, updates, inserts, alters, etc.)."
},
{
"code": null,
"e": 30466,
"s": 30255,
"text": "autovacuum_analyze_threshold: similar to autovacuum_vacuum_threshold, although here the action performed is analysis. The analysis is performed only if a minimum of 50 changes has been made by the transactions."
},
{
"code": null,
"e": 30919,
"s": 30466,
"text": "These parameters are modified based on the frequency at which transactions affect the database and how large the database is or is expected to grow. So, if transactions seem to be occurring at faster rates, autovacuum_max_workers may be increased or autovacuum_vacuum_scale_factor may be decreased if transactions aren’t expected to demand older data. Additionally, the developer may adjust the analysis parameters to formulate better query techniques."
},
{
"code": null,
"e": 30989,
"s": 30919,
"text": "This brings us to question the idea behind analyzing tables so often."
},
{
"code": null,
"e": 31242,
"s": 30989,
"text": "Analysis may be performed manually or simply by keeping autovacuum turned on. Analysis provides specific statistical information regarding the database which helps developers enhance efficiency. Essentially, analysis provides the following information:"
},
{
"code": null,
"e": 31635,
"s": 31242,
"text": "A list of the most common values in a specific column of a relation/table. In some cases, this isn’t required as the column might be the unique identifier – unique identifiers cannot be expected to repeat in a table.A histogram of the data distribution. This may include the sizes of data respective to columns or which columns are subject to the highest and lowest updates from transactions."
},
{
"code": null,
"e": 31852,
"s": 31635,
"text": "A list of the most common values in a specific column of a relation/table. In some cases, this isn’t required as the column might be the unique identifier – unique identifiers cannot be expected to repeat in a table."
},
{
"code": null,
"e": 32029,
"s": 31852,
"text": "A histogram of the data distribution. This may include the sizes of data respective to columns or which columns are subject to the highest and lowest updates from transactions."
},
{
"code": null,
"e": 32295,
"s": 32029,
"text": "Now answering the pertinent question — which tables actually require analysis. By the means of autovacuum, most tables are subjected to analysis. Nevertheless, in the likely case that the explicit ANALYZE function is issued, it is done due to the following reasons:"
},
{
"code": null,
"e": 32540,
"s": 32295,
"text": "Used when UPDATE activities don’t seem to directly affect certain columns. It might so happen that the statistics of certain columns are required which are not changed by ongoing transactions. Hence, the automatic analysis may be insignificant."
},
{
"code": null,
"e": 32644,
"s": 32540,
"text": "Analysis may be important to keep a tab on tables in which the rate at which updates occur is relevant."
},
{
"code": null,
"e": 32735,
"s": 32644,
"text": "To understand which aspects of the data are least prone to changes to establish a pattern."
},
{
"code": null,
"e": 32856,
"s": 32735,
"text": "Yet another question that may be posed is – How to shortlist tables on which analysis daemon must be separately issued? "
},
{
"code": null,
"e": 33178,
"s": 32856,
"text": "There exists a simple rule of thumb: analysis on tables makes sense as long as the minimum or maximum values of the columns are prone to changes. For example, a table showing speeds of vehicles measured by a velocity gun is bound to have its maximum values change. Therefore, the analysis will yield something conclusive."
},
{
"code": null,
"e": 33185,
"s": 33178,
"text": "Picked"
},
{
"code": null,
"e": 33211,
"s": 33185,
"text": "postgreSQL-administration"
},
{
"code": null,
"e": 33216,
"s": 33211,
"text": "DBMS"
},
{
"code": null,
"e": 33227,
"s": 33216,
"text": "PostgreSQL"
},
{
"code": null,
"e": 33232,
"s": 33227,
"text": "DBMS"
},
{
"code": null,
"e": 33330,
"s": 33232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33347,
"s": 33330,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 33388,
"s": 33347,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 33415,
"s": 33388,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 33448,
"s": 33415,
"text": "Conflict Serializability in DBMS"
},
{
"code": null,
"e": 33480,
"s": 33448,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 33500,
"s": 33480,
"text": "PostgreSQL - DELETE"
},
{
"code": null,
"e": 33527,
"s": 33500,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 33559,
"s": 33527,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 33583,
"s": 33559,
"text": "PostgreSQL - Data Types"
}
] |
Collecting data with Google forms and Pandas - GeeksforGeeks
|
08 May, 2021
In this article, we will discuss how to collect data from Google forms using Pandas.
pydrive: This is used to simplify many common Google Drive API tasks. To install this type the below command in the terminal.
pip install pydrive
xlrd: This module is used to extract data from a spreadsheet. To install this type the below command in the terminal.
pip install xlrd
openpyxl: This is a Python library for reading and writing Excel. To install this type the below command in the terminal.
pip install openpyxl
The First important part of the whole process is to create a Google Form. Visit this link and create a new form.
Form Creation in Google Forms
When we are done setting up the questions, click Send button to publish the form. To access this Google form, click here.
The next step is to authenticate our Python Script and Local Environment with Google and access the Google Form Data from Google Drive by enabling the Google Drive API in Google Cloud Platform. Follow these steps:
Goto the Google FormResponses Tab,Click the spreadsheet iconAnd create a new Destination Spreadsheet for our google form.
Goto the Google Form
Responses Tab,
Click the spreadsheet icon
And create a new Destination Spreadsheet for our google form.
Link a new spreadsheet and Google Form
This Spreadsheet will be created and stored in Google Drive. We have to integrate Google Drive and Python Environment. First, we have to authenticate with Google.
Now, to work with Google Drive API, we have to set up our account, enable Google Drive API and obtain our client_secrets.json key.
1. Go to the Google Cloud Platform Console, click on New Project / Projects → New Project, on the GCP Toolbar.
Click on the Project Name and then select New Project
2. Enter a name for our project and click Create.
Creation of a GCP Project
3. In the home screen of our project, click on the Navigation Bar in the Top-Left Corner and Click APIs and Services, and Select OAuth Consent Screen.
Navigating to Oauth Consent Screen
4. In the OAuth Consent Screen Homepage, select External and click Create
Oauth Initial Step
5. In the next screen, Enter the mandatory details that include App Name, User Support Email, and Developer Contact Information. Click on “Save and Continue” and proceed to the Summary Page.
App Details
6. In the Summary Screen, click “Back to Dashboard”. We will now have an option to Publish our App. Now We are ready to Push our App to production.
Publish our App
7. Now that We have published our App, click on Search Bar and search for Google Drive API. Select the Google Drive API and enable the Service.
Search for Google Drive API Service
Enable the Google Drive API
8. Now that We have published our App and enabled the Google Drive API, click on Navigation Bar, and in APIs and Services, select Credentials.
Create Credentials
9. In the OAuth Client ID Screen, Select Application Type as Desktop App, Enter the Name and click Create.
Create OAuth Client ID
9. We will be redirected to Credential Homepage where we will be able to find our OAuth Client ID. Click on the Download Key Option and save the .JSON file by the name client_secrets.json
Download the Secret Key
Note: This secret key and the Python File created below should be present in the same directory.
Python Implementation:
Python3
from pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDriveimport pandas as pd # Initializing a GoogleAuth Objectgauth = GoogleAuth() # client_secrets.json file is verified# and it automatically handles authenticationgauth.LocalWebserverAuth() # GoogleDrive Instance is created using# authenticated GoogleAuth instancedrive = GoogleDrive(gauth) # Initialize GoogleDriveFile instance with file idfile_obj = drive.CreateFile({'id': 'FILE_ID'})file_obj.GetContentFile('FILE_NAME.xls', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') dataframe = pd.read_excel('FILE_NAME.xls')print(dataframe)
Note: The Google Accounts used for Google Forms Creation and Python Environment GDrive Authentication must be the same
When We run the code, a Google Authentication Flow window pops up in our default Web Browser. We have to select our Google Account and Continue with the Flow.
Select our google account
Click Advanced -> Go to GFG App (unsafe)
We have to allow permission and again click Allow in the Next Screen.
Enable Permission for our App
Now we will receive a message in our browser which says “The authentication flow has completed”. And move to our Python environment, we will be able to see the Data in Pandas Dataframe format.
Output:
Pandas dataframe obtained in Real-Time from Google form through Google Drive API
Picked
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n08 May, 2021"
},
{
"code": null,
"e": 25649,
"s": 25563,
"text": "In this article, we will discuss how to collect data from Google forms using Pandas. "
},
{
"code": null,
"e": 25775,
"s": 25649,
"text": "pydrive: This is used to simplify many common Google Drive API tasks. To install this type the below command in the terminal."
},
{
"code": null,
"e": 25795,
"s": 25775,
"text": "pip install pydrive"
},
{
"code": null,
"e": 25913,
"s": 25795,
"text": "xlrd: This module is used to extract data from a spreadsheet. To install this type the below command in the terminal."
},
{
"code": null,
"e": 25930,
"s": 25913,
"text": "pip install xlrd"
},
{
"code": null,
"e": 26052,
"s": 25930,
"text": "openpyxl: This is a Python library for reading and writing Excel. To install this type the below command in the terminal."
},
{
"code": null,
"e": 26073,
"s": 26052,
"text": "pip install openpyxl"
},
{
"code": null,
"e": 26186,
"s": 26073,
"text": "The First important part of the whole process is to create a Google Form. Visit this link and create a new form."
},
{
"code": null,
"e": 26216,
"s": 26186,
"text": "Form Creation in Google Forms"
},
{
"code": null,
"e": 26338,
"s": 26216,
"text": "When we are done setting up the questions, click Send button to publish the form. To access this Google form, click here."
},
{
"code": null,
"e": 26552,
"s": 26338,
"text": "The next step is to authenticate our Python Script and Local Environment with Google and access the Google Form Data from Google Drive by enabling the Google Drive API in Google Cloud Platform. Follow these steps:"
},
{
"code": null,
"e": 26674,
"s": 26552,
"text": "Goto the Google FormResponses Tab,Click the spreadsheet iconAnd create a new Destination Spreadsheet for our google form."
},
{
"code": null,
"e": 26695,
"s": 26674,
"text": "Goto the Google Form"
},
{
"code": null,
"e": 26710,
"s": 26695,
"text": "Responses Tab,"
},
{
"code": null,
"e": 26737,
"s": 26710,
"text": "Click the spreadsheet icon"
},
{
"code": null,
"e": 26799,
"s": 26737,
"text": "And create a new Destination Spreadsheet for our google form."
},
{
"code": null,
"e": 26838,
"s": 26799,
"text": "Link a new spreadsheet and Google Form"
},
{
"code": null,
"e": 27001,
"s": 26838,
"text": "This Spreadsheet will be created and stored in Google Drive. We have to integrate Google Drive and Python Environment. First, we have to authenticate with Google."
},
{
"code": null,
"e": 27132,
"s": 27001,
"text": "Now, to work with Google Drive API, we have to set up our account, enable Google Drive API and obtain our client_secrets.json key."
},
{
"code": null,
"e": 27243,
"s": 27132,
"text": "1. Go to the Google Cloud Platform Console, click on New Project / Projects → New Project, on the GCP Toolbar."
},
{
"code": null,
"e": 27297,
"s": 27243,
"text": "Click on the Project Name and then select New Project"
},
{
"code": null,
"e": 27347,
"s": 27297,
"text": "2. Enter a name for our project and click Create."
},
{
"code": null,
"e": 27373,
"s": 27347,
"text": "Creation of a GCP Project"
},
{
"code": null,
"e": 27525,
"s": 27373,
"text": "3. In the home screen of our project, click on the Navigation Bar in the Top-Left Corner and Click APIs and Services, and Select OAuth Consent Screen. "
},
{
"code": null,
"e": 27560,
"s": 27525,
"text": "Navigating to Oauth Consent Screen"
},
{
"code": null,
"e": 27634,
"s": 27560,
"text": "4. In the OAuth Consent Screen Homepage, select External and click Create"
},
{
"code": null,
"e": 27653,
"s": 27634,
"text": "Oauth Initial Step"
},
{
"code": null,
"e": 27844,
"s": 27653,
"text": "5. In the next screen, Enter the mandatory details that include App Name, User Support Email, and Developer Contact Information. Click on “Save and Continue” and proceed to the Summary Page."
},
{
"code": null,
"e": 27856,
"s": 27844,
"text": "App Details"
},
{
"code": null,
"e": 28004,
"s": 27856,
"text": "6. In the Summary Screen, click “Back to Dashboard”. We will now have an option to Publish our App. Now We are ready to Push our App to production."
},
{
"code": null,
"e": 28020,
"s": 28004,
"text": "Publish our App"
},
{
"code": null,
"e": 28164,
"s": 28020,
"text": "7. Now that We have published our App, click on Search Bar and search for Google Drive API. Select the Google Drive API and enable the Service."
},
{
"code": null,
"e": 28200,
"s": 28164,
"text": "Search for Google Drive API Service"
},
{
"code": null,
"e": 28228,
"s": 28200,
"text": "Enable the Google Drive API"
},
{
"code": null,
"e": 28371,
"s": 28228,
"text": "8. Now that We have published our App and enabled the Google Drive API, click on Navigation Bar, and in APIs and Services, select Credentials."
},
{
"code": null,
"e": 28390,
"s": 28371,
"text": "Create Credentials"
},
{
"code": null,
"e": 28497,
"s": 28390,
"text": "9. In the OAuth Client ID Screen, Select Application Type as Desktop App, Enter the Name and click Create."
},
{
"code": null,
"e": 28520,
"s": 28497,
"text": "Create OAuth Client ID"
},
{
"code": null,
"e": 28708,
"s": 28520,
"text": "9. We will be redirected to Credential Homepage where we will be able to find our OAuth Client ID. Click on the Download Key Option and save the .JSON file by the name client_secrets.json"
},
{
"code": null,
"e": 28732,
"s": 28708,
"text": "Download the Secret Key"
},
{
"code": null,
"e": 28829,
"s": 28732,
"text": "Note: This secret key and the Python File created below should be present in the same directory."
},
{
"code": null,
"e": 28852,
"s": 28829,
"text": "Python Implementation:"
},
{
"code": null,
"e": 28860,
"s": 28852,
"text": "Python3"
},
{
"code": "from pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDriveimport pandas as pd # Initializing a GoogleAuth Objectgauth = GoogleAuth() # client_secrets.json file is verified# and it automatically handles authenticationgauth.LocalWebserverAuth() # GoogleDrive Instance is created using# authenticated GoogleAuth instancedrive = GoogleDrive(gauth) # Initialize GoogleDriveFile instance with file idfile_obj = drive.CreateFile({'id': 'FILE_ID'})file_obj.GetContentFile('FILE_NAME.xls', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') dataframe = pd.read_excel('FILE_NAME.xls')print(dataframe)",
"e": 29505,
"s": 28860,
"text": null
},
{
"code": null,
"e": 29624,
"s": 29505,
"text": "Note: The Google Accounts used for Google Forms Creation and Python Environment GDrive Authentication must be the same"
},
{
"code": null,
"e": 29783,
"s": 29624,
"text": "When We run the code, a Google Authentication Flow window pops up in our default Web Browser. We have to select our Google Account and Continue with the Flow."
},
{
"code": null,
"e": 29809,
"s": 29783,
"text": "Select our google account"
},
{
"code": null,
"e": 29850,
"s": 29809,
"text": "Click Advanced -> Go to GFG App (unsafe)"
},
{
"code": null,
"e": 29920,
"s": 29850,
"text": "We have to allow permission and again click Allow in the Next Screen."
},
{
"code": null,
"e": 29950,
"s": 29920,
"text": "Enable Permission for our App"
},
{
"code": null,
"e": 30143,
"s": 29950,
"text": "Now we will receive a message in our browser which says “The authentication flow has completed”. And move to our Python environment, we will be able to see the Data in Pandas Dataframe format."
},
{
"code": null,
"e": 30151,
"s": 30143,
"text": "Output:"
},
{
"code": null,
"e": 30232,
"s": 30151,
"text": "Pandas dataframe obtained in Real-Time from Google form through Google Drive API"
},
{
"code": null,
"e": 30239,
"s": 30232,
"text": "Picked"
},
{
"code": null,
"e": 30253,
"s": 30239,
"text": "Python-pandas"
},
{
"code": null,
"e": 30260,
"s": 30253,
"text": "Python"
},
{
"code": null,
"e": 30358,
"s": 30260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30390,
"s": 30358,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30432,
"s": 30390,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30474,
"s": 30432,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30501,
"s": 30474,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30557,
"s": 30501,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30579,
"s": 30557,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30618,
"s": 30579,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30649,
"s": 30618,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30678,
"s": 30649,
"text": "Create a directory in Python"
}
] |
How to store a very large number of more than 100 digits in C++ - GeeksforGeeks
|
06 Oct, 2021
Given an integer N in form of string str consisting of more than 100 digits, the task is to store the value for performing an arithmetic operation and print the given integer.Examples:
Input: str = “54326789013892014531903492543267890138920145319034925432678901389201” Output: 54326789013892014531903492543267890138920145319034925432678901389201Input: str = “7890138920145319034925432678907890138920145319034925432678901903492543267890” Output: 7890138920145319034925432678907890138920145319034925432678901903492543267890
Approach: No data type is present in C++ to store 10100. So, the idea is to use get the input as string (as string can be of any length) and then convert this string into an array of digits of the length same as the length of string. Storing the big integer into an integer array will help to perform some basic arithmetic on that number. Below are the steps:
Take the large number as input and store it in a string.Create an integer array arr[] of length same as the string size.Iterate over all characters (digits) of string str one by one and store that digits in the corresponding index of the array arr
Take the large number as input and store it in a string.
Create an integer array arr[] of length same as the string size.
Iterate over all characters (digits) of string str one by one and store that digits in the corresponding index of the array arr
arr[i] = str[i] – ‘0’;// Here ‘0’ represents the digit 0, and // str[i] – ‘0’ = ASCII(str[i]) – ASCII(‘0’) = ASCII(str[i] – 48
Using the above step, we can store very very large number for doing any arithmetic operations.
Using the above step, we can store very very large number for doing any arithmetic operations.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <iostream>using namespace std; // Function to return dynamic allocated// array consisting integers individuallyint* GetBigInteger(string str){ int x = str.size(), a = 0; // Create an array to store the big // integer into it. // Make the array size same as the // size of string str int* arr = new int[str.size()]; // Loop to extract string elements // into the array one by one while (a != x) { // Subtracting '0' to convert // each character into digit // str[a] - '0' // = ASCII(str[a]) - ASCII('0') // = ASCII(str[a] - 48 arr[a] = str[a] - '0'; a++; } // Return the reference of the array return arr;} // Driver Codeint main(){ // Big Integer in form of string str string str = "12345678098765431234567809876543"; // Function Call int* arr = GetBigInteger(str); // Print the digits in the arr[] for (int i = 0; i < str.size(); i++) { cout << arr[i]; } return 0;}
12345678098765431234567809876543
Time Complexity: O(K), K is the number of digits in the number Auxiliary Space: O(K), K is the number of digits in the number
arorakashish0911
cpp-input-output
large-numbers
number-digits
Numbers
Arrays
C++ Programs
Mathematical
Strings
Arrays
Strings
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26254,
"s": 26067,
"text": "Given an integer N in form of string str consisting of more than 100 digits, the task is to store the value for performing an arithmetic operation and print the given integer.Examples: "
},
{
"code": null,
"e": 26593,
"s": 26254,
"text": "Input: str = “54326789013892014531903492543267890138920145319034925432678901389201” Output: 54326789013892014531903492543267890138920145319034925432678901389201Input: str = “7890138920145319034925432678907890138920145319034925432678901903492543267890” Output: 7890138920145319034925432678907890138920145319034925432678901903492543267890 "
},
{
"code": null,
"e": 26956,
"s": 26595,
"text": "Approach: No data type is present in C++ to store 10100. So, the idea is to use get the input as string (as string can be of any length) and then convert this string into an array of digits of the length same as the length of string. Storing the big integer into an integer array will help to perform some basic arithmetic on that number. Below are the steps: "
},
{
"code": null,
"e": 27206,
"s": 26956,
"text": "Take the large number as input and store it in a string.Create an integer array arr[] of length same as the string size.Iterate over all characters (digits) of string str one by one and store that digits in the corresponding index of the array arr "
},
{
"code": null,
"e": 27263,
"s": 27206,
"text": "Take the large number as input and store it in a string."
},
{
"code": null,
"e": 27328,
"s": 27263,
"text": "Create an integer array arr[] of length same as the string size."
},
{
"code": null,
"e": 27458,
"s": 27328,
"text": "Iterate over all characters (digits) of string str one by one and store that digits in the corresponding index of the array arr "
},
{
"code": null,
"e": 27587,
"s": 27458,
"text": "arr[i] = str[i] – ‘0’;// Here ‘0’ represents the digit 0, and // str[i] – ‘0’ = ASCII(str[i]) – ASCII(‘0’) = ASCII(str[i] – 48 "
},
{
"code": null,
"e": 27683,
"s": 27587,
"text": " Using the above step, we can store very very large number for doing any arithmetic operations."
},
{
"code": null,
"e": 27780,
"s": 27685,
"text": "Using the above step, we can store very very large number for doing any arithmetic operations."
},
{
"code": null,
"e": 27832,
"s": 27780,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27836,
"s": 27832,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to return dynamic allocated// array consisting integers individuallyint* GetBigInteger(string str){ int x = str.size(), a = 0; // Create an array to store the big // integer into it. // Make the array size same as the // size of string str int* arr = new int[str.size()]; // Loop to extract string elements // into the array one by one while (a != x) { // Subtracting '0' to convert // each character into digit // str[a] - '0' // = ASCII(str[a]) - ASCII('0') // = ASCII(str[a] - 48 arr[a] = str[a] - '0'; a++; } // Return the reference of the array return arr;} // Driver Codeint main(){ // Big Integer in form of string str string str = \"12345678098765431234567809876543\"; // Function Call int* arr = GetBigInteger(str); // Print the digits in the arr[] for (int i = 0; i < str.size(); i++) { cout << arr[i]; } return 0;}",
"e": 28873,
"s": 27836,
"text": null
},
{
"code": null,
"e": 28906,
"s": 28873,
"text": "12345678098765431234567809876543"
},
{
"code": null,
"e": 29035,
"s": 28908,
"text": "Time Complexity: O(K), K is the number of digits in the number Auxiliary Space: O(K), K is the number of digits in the number "
},
{
"code": null,
"e": 29052,
"s": 29035,
"text": "arorakashish0911"
},
{
"code": null,
"e": 29069,
"s": 29052,
"text": "cpp-input-output"
},
{
"code": null,
"e": 29083,
"s": 29069,
"text": "large-numbers"
},
{
"code": null,
"e": 29097,
"s": 29083,
"text": "number-digits"
},
{
"code": null,
"e": 29105,
"s": 29097,
"text": "Numbers"
},
{
"code": null,
"e": 29112,
"s": 29105,
"text": "Arrays"
},
{
"code": null,
"e": 29125,
"s": 29112,
"text": "C++ Programs"
},
{
"code": null,
"e": 29138,
"s": 29125,
"text": "Mathematical"
},
{
"code": null,
"e": 29146,
"s": 29138,
"text": "Strings"
},
{
"code": null,
"e": 29153,
"s": 29146,
"text": "Arrays"
},
{
"code": null,
"e": 29161,
"s": 29153,
"text": "Strings"
},
{
"code": null,
"e": 29174,
"s": 29161,
"text": "Mathematical"
},
{
"code": null,
"e": 29182,
"s": 29174,
"text": "Numbers"
},
{
"code": null,
"e": 29280,
"s": 29182,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29311,
"s": 29280,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 29338,
"s": 29311,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 29363,
"s": 29338,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29401,
"s": 29363,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 29422,
"s": 29401,
"text": "Next Greater Element"
},
{
"code": null,
"e": 29457,
"s": 29422,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29501,
"s": 29457,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 29560,
"s": 29501,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29586,
"s": 29560,
"text": "C++ Program for QuickSort"
}
] |
Return by reference in C++ with Examples
|
01 Aug, 2020
Pointers and References in C++ held close relation with one another. The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable.
Functions in C++ can return a reference as it’s returns a pointer.
When function returns a reference it means it returns a implicit pointer.
Return by reference is very different from Call by reference. Functions behaves a very important role when variable or pointers are returned as reference.
See this function signature of Return by Reference Below:
dataType& functionName(parameters);where,dataType is the return type of the function,and parameters are the passed arguments to it.
Below is the code to illustrate the Return by reference:
CPP
// C++ program to illustrate return by reference#include <iostream>using namespace std; // Function to return as return by referenceint& returnValue(int& x){ // Print the address cout << "x = " << x << " The address of x is " << &x << endl; // Return reference return x;} // Driver Codeint main(){ int a = 20; int& b = returnValue(a); // Print a and its address cout << "a = " << a << " The address of a is " << &a << endl; // Print b and its address cout << "b = " << b << " The address of b is " << &b << endl; // We can also change the value of // 'a' by using the address returned // by returnValue function // Since the function returns an alias // of x, which is itself an alias of a, // we can update the value of a returnValue(a) = 13; // The above expression assigns the // value to the returned alias as 3. cout << "a = " << a << " The address of a is " << &a << endl; return 0;}
x = 20 The address of x is 0x7fff3025711c
a = 20 The address of a is 0x7fff3025711c
b = 20 The address of b is 0x7fff3025711c
x = 20 The address of x is 0x7fff3025711c
a = 13 The address of a is 0x7fff3025711c
Explanation:
Since reference is nothing but an alias(synonym) of another variable, the address of a, b and x never changes.
Note: We should never return a local variable as a reference, reason being, as soon as the functions returns, local variable will be erased, however, we still will be left with a reference which might be a security bug in the code.
Below is the code to illustrate the Return by reference:
C++
// C++ program to illustrate return// by reference#include <iostream>using namespace std; // Global variableint x; // Function returns as a return// by referenceint& retByRef(){ return x;} // Driver Codeint main(){ // Function Call for return // by reference retByRef() = 10; // Print X cout << x; return 0;}
10
Explanation:Return type of the above function retByRef() is a reference of the variable x so value 10 will be assigned into the x.
cpp-references
return
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Dynamic _Cast in C++
Different ways to print elements of vector
How to convert a Vector to Set in C++
Why it is important to write "using namespace std" in C++ program?
string::npos in C++ with Examples
Maximum value of long long int in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 262,
"s": 54,
"text": "Pointers and References in C++ held close relation with one another. The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable."
},
{
"code": null,
"e": 329,
"s": 262,
"text": "Functions in C++ can return a reference as it’s returns a pointer."
},
{
"code": null,
"e": 403,
"s": 329,
"text": "When function returns a reference it means it returns a implicit pointer."
},
{
"code": null,
"e": 558,
"s": 403,
"text": "Return by reference is very different from Call by reference. Functions behaves a very important role when variable or pointers are returned as reference."
},
{
"code": null,
"e": 616,
"s": 558,
"text": "See this function signature of Return by Reference Below:"
},
{
"code": null,
"e": 748,
"s": 616,
"text": "dataType& functionName(parameters);where,dataType is the return type of the function,and parameters are the passed arguments to it."
},
{
"code": null,
"e": 805,
"s": 748,
"text": "Below is the code to illustrate the Return by reference:"
},
{
"code": null,
"e": 809,
"s": 805,
"text": "CPP"
},
{
"code": "// C++ program to illustrate return by reference#include <iostream>using namespace std; // Function to return as return by referenceint& returnValue(int& x){ // Print the address cout << \"x = \" << x << \" The address of x is \" << &x << endl; // Return reference return x;} // Driver Codeint main(){ int a = 20; int& b = returnValue(a); // Print a and its address cout << \"a = \" << a << \" The address of a is \" << &a << endl; // Print b and its address cout << \"b = \" << b << \" The address of b is \" << &b << endl; // We can also change the value of // 'a' by using the address returned // by returnValue function // Since the function returns an alias // of x, which is itself an alias of a, // we can update the value of a returnValue(a) = 13; // The above expression assigns the // value to the returned alias as 3. cout << \"a = \" << a << \" The address of a is \" << &a << endl; return 0;}",
"e": 1842,
"s": 809,
"text": null
},
{
"code": null,
"e": 2053,
"s": 1842,
"text": "x = 20 The address of x is 0x7fff3025711c\na = 20 The address of a is 0x7fff3025711c\nb = 20 The address of b is 0x7fff3025711c\nx = 20 The address of x is 0x7fff3025711c\na = 13 The address of a is 0x7fff3025711c\n"
},
{
"code": null,
"e": 2066,
"s": 2053,
"text": "Explanation:"
},
{
"code": null,
"e": 2177,
"s": 2066,
"text": "Since reference is nothing but an alias(synonym) of another variable, the address of a, b and x never changes."
},
{
"code": null,
"e": 2409,
"s": 2177,
"text": "Note: We should never return a local variable as a reference, reason being, as soon as the functions returns, local variable will be erased, however, we still will be left with a reference which might be a security bug in the code."
},
{
"code": null,
"e": 2466,
"s": 2409,
"text": "Below is the code to illustrate the Return by reference:"
},
{
"code": null,
"e": 2470,
"s": 2466,
"text": "C++"
},
{
"code": "// C++ program to illustrate return// by reference#include <iostream>using namespace std; // Global variableint x; // Function returns as a return// by referenceint& retByRef(){ return x;} // Driver Codeint main(){ // Function Call for return // by reference retByRef() = 10; // Print X cout << x; return 0;}",
"e": 2805,
"s": 2470,
"text": null
},
{
"code": null,
"e": 2809,
"s": 2805,
"text": "10\n"
},
{
"code": null,
"e": 2940,
"s": 2809,
"text": "Explanation:Return type of the above function retByRef() is a reference of the variable x so value 10 will be assigned into the x."
},
{
"code": null,
"e": 2955,
"s": 2940,
"text": "cpp-references"
},
{
"code": null,
"e": 2962,
"s": 2955,
"text": "return"
},
{
"code": null,
"e": 2975,
"s": 2962,
"text": "C++ Programs"
},
{
"code": null,
"e": 3073,
"s": 2975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3114,
"s": 3073,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 3135,
"s": 3114,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 3147,
"s": 3135,
"text": "cout in C++"
},
{
"code": null,
"e": 3206,
"s": 3147,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 3227,
"s": 3206,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 3270,
"s": 3227,
"text": "Different ways to print elements of vector"
},
{
"code": null,
"e": 3308,
"s": 3270,
"text": "How to convert a Vector to Set in C++"
},
{
"code": null,
"e": 3375,
"s": 3308,
"text": "Why it is important to write \"using namespace std\" in C++ program?"
},
{
"code": null,
"e": 3409,
"s": 3375,
"text": "string::npos in C++ with Examples"
}
] |
Epsilon-Greedy Algorithm in Reinforcement Learning
|
04 May, 2020
In Reinforcement Learning, the agent or decision-maker learns what to do—how to map situations to actions—so as to maximize a numerical reward signal. The agent is not explicitly told which actions to take, but instead must discover which action yields the most reward through trial and error.
Multi-Armed Bandit Problem
The multi-armed bandit problem is used in reinforcement learning to formalize the notion of decision-making under uncertainty. In a multi-armed bandit problem, an agent(learner) chooses between k different actions and receives a reward based on the chosen action.The multi-armed bandits are also used to describe fundamental concepts in reinforcement learning, such as rewards, timesteps, and values.For selecting an action by an agent, we assume that each action has a separate distribution of rewards and there is at least one action that generates maximum numerical reward. Thus, the probability distribution of the rewards corresponding to each action is different and is unknown to the agent(decision-maker). Hence, the goal of the agent is to identify which action to choose to get the maximum reward after a given set of trials.
Action-Value and Action-Value EstimateFor an agent to decide which action yields the maximum reward, we must define the value of taking each action. We use the concept of probability to define these values using the action-value function.The value of selecting an action is defined as the expected reward received when taking that action from a set of all possible actions. Since the value of selecting an action is not known to the agent, so we use the ‘sample-average’ method to estimate the value of taking an action.
Exploration vs Exploitation
Exploration allows an agent to improve its current knowledge about each action, hopefully leading to long-term benefit. Improving the accuracy of the estimated action-values, enables an agent to make more informed decisions in the future.
Exploitation on the other hand, chooses the greedy action to get the most reward by exploiting the agent’s current action-value estimates. But by being greedy with respect to action-value estimates, may not actually get the most reward and lead to sub-optimal behaviour.When an agent explores, it gets more accurate estimates of action-values. And when it exploits, it might get more reward. It cannot, however, choose to do both simultaneously, which is also called the exploration-exploitation dilemma.
Epsilon-Greedy Action SelectionEpsilon-Greedy is a simple method to balance exploration and exploitation by choosing between exploration and exploitation randomly.The epsilon-greedy, where epsilon refers to the probability of choosing to explore, exploits most of the time with a small chance of exploring.
Code: Python code for Epsilon-Greedy
# Import required librariesimport numpy as npimport matplotlib.pyplot as plt # Define Action classclass Actions: def __init__(self, m): self.m = m self.mean = 0 self.N = 0 # Choose a random action def choose(self): return np.random.randn() + self.m # Update the action-value estimate def update(self, x): self.N += 1 self.mean = (1 - 1.0 / self.N)*self.mean + 1.0 / self.N * x def run_experiment(m1, m2, m3, eps, N): actions = [Actions(m1), Actions(m2), Actions(m3)] data = np.empty(N) for i in range(N): # epsilon greedy p = np.random.random() if p < eps: j = np.random.choice(3) else: j = np.argmax([a.mean for a in actions]) x = actions[j].choose() actions[j].update(x) # for the plot data[i] = x cumulative_average = np.cumsum(data) / (np.arange(N) + 1) # plot moving average ctr plt.plot(cumulative_average) plt.plot(np.ones(N)*m1) plt.plot(np.ones(N)*m2) plt.plot(np.ones(N)*m3) plt.xscale('log') plt.show() for a in actions: print(a.mean) return cumulative_average if __name__ == '__main__': c_1 = run_experiment(1.0, 2.0, 3.0, 0.1, 100000) c_05 = run_experiment(1.0, 2.0, 3.0, 0.05, 100000) c_01 = run_experiment(1.0, 2.0, 3.0, 0.01, 100000)
Output:
Code: Python code for getting the log output plot
# log scale plotplt.plot(c_1, label ='eps = 0.1')plt.plot(c_05, label ='eps = 0.05')plt.plot(c_01, label ='eps = 0.01')plt.legend()plt.xscale('log')plt.show()
Output:
Code: Python code for getting the linear output plot
# linear plotplt.figure(figsize = (12, 8))plt.plot(c_1, label ='eps = 0.1')plt.plot(c_05, label ='eps = 0.05')plt.plot(c_01, label ='eps = 0.01')plt.legend()plt.show()
Output:
Artificial Intelligence
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "In Reinforcement Learning, the agent or decision-maker learns what to do—how to map situations to actions—so as to maximize a numerical reward signal. The agent is not explicitly told which actions to take, but instead must discover which action yields the most reward through trial and error."
},
{
"code": null,
"e": 349,
"s": 322,
"text": "Multi-Armed Bandit Problem"
},
{
"code": null,
"e": 1185,
"s": 349,
"text": "The multi-armed bandit problem is used in reinforcement learning to formalize the notion of decision-making under uncertainty. In a multi-armed bandit problem, an agent(learner) chooses between k different actions and receives a reward based on the chosen action.The multi-armed bandits are also used to describe fundamental concepts in reinforcement learning, such as rewards, timesteps, and values.For selecting an action by an agent, we assume that each action has a separate distribution of rewards and there is at least one action that generates maximum numerical reward. Thus, the probability distribution of the rewards corresponding to each action is different and is unknown to the agent(decision-maker). Hence, the goal of the agent is to identify which action to choose to get the maximum reward after a given set of trials."
},
{
"code": null,
"e": 1706,
"s": 1185,
"text": "Action-Value and Action-Value EstimateFor an agent to decide which action yields the maximum reward, we must define the value of taking each action. We use the concept of probability to define these values using the action-value function.The value of selecting an action is defined as the expected reward received when taking that action from a set of all possible actions. Since the value of selecting an action is not known to the agent, so we use the ‘sample-average’ method to estimate the value of taking an action."
},
{
"code": null,
"e": 1734,
"s": 1706,
"text": "Exploration vs Exploitation"
},
{
"code": null,
"e": 1973,
"s": 1734,
"text": "Exploration allows an agent to improve its current knowledge about each action, hopefully leading to long-term benefit. Improving the accuracy of the estimated action-values, enables an agent to make more informed decisions in the future."
},
{
"code": null,
"e": 2478,
"s": 1973,
"text": "Exploitation on the other hand, chooses the greedy action to get the most reward by exploiting the agent’s current action-value estimates. But by being greedy with respect to action-value estimates, may not actually get the most reward and lead to sub-optimal behaviour.When an agent explores, it gets more accurate estimates of action-values. And when it exploits, it might get more reward. It cannot, however, choose to do both simultaneously, which is also called the exploration-exploitation dilemma."
},
{
"code": null,
"e": 2785,
"s": 2478,
"text": "Epsilon-Greedy Action SelectionEpsilon-Greedy is a simple method to balance exploration and exploitation by choosing between exploration and exploitation randomly.The epsilon-greedy, where epsilon refers to the probability of choosing to explore, exploits most of the time with a small chance of exploring."
},
{
"code": null,
"e": 2822,
"s": 2785,
"text": "Code: Python code for Epsilon-Greedy"
},
{
"code": "# Import required librariesimport numpy as npimport matplotlib.pyplot as plt # Define Action classclass Actions: def __init__(self, m): self.m = m self.mean = 0 self.N = 0 # Choose a random action def choose(self): return np.random.randn() + self.m # Update the action-value estimate def update(self, x): self.N += 1 self.mean = (1 - 1.0 / self.N)*self.mean + 1.0 / self.N * x def run_experiment(m1, m2, m3, eps, N): actions = [Actions(m1), Actions(m2), Actions(m3)] data = np.empty(N) for i in range(N): # epsilon greedy p = np.random.random() if p < eps: j = np.random.choice(3) else: j = np.argmax([a.mean for a in actions]) x = actions[j].choose() actions[j].update(x) # for the plot data[i] = x cumulative_average = np.cumsum(data) / (np.arange(N) + 1) # plot moving average ctr plt.plot(cumulative_average) plt.plot(np.ones(N)*m1) plt.plot(np.ones(N)*m2) plt.plot(np.ones(N)*m3) plt.xscale('log') plt.show() for a in actions: print(a.mean) return cumulative_average if __name__ == '__main__': c_1 = run_experiment(1.0, 2.0, 3.0, 0.1, 100000) c_05 = run_experiment(1.0, 2.0, 3.0, 0.05, 100000) c_01 = run_experiment(1.0, 2.0, 3.0, 0.01, 100000)",
"e": 4086,
"s": 2822,
"text": null
},
{
"code": null,
"e": 4094,
"s": 4086,
"text": "Output:"
},
{
"code": null,
"e": 4144,
"s": 4094,
"text": "Code: Python code for getting the log output plot"
},
{
"code": "# log scale plotplt.plot(c_1, label ='eps = 0.1')plt.plot(c_05, label ='eps = 0.05')plt.plot(c_01, label ='eps = 0.01')plt.legend()plt.xscale('log')plt.show()",
"e": 4303,
"s": 4144,
"text": null
},
{
"code": null,
"e": 4311,
"s": 4303,
"text": "Output:"
},
{
"code": null,
"e": 4364,
"s": 4311,
"text": "Code: Python code for getting the linear output plot"
},
{
"code": "# linear plotplt.figure(figsize = (12, 8))plt.plot(c_1, label ='eps = 0.1')plt.plot(c_05, label ='eps = 0.05')plt.plot(c_01, label ='eps = 0.01')plt.legend()plt.show()",
"e": 4532,
"s": 4364,
"text": null
},
{
"code": null,
"e": 4540,
"s": 4532,
"text": "Output:"
},
{
"code": null,
"e": 4564,
"s": 4540,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 4581,
"s": 4564,
"text": "Machine Learning"
},
{
"code": null,
"e": 4588,
"s": 4581,
"text": "Python"
},
{
"code": null,
"e": 4605,
"s": 4588,
"text": "Machine Learning"
}
] |
Public vs Private Access Modifiers in Java
|
22 Feb, 2021
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members.
Public Access Modifiers :
If a class is declared as public then we can access that class from anywhere.
In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B main method we create an object of type class A and trying to access the data of method m1.
Java
// Java program to showcase the example// of public access modifier // import required packagesimport java.io.*;import java.util.*; // declaring a public classpublic class A { // declaring method m1 public void m1() { System.out.println("GFG"); }} class B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }}
GFG
If class A is not public while compiling B class we will get compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package.
Similarly, if a member or method or interface is declared as public then we can access that member from anywhere.
Private Access Modifiers:
This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructor, methods, and fields inside the classes.
If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can’t access them.
Java
// Java program to showcase the example// of private access modifier // import required packagesimport java.io.*; import java.util.*; // helper classclass A { // helper method private void m1() { System.out.println("GFG"); }} // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }}
Java-Modifier
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 502,
"s": 53,
"text": "Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members."
},
{
"code": null,
"e": 528,
"s": 502,
"text": "Public Access Modifiers :"
},
{
"code": null,
"e": 606,
"s": 528,
"text": "If a class is declared as public then we can access that class from anywhere."
},
{
"code": null,
"e": 987,
"s": 606,
"text": "In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B main method we create an object of type class A and trying to access the data of method m1."
},
{
"code": null,
"e": 992,
"s": 987,
"text": "Java"
},
{
"code": "// Java program to showcase the example// of public access modifier // import required packagesimport java.io.*;import java.util.*; // declaring a public classpublic class A { // declaring method m1 public void m1() { System.out.println(\"GFG\"); }} class B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }}",
"e": 1462,
"s": 992,
"text": null
},
{
"code": null,
"e": 1467,
"s": 1462,
"text": "GFG\n"
},
{
"code": null,
"e": 1634,
"s": 1467,
"text": "If class A is not public while compiling B class we will get compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package."
},
{
"code": null,
"e": 1748,
"s": 1634,
"text": "Similarly, if a member or method or interface is declared as public then we can access that member from anywhere."
},
{
"code": null,
"e": 1774,
"s": 1748,
"text": "Private Access Modifiers:"
},
{
"code": null,
"e": 1922,
"s": 1774,
"text": "This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructor, methods, and fields inside the classes. "
},
{
"code": null,
"e": 2085,
"s": 1922,
"text": "If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can’t access them."
},
{
"code": null,
"e": 2090,
"s": 2085,
"text": "Java"
},
{
"code": "// Java program to showcase the example// of private access modifier // import required packagesimport java.io.*; import java.util.*; // helper classclass A { // helper method private void m1() { System.out.println(\"GFG\"); }} // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }}",
"e": 2556,
"s": 2090,
"text": null
},
{
"code": null,
"e": 2570,
"s": 2556,
"text": "Java-Modifier"
},
{
"code": null,
"e": 2577,
"s": 2570,
"text": "Picked"
},
{
"code": null,
"e": 2601,
"s": 2577,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2620,
"s": 2601,
"text": "Difference Between"
},
{
"code": null,
"e": 2625,
"s": 2620,
"text": "Java"
},
{
"code": null,
"e": 2644,
"s": 2625,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2649,
"s": 2644,
"text": "Java"
}
] |
Perl | Useful String functions
|
30 Jun, 2019
A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“).
Perl provides various functions to manipulate the string like any other programming language.Example:
# Perl program to demonstrate # string length function # string my $s = "geeksforgeeks"; # using length function & # displaying length print("Length: ", length($s)); # Converting to Uppercaseprint("\nTo Upper Case: "); print(uc($s), "\n");
Length: 13
To Upper Case: GEEKSFORGEEKS
Some string functions of Perl are as follows:
Perl-function
Perl-String
Perl-String-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Use of print() and say() in Perl
Hello World Program in Perl
Perl | ne operator
Perl | Basic Syntax of a Perl Program
Perl | eq operator
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 317,
"s": 28,
"text": "A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“)."
},
{
"code": null,
"e": 419,
"s": 317,
"text": "Perl provides various functions to manipulate the string like any other programming language.Example:"
},
{
"code": "# Perl program to demonstrate # string length function # string my $s = \"geeksforgeeks\"; # using length function & # displaying length print(\"Length: \", length($s)); # Converting to Uppercaseprint(\"\\nTo Upper Case: \"); print(uc($s), \"\\n\"); ",
"e": 672,
"s": 419,
"text": null
},
{
"code": null,
"e": 713,
"s": 672,
"text": "Length: 13\nTo Upper Case: GEEKSFORGEEKS\n"
},
{
"code": null,
"e": 759,
"s": 713,
"text": "Some string functions of Perl are as follows:"
},
{
"code": null,
"e": 773,
"s": 759,
"text": "Perl-function"
},
{
"code": null,
"e": 785,
"s": 773,
"text": "Perl-String"
},
{
"code": null,
"e": 807,
"s": 785,
"text": "Perl-String-Functions"
},
{
"code": null,
"e": 812,
"s": 807,
"text": "Perl"
},
{
"code": null,
"e": 817,
"s": 812,
"text": "Perl"
},
{
"code": null,
"e": 915,
"s": 817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 929,
"s": 915,
"text": "Perl | Arrays"
},
{
"code": null,
"e": 970,
"s": 929,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 992,
"s": 970,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 1017,
"s": 992,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 1049,
"s": 1017,
"text": "Perl | Subroutines or Functions"
},
{
"code": null,
"e": 1082,
"s": 1049,
"text": "Use of print() and say() in Perl"
},
{
"code": null,
"e": 1110,
"s": 1082,
"text": "Hello World Program in Perl"
},
{
"code": null,
"e": 1129,
"s": 1110,
"text": "Perl | ne operator"
},
{
"code": null,
"e": 1167,
"s": 1129,
"text": "Perl | Basic Syntax of a Perl Program"
}
] |
How can we implement cut, copy and paste functionality of JTextField in Java?
|
A JTextField is a subclass of JTextComponent class that allows the editing of a single line of text. We can implement the functionality of cut, copy and paste in a JTextField component by using cut(), copy() and paste() methods. These are pre-defined methods in a JTextFeild class.
public void cut()
public void copy()
public void paste()
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JTextFieldCutCopyPasteTest extends JFrame {
private JTextField textField;
private JButton cutButton, copyButton, pasteButton;
public JTextFieldCutCopyPasteTest() {
setTitle("JTextField CutCopyPaste Test");
setLayout(new FlowLayout());
textField = new JTextField(12);
cutButton = new JButton("Cut");
pasteButton = new JButton("Paste");
copyButton = new JButton("Copy");
cutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
textField.cut();
}
});
copyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
textField.copy();
}
});
pasteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
textField.paste();
}
});
textField.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
System.out.println("All text: " + textField.getText());
if (textField.getSelectedText() != null)
System.out.println("Selected text: " + textField.getSelectedText());
else
System.out.println("Selected text: ");
}
});
add(textField);
add(cutButton);
add(copyButton);
add(pasteButton);
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new JTextFieldCutCopyPasteTest();
}
}
|
[
{
"code": null,
"e": 1469,
"s": 1187,
"text": "A JTextField is a subclass of JTextComponent class that allows the editing of a single line of text. We can implement the functionality of cut, copy and paste in a JTextField component by using cut(), copy() and paste() methods. These are pre-defined methods in a JTextFeild class."
},
{
"code": null,
"e": 1526,
"s": 1469,
"text": "public void cut()\npublic void copy()\npublic void paste()"
},
{
"code": null,
"e": 3259,
"s": 1526,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\npublic class JTextFieldCutCopyPasteTest extends JFrame {\n private JTextField textField;\n private JButton cutButton, copyButton, pasteButton;\n public JTextFieldCutCopyPasteTest() {\n setTitle(\"JTextField CutCopyPaste Test\");\n setLayout(new FlowLayout());\n textField = new JTextField(12);\n cutButton = new JButton(\"Cut\");\n pasteButton = new JButton(\"Paste\");\n copyButton = new JButton(\"Copy\");\n cutButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n textField.cut();\n }\n });\n copyButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n textField.copy();\n }\n });\n pasteButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent le) {\n textField.paste();\n }\n });\n textField.addCaretListener(new CaretListener() {\n public void caretUpdate(CaretEvent ce) {\n System.out.println(\"All text: \" + textField.getText());\n if (textField.getSelectedText() != null)\n System.out.println(\"Selected text: \" + textField.getSelectedText());\n else\n System.out.println(\"Selected text: \");\n }\n });\n add(textField);\n add(cutButton);\n add(copyButton);\n add(pasteButton);\n setSize(375, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String args[]) {\n new JTextFieldCutCopyPasteTest();\n }\n}"
}
] |
Python | Convert a list of characters into a string
|
28 Jun, 2022
Given a list of characters, merge all of them into a string. Examples:
Input : ['g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's']
Output : geeksforgeeks
Input : ['p', 'r', 'o', 'g', 'r', 'a', 'm',
'm', 'i', 'n', 'g']
Output : programming
Method 1 : Traversal of list
Initialize an empty string at the beginning. Traverse in the list of characters, for every index add character to the initial string. After complete traversal, print the string which has been added with every character.
Python
# Python program to convert a list# of character def convert(s): # initialization of string to "" new = "" # traverse in the string for x in s: new += x # return string return new # driver codes = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(convert(s))
Output:
geeksforgeeks
Time Complexity: O(n)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Auxiliary Space: O(n)
Method 2 : Using join() function
By using join() function in python, all characters in the list can be joined. The syntax is:
str = ""
str1 = ( "geeks", "for", "geeks" )
str.join(str1)
The list of characters can be joined easily by initializing str=”” so that there are no spaces in between.
Python
# Python program to convert a list# of character def convert(s): # initialization of string to "" str1 = "" # using join function join the list s by # separating words by str1 return(str1.join(s)) # driver codes = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(convert(s))
Output:
geeksforgeeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#3: Using reduce() function
Reduce function is used to convert the iterables to reduce in a single cumulative value.
Python3
# Python program to convert a list# of characterimport functools def convert(s): # Using reduce to jion the list s to string str1 = functools.reduce(lambda x,y : x+y, s) # Return string 1 return str1 # driver codes = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(convert(s))
Output:
geeksforgeeks
Convert a list of characters into a string in Python | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersConvert a list of characters into a string in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=MsFdb1r8ytQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
nidhi_biet
riya55
satyam00so
Python list-programs
Python string-programs
python-list
python-string
Python
Strings
python-list
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 123,
"s": 52,
"text": "Given a list of characters, merge all of them into a string. Examples:"
},
{
"code": null,
"e": 347,
"s": 123,
"text": "Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', \n 'r', 'g', 'e', 'e', 'k', 's']\nOutput : geeksforgeeks \n\nInput : ['p', 'r', 'o', 'g', 'r', 'a', 'm', \n 'm', 'i', 'n', 'g']\nOutput : programming "
},
{
"code": null,
"e": 376,
"s": 347,
"text": "Method 1 : Traversal of list"
},
{
"code": null,
"e": 597,
"s": 376,
"text": "Initialize an empty string at the beginning. Traverse in the list of characters, for every index add character to the initial string. After complete traversal, print the string which has been added with every character. "
},
{
"code": null,
"e": 604,
"s": 597,
"text": "Python"
},
{
"code": "# Python program to convert a list# of character def convert(s): # initialization of string to \"\" new = \"\" # traverse in the string for x in s: new += x # return string return new # driver codes = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(convert(s))",
"e": 921,
"s": 604,
"text": null
},
{
"code": null,
"e": 929,
"s": 921,
"text": "Output:"
},
{
"code": null,
"e": 943,
"s": 929,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 965,
"s": 943,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 974,
"s": 965,
"text": "Chapters"
},
{
"code": null,
"e": 1001,
"s": 974,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1051,
"s": 1001,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1074,
"s": 1051,
"text": "captions off, selected"
},
{
"code": null,
"e": 1082,
"s": 1074,
"text": "English"
},
{
"code": null,
"e": 1106,
"s": 1082,
"text": "This is a modal window."
},
{
"code": null,
"e": 1175,
"s": 1106,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1197,
"s": 1175,
"text": "End of dialog window."
},
{
"code": null,
"e": 1219,
"s": 1197,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1252,
"s": 1219,
"text": "Method 2 : Using join() function"
},
{
"code": null,
"e": 1345,
"s": 1252,
"text": "By using join() function in python, all characters in the list can be joined. The syntax is:"
},
{
"code": null,
"e": 1405,
"s": 1345,
"text": "str = \"\"\nstr1 = ( \"geeks\", \"for\", \"geeks\" )\nstr.join(str1) "
},
{
"code": null,
"e": 1513,
"s": 1405,
"text": "The list of characters can be joined easily by initializing str=”” so that there are no spaces in between. "
},
{
"code": null,
"e": 1520,
"s": 1513,
"text": "Python"
},
{
"code": "# Python program to convert a list# of character def convert(s): # initialization of string to \"\" str1 = \"\" # using join function join the list s by # separating words by str1 return(str1.join(s)) # driver codes = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(convert(s))",
"e": 1838,
"s": 1520,
"text": null
},
{
"code": null,
"e": 1846,
"s": 1838,
"text": "Output:"
},
{
"code": null,
"e": 1860,
"s": 1846,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 1882,
"s": 1860,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 1904,
"s": 1882,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 2048,
"s": 1904,
"text": " Method#3: Using reduce() function"
},
{
"code": null,
"e": 2138,
"s": 2048,
"text": "Reduce function is used to convert the iterables to reduce in a single cumulative value. "
},
{
"code": null,
"e": 2146,
"s": 2138,
"text": "Python3"
},
{
"code": "# Python program to convert a list# of characterimport functools def convert(s): # Using reduce to jion the list s to string str1 = functools.reduce(lambda x,y : x+y, s) # Return string 1 return str1 # driver codes = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(convert(s))",
"e": 2464,
"s": 2146,
"text": null
},
{
"code": null,
"e": 2472,
"s": 2464,
"text": "Output:"
},
{
"code": null,
"e": 2486,
"s": 2472,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 3408,
"s": 2486,
"text": "Convert a list of characters into a string in Python | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersConvert a list of characters into a string in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=MsFdb1r8ytQ\" 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": 3419,
"s": 3408,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3426,
"s": 3419,
"text": "riya55"
},
{
"code": null,
"e": 3437,
"s": 3426,
"text": "satyam00so"
},
{
"code": null,
"e": 3458,
"s": 3437,
"text": "Python list-programs"
},
{
"code": null,
"e": 3481,
"s": 3458,
"text": "Python string-programs"
},
{
"code": null,
"e": 3493,
"s": 3481,
"text": "python-list"
},
{
"code": null,
"e": 3507,
"s": 3493,
"text": "python-string"
},
{
"code": null,
"e": 3514,
"s": 3507,
"text": "Python"
},
{
"code": null,
"e": 3522,
"s": 3514,
"text": "Strings"
},
{
"code": null,
"e": 3534,
"s": 3522,
"text": "python-list"
},
{
"code": null,
"e": 3542,
"s": 3534,
"text": "Strings"
}
] |
Node.js fs.stat() Method
|
12 Oct, 2021
The fs.stat() method is used to return information about the given file or directory. It returns an fs.Stat object which has several properties and methods to get details about the file or directory.
Syntax:
fs.stat( path, options, callback )
Parameters: This method accept three parameters as mentioned above and described below:
path: It holds the path of the file or directory that has to be checked. It can be a String, Buffer or URL.
options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false.
bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false.
callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the methodstats: It is the Stats object that contains the details of the file path.
err: It is an error that would be thrown if the method
stats: It is the Stats object that contains the details of the file path.
Below examples illustrate the fs.stat() method in Node.js:
Example 1: This example uses fs.stat() method to get the details of the path.
// Node.js program to demonstrate the// fs.stat() method // Import the filesystem moduleconst fs = require('fs'); // Getting information for a filefs.stat("example_file.txt", (error, stats) => { if (error) { console.log(error); } else { console.log("Stats object for: example_file.txt"); console.log(stats); // Using methods of the Stats object console.log("Path is file:", stats.isFile()); console.log("Path is directory:", stats.isDirectory()); }}); // Getting information for a directoryfs.stat("example_directory.txt", (error, stats) => { if (error) { console.log(error); } else { console.log("Stats object for: example_directory.txt"); console.log(stats); // Using methods of the Stats object console.log("Path is file:", stats.isFile()); console.log("Path is directory:", stats.isDirectory()); }});
Output:
Stats object for: example_file.txt
Stats {
dev: 2269,
mode: 33188,
nlink: 1,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: 271,
size: 0,
blocks: 0,
atimeMs: 1582871562365.894,
mtimeMs: 1582871556897.5554,
ctimeMs: 1582871556897.5554,
birthtimeMs: 1582871556897.5554,
atime: 2020-02-28T06:32:42.366Z,
mtime: 2020-02-28T06:32:36.898Z,
ctime: 2020-02-28T06:32:36.898Z,
birthtime: 2020-02-28T06:32:36.898Z }
Path is file: true
Path is directory: false
Stats object for: example_directory.txt
Stats {
dev: 2269,
mode: 33188,
nlink: 1,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: 270,
size: 0,
blocks: 0,
atimeMs: 1582871562357.8936,
mtimeMs: 1582871553413.3396,
ctimeMs: 1582871553417.3398,
birthtimeMs: 1582871553413.3396,
atime: 2020-02-28T06:32:42.358Z,
mtime: 2020-02-28T06:32:33.413Z,
ctime: 2020-02-28T06:32:33.417Z,
birthtime: 2020-02-28T06:32:33.413Z }
Path is file: true
Path is directory: false
Example 2: This example uses fs.stat() method to get the details of files with the bigint option.
// Node.js program to demonstrate the// fs.stat() method // Import the filesystem moduleconst fs = require('fs'); fs.stat("example_file.txt", (error, stats) => { console.log(stats);}); // Using the bigint option to return// the values in big integer formatfs.stat("example_file.txt", { bigint: true }, (error, stats) => { console.log(stats);});
Output:
Stats {
dev: 2269,
mode: 33188,
nlink: 1,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: 271,
size: 0,
blocks: 0,
atimeMs: 1582871562365.894,
mtimeMs: 1582871556897.5554,
ctimeMs: 1582871556897.5554,
birthtimeMs: 1582871556897.5554,
atime: 2020-02-28T06:32:42.366Z,
mtime: 2020-02-28T06:32:36.898Z,
ctime: 2020-02-28T06:32:36.898Z,
birthtime: 2020-02-28T06:32:36.898Z }
Stats {
dev: 2269n,
mode: 33188n,
nlink: 1n,
uid: 1000n,
gid: 1000n,
rdev: 0n,
blksize: 4096n,
ino: 271n,
size: 0n,
blocks: 0n,
atimeMs: 1582871562365n,
mtimeMs: 1582871556897n,
ctimeMs: 1582871556897n,
birthtimeMs: 1582871556897n,
atime: 2020-02-28T06:32:42.365Z,
mtime: 2020-02-28T06:32:36.897Z,
ctime: 2020-02-28T06:32:36.897Z,
birthtime: 2020-02-28T06:32:36.897Z }
Reference: https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 228,
"s": 28,
"text": "The fs.stat() method is used to return information about the given file or directory. It returns an fs.Stat object which has several properties and methods to get details about the file or directory."
},
{
"code": null,
"e": 236,
"s": 228,
"text": "Syntax:"
},
{
"code": null,
"e": 271,
"s": 236,
"text": "fs.stat( path, options, callback )"
},
{
"code": null,
"e": 359,
"s": 271,
"text": "Parameters: This method accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 467,
"s": 359,
"text": "path: It holds the path of the file or directory that has to be checked. It can be a String, Buffer or URL."
},
{
"code": null,
"e": 739,
"s": 467,
"text": "options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false."
},
{
"code": null,
"e": 879,
"s": 739,
"text": "bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false."
},
{
"code": null,
"e": 1085,
"s": 879,
"text": "callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the methodstats: It is the Stats object that contains the details of the file path."
},
{
"code": null,
"e": 1140,
"s": 1085,
"text": "err: It is an error that would be thrown if the method"
},
{
"code": null,
"e": 1214,
"s": 1140,
"text": "stats: It is the Stats object that contains the details of the file path."
},
{
"code": null,
"e": 1273,
"s": 1214,
"text": "Below examples illustrate the fs.stat() method in Node.js:"
},
{
"code": null,
"e": 1351,
"s": 1273,
"text": "Example 1: This example uses fs.stat() method to get the details of the path."
},
{
"code": "// Node.js program to demonstrate the// fs.stat() method // Import the filesystem moduleconst fs = require('fs'); // Getting information for a filefs.stat(\"example_file.txt\", (error, stats) => { if (error) { console.log(error); } else { console.log(\"Stats object for: example_file.txt\"); console.log(stats); // Using methods of the Stats object console.log(\"Path is file:\", stats.isFile()); console.log(\"Path is directory:\", stats.isDirectory()); }}); // Getting information for a directoryfs.stat(\"example_directory.txt\", (error, stats) => { if (error) { console.log(error); } else { console.log(\"Stats object for: example_directory.txt\"); console.log(stats); // Using methods of the Stats object console.log(\"Path is file:\", stats.isFile()); console.log(\"Path is directory:\", stats.isDirectory()); }});",
"e": 2207,
"s": 1351,
"text": null
},
{
"code": null,
"e": 2215,
"s": 2207,
"text": "Output:"
},
{
"code": null,
"e": 3199,
"s": 2215,
"text": "Stats object for: example_file.txt\nStats {\n dev: 2269,\n mode: 33188,\n nlink: 1,\n uid: 1000,\n gid: 1000,\n rdev: 0,\n blksize: 4096,\n ino: 271,\n size: 0,\n blocks: 0,\n atimeMs: 1582871562365.894,\n mtimeMs: 1582871556897.5554,\n ctimeMs: 1582871556897.5554,\n birthtimeMs: 1582871556897.5554,\n atime: 2020-02-28T06:32:42.366Z,\n mtime: 2020-02-28T06:32:36.898Z,\n ctime: 2020-02-28T06:32:36.898Z,\n birthtime: 2020-02-28T06:32:36.898Z }\nPath is file: true\nPath is directory: false\nStats object for: example_directory.txt\nStats {\n dev: 2269,\n mode: 33188,\n nlink: 1,\n uid: 1000,\n gid: 1000,\n rdev: 0,\n blksize: 4096,\n ino: 270,\n size: 0,\n blocks: 0,\n atimeMs: 1582871562357.8936,\n mtimeMs: 1582871553413.3396,\n ctimeMs: 1582871553417.3398,\n birthtimeMs: 1582871553413.3396,\n atime: 2020-02-28T06:32:42.358Z,\n mtime: 2020-02-28T06:32:33.413Z,\n ctime: 2020-02-28T06:32:33.417Z,\n birthtime: 2020-02-28T06:32:33.413Z }\nPath is file: true\nPath is directory: false"
},
{
"code": null,
"e": 3297,
"s": 3199,
"text": "Example 2: This example uses fs.stat() method to get the details of files with the bigint option."
},
{
"code": "// Node.js program to demonstrate the// fs.stat() method // Import the filesystem moduleconst fs = require('fs'); fs.stat(\"example_file.txt\", (error, stats) => { console.log(stats);}); // Using the bigint option to return// the values in big integer formatfs.stat(\"example_file.txt\", { bigint: true }, (error, stats) => { console.log(stats);});",
"e": 3647,
"s": 3297,
"text": null
},
{
"code": null,
"e": 3655,
"s": 3647,
"text": "Output:"
},
{
"code": null,
"e": 4470,
"s": 3655,
"text": "Stats {\n dev: 2269,\n mode: 33188,\n nlink: 1,\n uid: 1000,\n gid: 1000,\n rdev: 0,\n blksize: 4096,\n ino: 271,\n size: 0,\n blocks: 0,\n atimeMs: 1582871562365.894,\n mtimeMs: 1582871556897.5554,\n ctimeMs: 1582871556897.5554,\n birthtimeMs: 1582871556897.5554,\n atime: 2020-02-28T06:32:42.366Z,\n mtime: 2020-02-28T06:32:36.898Z,\n ctime: 2020-02-28T06:32:36.898Z,\n birthtime: 2020-02-28T06:32:36.898Z }\nStats {\n dev: 2269n,\n mode: 33188n,\n nlink: 1n,\n uid: 1000n,\n gid: 1000n,\n rdev: 0n,\n blksize: 4096n,\n ino: 271n,\n size: 0n,\n blocks: 0n,\n atimeMs: 1582871562365n,\n mtimeMs: 1582871556897n,\n ctimeMs: 1582871556897n,\n birthtimeMs: 1582871556897n,\n atime: 2020-02-28T06:32:42.365Z,\n mtime: 2020-02-28T06:32:36.897Z,\n ctime: 2020-02-28T06:32:36.897Z,\n birthtime: 2020-02-28T06:32:36.897Z }"
},
{
"code": null,
"e": 4545,
"s": 4470,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback"
},
{
"code": null,
"e": 4563,
"s": 4545,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 4570,
"s": 4563,
"text": "Picked"
},
{
"code": null,
"e": 4578,
"s": 4570,
"text": "Node.js"
},
{
"code": null,
"e": 4595,
"s": 4578,
"text": "Web Technologies"
},
{
"code": null,
"e": 4693,
"s": 4595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4741,
"s": 4693,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4774,
"s": 4741,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 4804,
"s": 4774,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 4824,
"s": 4804,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 4878,
"s": 4824,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 4940,
"s": 4878,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5001,
"s": 4940,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5051,
"s": 5001,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5094,
"s": 5051,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python – Generate k random dates between two other dates
|
03 Aug, 2021
Given two dates, the task is to write a Python program to get K dates randomly.
Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1), K = 7
Output : [datetime.date(2015, 6, 18), datetime.date(2015, 6, 25), datetime.date(2015, 6, 29), datetime.date(2015, 6, 11), datetime.date(2015, 6, 11), datetime.date(2015, 6, 10), datetime.date(2015, 6, 24)]
Explanation : 7 random dates starting from 3 June 2015 to 1 July 2015 are generated.
Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 8, 1), K = 6
Output : [datetime.date(2015, 6, 20), datetime.date(2015, 7, 22), datetime.date(2015, 6, 29), datetime.date(2015, 6, 18), datetime.date(2015, 6, 13), datetime.date(2015, 7, 14)]
Explanation : 6 random dates starting from 3 June 2015 to 1 August 2015 are generated.
Method #1 : Using choices() + loop + timedelta()
In this, we extract all dates in range using loop and timedelta() of 1-day difference. Among them K random dates are chosen using choices().
Python3
# Python3 code to demonstrate working of# Random K dates in Range# Using choices() + timedelta() + loopfrom datetime import date, timedeltafrom random import choices # initializing dates ranges test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1) # printing dates print("The original range : " + str(test_date1) + " " + str(test_date2)) # initializing KK = 7 res_dates = [test_date1] # loop to get each date till end datewhile test_date1 != test_date2: test_date1 += timedelta(days=1) res_dates.append(test_date1) # random K dates from packres = choices(res_dates, k=K) # printing print("K random dates in range : " + str(res))
Output:
The original range : 2015-06-03 2015-07-01
K random dates in range : [datetime.date(2015, 6, 25), datetime.date(2015, 6, 10), datetime.date(2015, 6, 18), datetime.date(2015, 6, 7), datetime.date(2015, 6, 4), datetime.date(2015, 6, 16), datetime.date(2015, 6, 12)]
Method #2 : Using randrange() + timedelta() + loop
In this, a total number of days between ranges is extracted and that range is used to get elements K times, adding a random index number from start date extracted using randrange().
Python3
# Python3 code to demonstrate working of# Random K dates in Range# Using randrange() + timedelta() + loopfrom datetime import date, timedeltaimport random # initializing dates ranges test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1) # printing dates print("The original range : " + str(test_date1) + " " + str(test_date2)) # initializing KK = 7 # getting days between datesdates_bet = test_date2 - test_date1total_days = dates_bet.days res = []for idx in range(K): random.seed(a=None) # getting random days randay = random.randrange(total_days) # getting random dates res.append(test_date1 + timedelta(days=randay)) # printing print("K random dates in range : " + str(res))
Output:
The original range : 2015-06-03 2015-07-01
K random dates in range : [datetime.date(2015, 6, 26), datetime.date(2015, 6, 5), datetime.date(2015, 6, 6), datetime.date(2015, 6, 18), datetime.date(2015, 6, 21), datetime.date(2015, 6, 15), datetime.date(2015, 6, 12)]
Python datetime-program
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": "\n03 Aug, 2021"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "Given two dates, the task is to write a Python program to get K dates randomly."
},
{
"code": null,
"e": 183,
"s": 108,
"text": "Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1), K = 7"
},
{
"code": null,
"e": 389,
"s": 183,
"text": "Output : [datetime.date(2015, 6, 18), datetime.date(2015, 6, 25), datetime.date(2015, 6, 29), datetime.date(2015, 6, 11), datetime.date(2015, 6, 11), datetime.date(2015, 6, 10), datetime.date(2015, 6, 24)]"
},
{
"code": null,
"e": 474,
"s": 389,
"text": "Explanation : 7 random dates starting from 3 June 2015 to 1 July 2015 are generated."
},
{
"code": null,
"e": 549,
"s": 474,
"text": "Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 8, 1), K = 6"
},
{
"code": null,
"e": 727,
"s": 549,
"text": "Output : [datetime.date(2015, 6, 20), datetime.date(2015, 7, 22), datetime.date(2015, 6, 29), datetime.date(2015, 6, 18), datetime.date(2015, 6, 13), datetime.date(2015, 7, 14)]"
},
{
"code": null,
"e": 814,
"s": 727,
"text": "Explanation : 6 random dates starting from 3 June 2015 to 1 August 2015 are generated."
},
{
"code": null,
"e": 863,
"s": 814,
"text": "Method #1 : Using choices() + loop + timedelta()"
},
{
"code": null,
"e": 1004,
"s": 863,
"text": "In this, we extract all dates in range using loop and timedelta() of 1-day difference. Among them K random dates are chosen using choices()."
},
{
"code": null,
"e": 1012,
"s": 1004,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Random K dates in Range# Using choices() + timedelta() + loopfrom datetime import date, timedeltafrom random import choices # initializing dates ranges test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1) # printing dates print(\"The original range : \" + str(test_date1) + \" \" + str(test_date2)) # initializing KK = 7 res_dates = [test_date1] # loop to get each date till end datewhile test_date1 != test_date2: test_date1 += timedelta(days=1) res_dates.append(test_date1) # random K dates from packres = choices(res_dates, k=K) # printing print(\"K random dates in range : \" + str(res))",
"e": 1660,
"s": 1012,
"text": null
},
{
"code": null,
"e": 1668,
"s": 1660,
"text": "Output:"
},
{
"code": null,
"e": 1711,
"s": 1668,
"text": "The original range : 2015-06-03 2015-07-01"
},
{
"code": null,
"e": 1932,
"s": 1711,
"text": "K random dates in range : [datetime.date(2015, 6, 25), datetime.date(2015, 6, 10), datetime.date(2015, 6, 18), datetime.date(2015, 6, 7), datetime.date(2015, 6, 4), datetime.date(2015, 6, 16), datetime.date(2015, 6, 12)]"
},
{
"code": null,
"e": 1983,
"s": 1932,
"text": "Method #2 : Using randrange() + timedelta() + loop"
},
{
"code": null,
"e": 2165,
"s": 1983,
"text": "In this, a total number of days between ranges is extracted and that range is used to get elements K times, adding a random index number from start date extracted using randrange()."
},
{
"code": null,
"e": 2173,
"s": 2165,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Random K dates in Range# Using randrange() + timedelta() + loopfrom datetime import date, timedeltaimport random # initializing dates ranges test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1) # printing dates print(\"The original range : \" + str(test_date1) + \" \" + str(test_date2)) # initializing KK = 7 # getting days between datesdates_bet = test_date2 - test_date1total_days = dates_bet.days res = []for idx in range(K): random.seed(a=None) # getting random days randay = random.randrange(total_days) # getting random dates res.append(test_date1 + timedelta(days=randay)) # printing print(\"K random dates in range : \" + str(res))",
"e": 2891,
"s": 2173,
"text": null
},
{
"code": null,
"e": 2899,
"s": 2891,
"text": "Output:"
},
{
"code": null,
"e": 2942,
"s": 2899,
"text": "The original range : 2015-06-03 2015-07-01"
},
{
"code": null,
"e": 3163,
"s": 2942,
"text": "K random dates in range : [datetime.date(2015, 6, 26), datetime.date(2015, 6, 5), datetime.date(2015, 6, 6), datetime.date(2015, 6, 18), datetime.date(2015, 6, 21), datetime.date(2015, 6, 15), datetime.date(2015, 6, 12)]"
},
{
"code": null,
"e": 3187,
"s": 3163,
"text": "Python datetime-program"
},
{
"code": null,
"e": 3194,
"s": 3187,
"text": "Python"
},
{
"code": null,
"e": 3210,
"s": 3194,
"text": "Python Programs"
}
] |
Runtime Type Identification in Java
|
22 Feb, 2021
Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.lang. Unlike C++ Java does not support Runtime Type Identification (RTTI) but it provides few methods to find objects at runtime.
Some essential points regarding Runtime Type Identification in Java are following:
Determining the type of object at run time not only reduces error but also results in robustness.
It is also useful before typecasting any object into another type to avoid run time exception.
It is used to implement the type-specific feature on methods that accept types like objects or any interfaces.
The java.lang.Object.getClass() method is used to determine the type of object at run time.
Syntax:
public final Class getClass()
Return Type: Returns the Class objects that represent the runtime class of this object.
Example 1:
Java
// Java Program to determine Runtime type import java.io.*; public class Example1 { public static void main(String[] args) { // Creating the obj Object obj = new String("Learn_programming"); Class abc = obj.getClass(); // Print the class of obj System.out.println("Class of Object obj is : " + abc.getName()); }}
Class of Object obj is : java.lang.String
Example 2:
Java
// Java program to determine object class at run time import java.io.*; public class Example2 { public static void main(String[] args) { // create a new Integer Integer num = new Integer(100); // print num System.out.println("" + num); // print the class of num System.out.println("" + num.getClass()); } }
Output:
100
class java.lang.Integer
Picked
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": "\n22 Feb, 2021"
},
{
"code": null,
"e": 385,
"s": 54,
"text": "Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.lang. Unlike C++ Java does not support Runtime Type Identification (RTTI) but it provides few methods to find objects at runtime."
},
{
"code": null,
"e": 468,
"s": 385,
"text": "Some essential points regarding Runtime Type Identification in Java are following:"
},
{
"code": null,
"e": 566,
"s": 468,
"text": "Determining the type of object at run time not only reduces error but also results in robustness."
},
{
"code": null,
"e": 661,
"s": 566,
"text": "It is also useful before typecasting any object into another type to avoid run time exception."
},
{
"code": null,
"e": 772,
"s": 661,
"text": "It is used to implement the type-specific feature on methods that accept types like objects or any interfaces."
},
{
"code": null,
"e": 864,
"s": 772,
"text": "The java.lang.Object.getClass() method is used to determine the type of object at run time."
},
{
"code": null,
"e": 872,
"s": 864,
"text": "Syntax:"
},
{
"code": null,
"e": 902,
"s": 872,
"text": "public final Class getClass()"
},
{
"code": null,
"e": 990,
"s": 902,
"text": "Return Type: Returns the Class objects that represent the runtime class of this object."
},
{
"code": null,
"e": 1001,
"s": 990,
"text": "Example 1:"
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "Java"
},
{
"code": "// Java Program to determine Runtime type import java.io.*; public class Example1 { public static void main(String[] args) { // Creating the obj Object obj = new String(\"Learn_programming\"); Class abc = obj.getClass(); // Print the class of obj System.out.println(\"Class of Object obj is : \" + abc.getName()); }}",
"e": 1395,
"s": 1006,
"text": null
},
{
"code": null,
"e": 1438,
"s": 1395,
"text": "Class of Object obj is : java.lang.String\n"
},
{
"code": null,
"e": 1449,
"s": 1438,
"text": "Example 2:"
},
{
"code": null,
"e": 1454,
"s": 1449,
"text": "Java"
},
{
"code": "// Java program to determine object class at run time import java.io.*; public class Example2 { public static void main(String[] args) { // create a new Integer Integer num = new Integer(100); // print num System.out.println(\"\" + num); // print the class of num System.out.println(\"\" + num.getClass()); } } ",
"e": 1822,
"s": 1454,
"text": null
},
{
"code": null,
"e": 1830,
"s": 1822,
"text": "Output:"
},
{
"code": null,
"e": 1858,
"s": 1830,
"text": "100\nclass java.lang.Integer"
},
{
"code": null,
"e": 1865,
"s": 1858,
"text": "Picked"
},
{
"code": null,
"e": 1870,
"s": 1865,
"text": "Java"
},
{
"code": null,
"e": 1875,
"s": 1870,
"text": "Java"
}
] |
Java Program to Increment by 1 to all the Digits of a given Integer
|
24 Nov, 2020
Given an integer, the task is to generate a Java Program to Increment by 1 All the Digits of a given Integer.
Examples:
Input: 12345
Output: 23456
Input: 110102
Output: 221213
Approach 1:
In this approach, we will create a number which will be of the same length as the input and will contain only 1 in it. Then we will add them.
Take the integer input.Find its length and then generate the number containing only 1 as digit of the length.Add both numbers.Print the result.
Take the integer input.
Find its length and then generate the number containing only 1 as digit of the length.
Add both numbers.
Print the result.
Java
// Java Program to Increment by 1 All the Digits of a given// Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main function public static void main(String[] args) { // Declaring the number int number = 110102; // Converting the number to String String string_num = Integer.toString(number); // Finding the length of the number int len = string_num.length(); // Declaring the empty string String add = ""; // Generating the addition string for (int i = 0; i < len; i++) { add = add.concat("1"); } // COnverting it to Integer int str_num = Integer.parseInt(add); // Adding them and displaying the result System.out.println(number + str_num); }}
221213
Approach 2:
In this approach, we will take an integer variable with value 1, we will multiply that variable with 10 and keep on adding the variable to the number till both of them have the same length.
Take the integer input.Add value 1 to the input.Multiply 1 with 10 and again add them.Keep on repeating step 2 and 3 till both of them have the same length.Print the result.
Take the integer input.
Add value 1 to the input.
Multiply 1 with 10 and again add them.
Keep on repeating step 2 and 3 till both of them have the same length.
Print the result.
Java
// Java Program to Increment by 1 All the Digits of a given// Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main function public static void main(String[] args) { // Declaring the number int number = 110102; // Declaring another variable with value 1 int add = 1; for (int i = 0; i < String.valueOf(number).length(); i++) { // Adding variable add and number number = number + add; // Multiplying value of the add with 10 add = add * 10; } // Printing result System.out.println(number); }}
221213
Time Complexity: O(l) where l is the length of an integer.
Space Complexity: O(1)
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "Given an integer, the task is to generate a Java Program to Increment by 1 All the Digits of a given Integer."
},
{
"code": null,
"e": 148,
"s": 138,
"text": "Examples:"
},
{
"code": null,
"e": 206,
"s": 148,
"text": "Input: 12345\nOutput: 23456\n\nInput: 110102\nOutput: 221213\n"
},
{
"code": null,
"e": 218,
"s": 206,
"text": "Approach 1:"
},
{
"code": null,
"e": 360,
"s": 218,
"text": "In this approach, we will create a number which will be of the same length as the input and will contain only 1 in it. Then we will add them."
},
{
"code": null,
"e": 504,
"s": 360,
"text": "Take the integer input.Find its length and then generate the number containing only 1 as digit of the length.Add both numbers.Print the result."
},
{
"code": null,
"e": 528,
"s": 504,
"text": "Take the integer input."
},
{
"code": null,
"e": 615,
"s": 528,
"text": "Find its length and then generate the number containing only 1 as digit of the length."
},
{
"code": null,
"e": 633,
"s": 615,
"text": "Add both numbers."
},
{
"code": null,
"e": 651,
"s": 633,
"text": "Print the result."
},
{
"code": null,
"e": 656,
"s": 651,
"text": "Java"
},
{
"code": "// Java Program to Increment by 1 All the Digits of a given// Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main function public static void main(String[] args) { // Declaring the number int number = 110102; // Converting the number to String String string_num = Integer.toString(number); // Finding the length of the number int len = string_num.length(); // Declaring the empty string String add = \"\"; // Generating the addition string for (int i = 0; i < len; i++) { add = add.concat(\"1\"); } // COnverting it to Integer int str_num = Integer.parseInt(add); // Adding them and displaying the result System.out.println(number + str_num); }}",
"e": 1475,
"s": 656,
"text": null
},
{
"code": null,
"e": 1483,
"s": 1475,
"text": "221213\n"
},
{
"code": null,
"e": 1495,
"s": 1483,
"text": "Approach 2:"
},
{
"code": null,
"e": 1685,
"s": 1495,
"text": "In this approach, we will take an integer variable with value 1, we will multiply that variable with 10 and keep on adding the variable to the number till both of them have the same length."
},
{
"code": null,
"e": 1859,
"s": 1685,
"text": "Take the integer input.Add value 1 to the input.Multiply 1 with 10 and again add them.Keep on repeating step 2 and 3 till both of them have the same length.Print the result."
},
{
"code": null,
"e": 1883,
"s": 1859,
"text": "Take the integer input."
},
{
"code": null,
"e": 1909,
"s": 1883,
"text": "Add value 1 to the input."
},
{
"code": null,
"e": 1948,
"s": 1909,
"text": "Multiply 1 with 10 and again add them."
},
{
"code": null,
"e": 2019,
"s": 1948,
"text": "Keep on repeating step 2 and 3 till both of them have the same length."
},
{
"code": null,
"e": 2037,
"s": 2019,
"text": "Print the result."
},
{
"code": null,
"e": 2042,
"s": 2037,
"text": "Java"
},
{
"code": "// Java Program to Increment by 1 All the Digits of a given// Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main function public static void main(String[] args) { // Declaring the number int number = 110102; // Declaring another variable with value 1 int add = 1; for (int i = 0; i < String.valueOf(number).length(); i++) { // Adding variable add and number number = number + add; // Multiplying value of the add with 10 add = add * 10; } // Printing result System.out.println(number); }}",
"e": 2698,
"s": 2042,
"text": null
},
{
"code": null,
"e": 2706,
"s": 2698,
"text": "221213\n"
},
{
"code": null,
"e": 2765,
"s": 2706,
"text": "Time Complexity: O(l) where l is the length of an integer."
},
{
"code": null,
"e": 2790,
"s": 2765,
"text": "Space Complexity: O(1) "
},
{
"code": null,
"e": 2795,
"s": 2790,
"text": "Java"
},
{
"code": null,
"e": 2809,
"s": 2795,
"text": "Java Programs"
},
{
"code": null,
"e": 2814,
"s": 2809,
"text": "Java"
},
{
"code": null,
"e": 2912,
"s": 2814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2927,
"s": 2912,
"text": "Stream In Java"
},
{
"code": null,
"e": 2948,
"s": 2927,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2969,
"s": 2948,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2988,
"s": 2969,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3005,
"s": 2988,
"text": "Generics in Java"
},
{
"code": null,
"e": 3031,
"s": 3005,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3065,
"s": 3031,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3112,
"s": 3065,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 3150,
"s": 3112,
"text": "Factory method design pattern in Java"
}
] |
Python Modules
|
07 Jun, 2022
A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.
Python3
# A simple module, calc.py def add(x, y): return (x+y) def subtract(x, y): return (x-y)
We can import the functions, classes defined in a module to another module using the import statement in some other Python source file.
Syntax:
import module
When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module. For example, to import the module calc.py, we need to put the following command at the top of the script.
Note: This does not import the functions or classes directly instead imports the module only. To access the functions inside the module the dot(.) operator is used.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Python3
# importing module calc.pyimport calc print(calc.add(10, 2))
Output:
12
Python’s from statement lets you import specific attributes from a module without importing the module as a whole.
Python3
# importing sqrt() and factorial from the# module mathfrom math import sqrt, factorial # if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(sqrt(16))print(factorial(6))
Output:
4.0
720
The * symbol used with the from import statement is used to import all the names from a module to a current namespace.
Syntax:
from module_name import *
The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the module, it is not recommended to use *, else do so.
Python3
# importing sqrt() and factorial from the# module mathfrom math import * # if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(sqrt(16))print(factorial(6))
4.0
720
Whenever a module is imported in Python the interpreter looks for several locations. First, it will check for the built-in module, if not found then it looks for a list of directories defined in the sys.path. Python interpreter searches for the module in the following manner –
First, it searches for the module in the current directory.
If the module isn’t found in the current directory, Python then searches each directory in the shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of directories.
If that also fails python checks the installation-dependent list of directories configured at the time Python is installed.
Python3
# importing sys moduleimport sys # importing sys.pathprint(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’, ‘/home/nikhil/.ipython’]
We can rename the module while importing it using the as keyword.
Python3
# importing sqrt() and factorial from the# module mathimport math as gfg # if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(gfg.sqrt(16))print(gfg.factorial(6))
4.0
720
The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables, and functions that are defined in a module.
Python3
# Import built-in module randomimport randomprint(dir(random))
Output:
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’, ‘TWOPI’, ‘_BuiltinMethodType’, ‘_MethodType’, ‘_Sequence’, ‘_Set’, ‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘_acos’, ‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_inst’, ‘_itertools’, ‘_log’, ‘_pi’, ‘_random’, ‘_sha512’, ‘_sin’, ‘_sqrt’, ‘_test’, ‘_test_generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’, ‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’, ‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]
Code Snippet illustrating python built-in modules:
Python3
# importing built-in module mathimport math # using square root(sqrt) function contained # in math moduleprint(math.sqrt(25)) # using pi function contained in math moduleprint(math.pi) # 2 radians = 114.59 degreesprint(math.degrees(2)) # 60 degrees = 1.04 radiansprint(math.radians(60)) # Sine of 2 radiansprint(math.sin(2)) # Cosine of 0.5 radiansprint(math.cos(0.5)) # Tangent of 0.23 radiansprint(math.tan(0.23)) # 1 * 2 * 3 * 4 = 24print(math.factorial(4)) # importing built in module randomimport random # printing random integer between 0 and 5print(random.randint(0, 5)) # print random floating point number between 0 and 1print(random.random()) # random number between 0 and 100print(random.random() * 100) List = [1, 4, True, 800, "python", 27, "hello"] # using choice function in random module for choosing # a random element from a set such as a listprint(random.choice(List)) # importing built in module datetimeimport datetimefrom datetime import dateimport time # Returns the number of seconds since the# Unix Epoch, January 1st 1970print(time.time()) # Converts a number of seconds to a date objectprint(date.fromtimestamp(454554))
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
My Personal Notes
arrow_drop_up
Save
fridayda13
RajuKumar19
nikhilaggarwal3
sagartomar9927
amartyaniel20
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 345,
"s": 52,
"text": "A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized."
},
{
"code": null,
"e": 353,
"s": 345,
"text": "Python3"
},
{
"code": "# A simple module, calc.py def add(x, y): return (x+y) def subtract(x, y): return (x-y)",
"e": 449,
"s": 353,
"text": null
},
{
"code": null,
"e": 586,
"s": 449,
"text": "We can import the functions, classes defined in a module to another module using the import statement in some other Python source file. "
},
{
"code": null,
"e": 594,
"s": 586,
"text": "Syntax:"
},
{
"code": null,
"e": 608,
"s": 594,
"text": "import module"
},
{
"code": null,
"e": 927,
"s": 608,
"text": "When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module. For example, to import the module calc.py, we need to put the following command at the top of the script."
},
{
"code": null,
"e": 1092,
"s": 927,
"text": "Note: This does not import the functions or classes directly instead imports the module only. To access the functions inside the module the dot(.) operator is used."
},
{
"code": null,
"e": 1101,
"s": 1092,
"text": "Chapters"
},
{
"code": null,
"e": 1128,
"s": 1101,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1178,
"s": 1128,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1201,
"s": 1178,
"text": "captions off, selected"
},
{
"code": null,
"e": 1209,
"s": 1201,
"text": "English"
},
{
"code": null,
"e": 1233,
"s": 1209,
"text": "This is a modal window."
},
{
"code": null,
"e": 1302,
"s": 1233,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1324,
"s": 1302,
"text": "End of dialog window."
},
{
"code": null,
"e": 1332,
"s": 1324,
"text": "Python3"
},
{
"code": "# importing module calc.pyimport calc print(calc.add(10, 2))",
"e": 1395,
"s": 1332,
"text": null
},
{
"code": null,
"e": 1403,
"s": 1395,
"text": "Output:"
},
{
"code": null,
"e": 1406,
"s": 1403,
"text": "12"
},
{
"code": null,
"e": 1521,
"s": 1406,
"text": "Python’s from statement lets you import specific attributes from a module without importing the module as a whole."
},
{
"code": null,
"e": 1529,
"s": 1521,
"text": "Python3"
},
{
"code": "# importing sqrt() and factorial from the# module mathfrom math import sqrt, factorial # if we simply do \"import math\", then# math.sqrt(16) and math.factorial()# are required.print(sqrt(16))print(factorial(6))",
"e": 1740,
"s": 1529,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1740,
"text": "Output: "
},
{
"code": null,
"e": 1757,
"s": 1749,
"text": "4.0\n720"
},
{
"code": null,
"e": 1876,
"s": 1757,
"text": "The * symbol used with the from import statement is used to import all the names from a module to a current namespace."
},
{
"code": null,
"e": 1884,
"s": 1876,
"text": "Syntax:"
},
{
"code": null,
"e": 1910,
"s": 1884,
"text": "from module_name import *"
},
{
"code": null,
"e": 2067,
"s": 1910,
"text": "The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the module, it is not recommended to use *, else do so."
},
{
"code": null,
"e": 2075,
"s": 2067,
"text": "Python3"
},
{
"code": "# importing sqrt() and factorial from the# module mathfrom math import * # if we simply do \"import math\", then# math.sqrt(16) and math.factorial()# are required.print(sqrt(16))print(factorial(6))",
"e": 2272,
"s": 2075,
"text": null
},
{
"code": null,
"e": 2280,
"s": 2272,
"text": "4.0\n720"
},
{
"code": null,
"e": 2558,
"s": 2280,
"text": "Whenever a module is imported in Python the interpreter looks for several locations. First, it will check for the built-in module, if not found then it looks for a list of directories defined in the sys.path. Python interpreter searches for the module in the following manner –"
},
{
"code": null,
"e": 2618,
"s": 2558,
"text": "First, it searches for the module in the current directory."
},
{
"code": null,
"e": 2820,
"s": 2618,
"text": "If the module isn’t found in the current directory, Python then searches each directory in the shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of directories."
},
{
"code": null,
"e": 2944,
"s": 2820,
"text": "If that also fails python checks the installation-dependent list of directories configured at the time Python is installed."
},
{
"code": null,
"e": 2952,
"s": 2944,
"text": "Python3"
},
{
"code": "# importing sys moduleimport sys # importing sys.pathprint(sys.path)",
"e": 3022,
"s": 2952,
"text": null
},
{
"code": null,
"e": 3030,
"s": 3022,
"text": "Output:"
},
{
"code": null,
"e": 3356,
"s": 3030,
"text": "[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’, ‘/home/nikhil/.ipython’]"
},
{
"code": null,
"e": 3423,
"s": 3356,
"text": "We can rename the module while importing it using the as keyword. "
},
{
"code": null,
"e": 3431,
"s": 3423,
"text": "Python3"
},
{
"code": "# importing sqrt() and factorial from the# module mathimport math as gfg # if we simply do \"import math\", then# math.sqrt(16) and math.factorial()# are required.print(gfg.sqrt(16))print(gfg.factorial(6))",
"e": 3636,
"s": 3431,
"text": null
},
{
"code": null,
"e": 3644,
"s": 3636,
"text": "4.0\n720"
},
{
"code": null,
"e": 3850,
"s": 3644,
"text": "The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables, and functions that are defined in a module."
},
{
"code": null,
"e": 3858,
"s": 3850,
"text": "Python3"
},
{
"code": "# Import built-in module randomimport randomprint(dir(random))",
"e": 3924,
"s": 3858,
"text": null
},
{
"code": null,
"e": 3935,
"s": 3927,
"text": "Output:"
},
{
"code": null,
"e": 4679,
"s": 3937,
"text": "[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’, ‘TWOPI’, ‘_BuiltinMethodType’, ‘_MethodType’, ‘_Sequence’, ‘_Set’, ‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘_acos’, ‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_inst’, ‘_itertools’, ‘_log’, ‘_pi’, ‘_random’, ‘_sha512’, ‘_sin’, ‘_sqrt’, ‘_test’, ‘_test_generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’, ‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’, ‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]"
},
{
"code": null,
"e": 4731,
"s": 4679,
"text": "Code Snippet illustrating python built-in modules: "
},
{
"code": null,
"e": 4741,
"s": 4733,
"text": "Python3"
},
{
"code": "# importing built-in module mathimport math # using square root(sqrt) function contained # in math moduleprint(math.sqrt(25)) # using pi function contained in math moduleprint(math.pi) # 2 radians = 114.59 degreesprint(math.degrees(2)) # 60 degrees = 1.04 radiansprint(math.radians(60)) # Sine of 2 radiansprint(math.sin(2)) # Cosine of 0.5 radiansprint(math.cos(0.5)) # Tangent of 0.23 radiansprint(math.tan(0.23)) # 1 * 2 * 3 * 4 = 24print(math.factorial(4)) # importing built in module randomimport random # printing random integer between 0 and 5print(random.randint(0, 5)) # print random floating point number between 0 and 1print(random.random()) # random number between 0 and 100print(random.random() * 100) List = [1, 4, True, 800, \"python\", 27, \"hello\"] # using choice function in random module for choosing # a random element from a set such as a listprint(random.choice(List)) # importing built in module datetimeimport datetimefrom datetime import dateimport time # Returns the number of seconds since the# Unix Epoch, January 1st 1970print(time.time()) # Converts a number of seconds to a date objectprint(date.fromtimestamp(454554)) ",
"e": 5931,
"s": 4741,
"text": null
},
{
"code": null,
"e": 5939,
"s": 5931,
"text": "Output:"
},
{
"code": null,
"e": 6232,
"s": 5939,
"text": "5.0\n3.14159265359\n114.591559026\n1.0471975512\n0.909297426826\n0.87758256189\n0.234143362351\n24\n3\n0.401533172951\n88.4917616788\nTrue\n1461425771.87\n\n \n My Personal Notes\n arrow_drop_up\n \n \n \n \n \n Save\n \n \n "
},
{
"code": null,
"e": 6243,
"s": 6232,
"text": "fridayda13"
},
{
"code": null,
"e": 6255,
"s": 6243,
"text": "RajuKumar19"
},
{
"code": null,
"e": 6271,
"s": 6255,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 6286,
"s": 6271,
"text": "sagartomar9927"
},
{
"code": null,
"e": 6300,
"s": 6286,
"text": "amartyaniel20"
},
{
"code": null,
"e": 6309,
"s": 6300,
"text": "\nPython\n"
},
{
"code": null,
"e": 6514,
"s": 6309,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 6542,
"s": 6514,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6592,
"s": 6542,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 6614,
"s": 6592,
"text": "Python map() function"
},
{
"code": null,
"e": 6658,
"s": 6614,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 6676,
"s": 6658,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6718,
"s": 6676,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6741,
"s": 6718,
"text": "Taking input in Python"
},
{
"code": null,
"e": 6763,
"s": 6741,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6798,
"s": 6763,
"text": "Read a file line by line in Python"
}
] |
Maximize the sum of selected numbers from an array to make it empty
|
28 Mar, 2022
Given an array A[] of N numbers, we need to maximize the sum of selected numbers following the given operation:
At each step, you need to select a number Ai, delete one occurrence and add it to the sum.
Delete one occurrence of Ai-1 and Ai+1 (if they exist in the array).
Repeat these steps until the array gets empty.
Examples:
Input: A[] = {1, 2, 3} Output: 4Explanation: At first step we select 1, so 1 and 2 are deleted from the sequence leaving us with 3. Then we select 3 from the sequence and delete it.So the sum of selected numbers is 1+3 = 4.
Input: A[] = {1, 2, 2, 2, 3, 4}Output: 10 Explanation: Select one of the 2’s from the array. So 2, 2-1, 2+1 will be deleted. Now array is {2, 2, 4}, since 1 and 3 are deleted. Select 2 in next two steps, and then select 4 in the last step.We get a sum of 2 + 2 + 2 + 4 = 10 which is the maximum possible.
Approach: The idea to solve the problem is:
Pre-calculate the occurrence of all numbers ( say x ) in the array A[] and then iterate from maximum number to minimum number.For each number x delete one occurrence of x and x-1(if exists) and add x to the sum until x is completely removed.
Follow the steps mentioned below to solve the problem
Calculate the MAX value in the array.
Create an array of size MAX and store the occurrences of each element in it.
Since we want to maximize our answer, we will start iterating from the MAX value to 0.
If the occurrence of the ith element is greater than 0, then add it to our answer decrease the occurrences of the i-1th element by 1, and also decrease the occurrence of ith by 1 since we have added it to our answer.
We don’t have to decrease the occurrence of the i+1th element because we are already starting from the end so i+1th is already processed.
There might be multiple occurrences of the ith element that’s why do not decrease i yet, to stay on the same element.
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// CPP program to Maximize the sum of selected// numbers by deleting three consecutive numbers.#include <bits/stdc++.h>using namespace std; // function to maximize the sum of selected numbersint maximizeSum(int arr[], int n) { // Largest element in the array int mx = -1; for(int i = 0; i < n; i++) { mx = max(mx, arr[i]); } // An array to count the occurrence of each element int freq[mx + 1]; memset(freq, 0, sizeof(freq)); for(int i = 0; i < n; i++) { freq[arr[i]]++; } // ans to store the result int ans = 0, i=mx; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans;} // Driver codeint main(){ int a[] = {1, 2, 3}; int n = sizeof(a) / sizeof(a[0]); cout << maximizeSum(a, n); return 0;}
// Java implementation of the approachimport java.util.*;import java.math.*; class GFG{ // Function to maximise the sum of selected numbers //by deleting occurrences of Ai-1 and Ai+1 public static int getMaximumSum (int arr[]) { // Number of elements in the array int n = arr.length; // Largest element in the array int max = -1; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i]); } // An array to count the occurrence of each element int []freq = new int[max + 1]; for(int i = 0; i < n; i++) { freq[arr[i]]++; } // ans to store the result int ans = 0, i=max; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans; } // Driver code public static void main(String[] args) { int []a = {1, 2, 3}; System.out.println(getMaximumSum(a)); }}
# Python3 program to Maximize the sum of selected# numbers by deleting three consecutive numbers. # function to maximize the sum of# selected numbersdef maximizeSum(a, n) : # maximum in the sequence maximum = max(a) # stores the occurrences of the numbers ans = dict.fromkeys(range(0, n + 1), 0) # marks the occurrence of every # number in the sequence for i in range(n) : ans[a[i]] += 1 # ans to store the result result = 0 i = maximum # Using the above mentioned approach while i > 0: # if occurrence is greater than 0 if ans[i] > 0: # add it to ans result += i; # decrease i-1th element by 1 ans[i-1] -= 1; # decrease ith element by 1 ans[i] -= 1; else: # decrease i i -= 1; return result; # Driver codeif __name__ == "__main__" : a = [1, 2, 3] n = len(a) print(maximizeSum(a, n)) # This code is contributed by Ryuga
// C# implementation of the approachusing System;using System.Linq; class GFG{ // Function to maximise the sum of selected numbers//by deleting occurrences of Ai-1 and Ai+1static int getMaximumSum(int []arr){ // Number of elements in the array int n = arr.Length; // Largest element in the array int max = arr.Max(); // An array to count the occurrence of each element int []freq = new int[max + 1]; for(int j = 0; j < n; j++) { freq[arr[j]]++; } // ans to store the result int ans = 0, i=max; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans;} // Driver codepublic static void Main(string[] args){ int []a = {1, 2, 3}; Console.Write(getMaximumSum(a));}} // This code is contributed by rock_cool
<script> // Javascript implementation of the approach // Function to maximise the sum of selected numbers //by deleting occurrences of Ai-1 and Ai+1 function getMaximumSum(arr) { // Number of elements in the array let n = arr.length; // Largest element in the array let max = Number.MIN_VALUE; for(let i = 0; i < n; i++) { max = Math.max(max, arr[i]); } // An array to count the occurrence of each element let freq = new Array(max + 1); freq.fill(0); for(let j = 0; j < n; j++) { freq[arr[j]]++; } // ans to store the result let ans = 0, i=max; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans; } let a = [1, 2, 3]; document.write(getMaximumSum(a)); // This code is contributed by suresh07.</script>
Output:
4
Time Complexity: (Amax + Highest occurrence of element in arr), because if the frequency is greater than 1 then we are processing that element multiple times.Auxiliary Space: O(Amax ), where Amax is the maximum element present in array A[].
ankthon
AnshulAggarwal
sooraj10
rock_cool
divyesh072019
adityapande88
suresh07
sooda367
ruhelaa48
sagartomar9927
animeshdey
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 164,
"s": 52,
"text": "Given an array A[] of N numbers, we need to maximize the sum of selected numbers following the given operation:"
},
{
"code": null,
"e": 255,
"s": 164,
"text": "At each step, you need to select a number Ai, delete one occurrence and add it to the sum."
},
{
"code": null,
"e": 325,
"s": 255,
"text": "Delete one occurrence of Ai-1 and Ai+1 (if they exist in the array). "
},
{
"code": null,
"e": 372,
"s": 325,
"text": "Repeat these steps until the array gets empty."
},
{
"code": null,
"e": 384,
"s": 372,
"text": "Examples: "
},
{
"code": null,
"e": 609,
"s": 384,
"text": "Input: A[] = {1, 2, 3} Output: 4Explanation: At first step we select 1, so 1 and 2 are deleted from the sequence leaving us with 3. Then we select 3 from the sequence and delete it.So the sum of selected numbers is 1+3 = 4. "
},
{
"code": null,
"e": 917,
"s": 609,
"text": "Input: A[] = {1, 2, 2, 2, 3, 4}Output: 10 Explanation: Select one of the 2’s from the array. So 2, 2-1, 2+1 will be deleted. Now array is {2, 2, 4}, since 1 and 3 are deleted. Select 2 in next two steps, and then select 4 in the last step.We get a sum of 2 + 2 + 2 + 4 = 10 which is the maximum possible. "
},
{
"code": null,
"e": 962,
"s": 917,
"text": " Approach: The idea to solve the problem is:"
},
{
"code": null,
"e": 1204,
"s": 962,
"text": "Pre-calculate the occurrence of all numbers ( say x ) in the array A[] and then iterate from maximum number to minimum number.For each number x delete one occurrence of x and x-1(if exists) and add x to the sum until x is completely removed."
},
{
"code": null,
"e": 1258,
"s": 1204,
"text": "Follow the steps mentioned below to solve the problem"
},
{
"code": null,
"e": 1296,
"s": 1258,
"text": "Calculate the MAX value in the array."
},
{
"code": null,
"e": 1373,
"s": 1296,
"text": "Create an array of size MAX and store the occurrences of each element in it."
},
{
"code": null,
"e": 1460,
"s": 1373,
"text": "Since we want to maximize our answer, we will start iterating from the MAX value to 0."
},
{
"code": null,
"e": 1677,
"s": 1460,
"text": "If the occurrence of the ith element is greater than 0, then add it to our answer decrease the occurrences of the i-1th element by 1, and also decrease the occurrence of ith by 1 since we have added it to our answer."
},
{
"code": null,
"e": 1815,
"s": 1677,
"text": "We don’t have to decrease the occurrence of the i+1th element because we are already starting from the end so i+1th is already processed."
},
{
"code": null,
"e": 1933,
"s": 1815,
"text": "There might be multiple occurrences of the ith element that’s why do not decrease i yet, to stay on the same element."
},
{
"code": null,
"e": 1982,
"s": 1933,
"text": "Below is the implementation of the above idea: "
},
{
"code": null,
"e": 1986,
"s": 1982,
"text": "C++"
},
{
"code": null,
"e": 1991,
"s": 1986,
"text": "Java"
},
{
"code": null,
"e": 1999,
"s": 1991,
"text": "Python3"
},
{
"code": null,
"e": 2002,
"s": 1999,
"text": "C#"
},
{
"code": null,
"e": 2013,
"s": 2002,
"text": "Javascript"
},
{
"code": "// CPP program to Maximize the sum of selected// numbers by deleting three consecutive numbers.#include <bits/stdc++.h>using namespace std; // function to maximize the sum of selected numbersint maximizeSum(int arr[], int n) { // Largest element in the array int mx = -1; for(int i = 0; i < n; i++) { mx = max(mx, arr[i]); } // An array to count the occurrence of each element int freq[mx + 1]; memset(freq, 0, sizeof(freq)); for(int i = 0; i < n; i++) { freq[arr[i]]++; } // ans to store the result int ans = 0, i=mx; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans;} // Driver codeint main(){ int a[] = {1, 2, 3}; int n = sizeof(a) / sizeof(a[0]); cout << maximizeSum(a, n); return 0;}",
"e": 3170,
"s": 2013,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;import java.math.*; class GFG{ // Function to maximise the sum of selected numbers //by deleting occurrences of Ai-1 and Ai+1 public static int getMaximumSum (int arr[]) { // Number of elements in the array int n = arr.length; // Largest element in the array int max = -1; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i]); } // An array to count the occurrence of each element int []freq = new int[max + 1]; for(int i = 0; i < n; i++) { freq[arr[i]]++; } // ans to store the result int ans = 0, i=max; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans; } // Driver code public static void main(String[] args) { int []a = {1, 2, 3}; System.out.println(getMaximumSum(a)); }}",
"e": 4616,
"s": 3170,
"text": null
},
{
"code": "# Python3 program to Maximize the sum of selected# numbers by deleting three consecutive numbers. # function to maximize the sum of# selected numbersdef maximizeSum(a, n) : # maximum in the sequence maximum = max(a) # stores the occurrences of the numbers ans = dict.fromkeys(range(0, n + 1), 0) # marks the occurrence of every # number in the sequence for i in range(n) : ans[a[i]] += 1 # ans to store the result result = 0 i = maximum # Using the above mentioned approach while i > 0: # if occurrence is greater than 0 if ans[i] > 0: # add it to ans result += i; # decrease i-1th element by 1 ans[i-1] -= 1; # decrease ith element by 1 ans[i] -= 1; else: # decrease i i -= 1; return result; # Driver codeif __name__ == \"__main__\" : a = [1, 2, 3] n = len(a) print(maximizeSum(a, n)) # This code is contributed by Ryuga",
"e": 5676,
"s": 4616,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Linq; class GFG{ // Function to maximise the sum of selected numbers//by deleting occurrences of Ai-1 and Ai+1static int getMaximumSum(int []arr){ // Number of elements in the array int n = arr.Length; // Largest element in the array int max = arr.Max(); // An array to count the occurrence of each element int []freq = new int[max + 1]; for(int j = 0; j < n; j++) { freq[arr[j]]++; } // ans to store the result int ans = 0, i=max; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans;} // Driver codepublic static void Main(string[] args){ int []a = {1, 2, 3}; Console.Write(getMaximumSum(a));}} // This code is contributed by rock_cool",
"e": 6745,
"s": 5676,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to maximise the sum of selected numbers //by deleting occurrences of Ai-1 and Ai+1 function getMaximumSum(arr) { // Number of elements in the array let n = arr.length; // Largest element in the array let max = Number.MIN_VALUE; for(let i = 0; i < n; i++) { max = Math.max(max, arr[i]); } // An array to count the occurrence of each element let freq = new Array(max + 1); freq.fill(0); for(let j = 0; j < n; j++) { freq[arr[j]]++; } // ans to store the result let ans = 0, i=max; // Using the above mentioned approach while(i>0){ // if occurrence is greater than 0 if(freq[i] > 0){ // add it to ans ans += i; // decrease i-1th element by 1 freq[i-1]--; // decrease ith element by 1 freq[i]--; }else{ // decrease i i--; } } return ans; } let a = [1, 2, 3]; document.write(getMaximumSum(a)); // This code is contributed by suresh07.</script>",
"e": 8004,
"s": 6745,
"text": null
},
{
"code": null,
"e": 8013,
"s": 8004,
"text": "Output: "
},
{
"code": null,
"e": 8015,
"s": 8013,
"text": "4"
},
{
"code": null,
"e": 8256,
"s": 8015,
"text": "Time Complexity: (Amax + Highest occurrence of element in arr), because if the frequency is greater than 1 then we are processing that element multiple times.Auxiliary Space: O(Amax ), where Amax is the maximum element present in array A[]."
},
{
"code": null,
"e": 8264,
"s": 8256,
"text": "ankthon"
},
{
"code": null,
"e": 8279,
"s": 8264,
"text": "AnshulAggarwal"
},
{
"code": null,
"e": 8288,
"s": 8279,
"text": "sooraj10"
},
{
"code": null,
"e": 8298,
"s": 8288,
"text": "rock_cool"
},
{
"code": null,
"e": 8312,
"s": 8298,
"text": "divyesh072019"
},
{
"code": null,
"e": 8326,
"s": 8312,
"text": "adityapande88"
},
{
"code": null,
"e": 8335,
"s": 8326,
"text": "suresh07"
},
{
"code": null,
"e": 8344,
"s": 8335,
"text": "sooda367"
},
{
"code": null,
"e": 8354,
"s": 8344,
"text": "ruhelaa48"
},
{
"code": null,
"e": 8369,
"s": 8354,
"text": "sagartomar9927"
},
{
"code": null,
"e": 8380,
"s": 8369,
"text": "animeshdey"
},
{
"code": null,
"e": 8400,
"s": 8380,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8420,
"s": 8400,
"text": "Dynamic Programming"
}
] |
Python Program for Range sum queries without updates
|
12 Jun, 2022
Given an array arr of integers of size n. We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples:
Input : arr[] = {1, 2, 3, 4, 5}
i = 1, j = 3
i = 2, j = 4
Output : 9
12
Input : arr[] = {1, 2, 3, 4, 5}
i = 0, j = 4
i = 1, j = 2
Output : 15
5
Python3
# Python program to find sum between two indexes# when there is no update. def find_ans(ar, j, k): l = len(ar) for i in range(1, l): ar[i] = ar[i] + ar[i-1] print(ar[k] - ar[j-1]) return; pr = [1, 2, 3, 4, 5]ar = pr[:]find_ans(ar, 1, 3)ar = pr[:]find_ans(ar, 2, 4) # Code Contributed by Mohit Gupta_OMG <(0_o)>
9
12
Time Complexity: O(n), where n represents the size of the given array.Auxiliary Space: O(n), where n represents the size of the given array.
Please refer complete article on Range sum queries without updates for more details!
tamanna17122007
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 245,
"s": 53,
"text": "Given an array arr of integers of size n. We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples:"
},
{
"code": null,
"e": 453,
"s": 245,
"text": "Input : arr[] = {1, 2, 3, 4, 5}\n i = 1, j = 3\n i = 2, j = 4\nOutput : 9\n 12 \n\nInput : arr[] = {1, 2, 3, 4, 5}\n i = 0, j = 4 \n i = 1, j = 2 \nOutput : 15\n 5"
},
{
"code": null,
"e": 461,
"s": 453,
"text": "Python3"
},
{
"code": "# Python program to find sum between two indexes# when there is no update. def find_ans(ar, j, k): l = len(ar) for i in range(1, l): ar[i] = ar[i] + ar[i-1] print(ar[k] - ar[j-1]) return; pr = [1, 2, 3, 4, 5]ar = pr[:]find_ans(ar, 1, 3)ar = pr[:]find_ans(ar, 2, 4) # Code Contributed by Mohit Gupta_OMG <(0_o)>",
"e": 793,
"s": 461,
"text": null
},
{
"code": null,
"e": 798,
"s": 793,
"text": "9\n12"
},
{
"code": null,
"e": 939,
"s": 798,
"text": "Time Complexity: O(n), where n represents the size of the given array.Auxiliary Space: O(n), where n represents the size of the given array."
},
{
"code": null,
"e": 1024,
"s": 939,
"text": "Please refer complete article on Range sum queries without updates for more details!"
},
{
"code": null,
"e": 1040,
"s": 1024,
"text": "tamanna17122007"
},
{
"code": null,
"e": 1056,
"s": 1040,
"text": "Python Programs"
}
] |
Tcl - Special Variables
|
In Tcl, we classify some of the variables as special variables and they have a predefined usage/functionality. The list of specials variables is listed below.
argc
Refers to a number of command-line arguments.
argv
Refers to the list containing the command-line arguments.
argv0
Refers to the file name of the file being interpreted or the name by which we invoke the script.
env
Used for representing the array of elements that are environmental variables.
errorCode
Provides the error code for last Tcl error.
errorInfo
Provides the stack trace for last Tcl error.
tcl_interactive
Used to switch between interactive and non-interactive modes by setting this to 1 and 0 respectively.
tcl_library
Used for setting the location of standard Tcl libraries.
tcl_pkgPath
Provides the list of directories where packages are generally installed.
tcl_patchLevel
Refers to the current patch level of the Tcl interpreter.
tcl_platform
Used for representing the array of elements with objects including byteOrder, machine, osVersion, platform, and os.
tcl_precision
Refers to the precision i.e. number of digits to retain when converting to floating-point numbers to strings. The default value is 12.
tcl_prompt1
Refers to the primary prompt.
tcl_prompt2
Refers to the secondary prompt with invalid commands.
tcl_rcFileName
Provides the user specific startup file.
tcl_traceCompile
Used for controlling the tracing of bytecode compilation. Use 0 for no output, 1 for summary, and 2 for detailed.
tcl_traceExec
Used for controlling the tracing of bytecode execution. Use 0 for no output, 1 for summary, and 2 for detailed.
tcl_version
Returns the current version of the Tcl interpreter.
The above special variables have their special meanings for the Tcl interpreter.
Let's see some examples for special variables.
#!/usr/bin/tclsh
puts $tcl_version
When you run the program, you will get a similar output as shown below −
8.6
#!/usr/bin/tclsh
puts $env(PATH)
When you run the program, you will get a similar output as shown below −
/home/cg/root/GNUstep/Tools:/usr/GNUstep/Local/Tools:/usr/GNUstep/
System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/webmaster/.local/bin:/
home/webmaster/bin:/usr/local/scriba/bin:/usr/local/smlnj/
bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/
local/dart/bin:/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/opt/mono/
bin:/opt/mono/lib/mono/4.5:/usr/local/bin:.:/usr/libexec/sdcc:/usr/local/
icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/jdk1.7.0_75/bin:/
opt/jdk1.7.0_75/jre/bin:/opt/pash/Source/PashConsole/bin/Debug/
#!/usr/bin/tclsh
puts $tcl_pkgPath
When you run the program, you will get a similar output as shown below −
/usr/lib64/tcl8.6 /usr/share/tcl8.6 /usr/lib64/tk8.6 /usr/share/tk8.6
#!/usr/bin/tclsh
puts $tcl_library
When you run the program, you will get a similar output as shown below −
/usr/share/tcl8.6
#!/usr/bin/tclsh
puts $tcl_patchLevel
When you run the program, you will get a similar output as shown below −
8.6.6
#!/usr/bin/tclsh
puts $tcl_precision
When you run the program, you will get a similar output as shown below −
0
#!/usr/bin/tclsh
puts $tcl_rcFileName
When you run the program, you will get a similar output as shown below −
|
[
{
"code": null,
"e": 2494,
"s": 2335,
"text": "In Tcl, we classify some of the variables as special variables and they have a predefined usage/functionality. The list of specials variables is listed below."
},
{
"code": null,
"e": 2499,
"s": 2494,
"text": "argc"
},
{
"code": null,
"e": 2545,
"s": 2499,
"text": "Refers to a number of command-line arguments."
},
{
"code": null,
"e": 2550,
"s": 2545,
"text": "argv"
},
{
"code": null,
"e": 2608,
"s": 2550,
"text": "Refers to the list containing the command-line arguments."
},
{
"code": null,
"e": 2614,
"s": 2608,
"text": "argv0"
},
{
"code": null,
"e": 2711,
"s": 2614,
"text": "Refers to the file name of the file being interpreted or the name by which we invoke the script."
},
{
"code": null,
"e": 2715,
"s": 2711,
"text": "env"
},
{
"code": null,
"e": 2793,
"s": 2715,
"text": "Used for representing the array of elements that are environmental variables."
},
{
"code": null,
"e": 2803,
"s": 2793,
"text": "errorCode"
},
{
"code": null,
"e": 2847,
"s": 2803,
"text": "Provides the error code for last Tcl error."
},
{
"code": null,
"e": 2857,
"s": 2847,
"text": "errorInfo"
},
{
"code": null,
"e": 2902,
"s": 2857,
"text": "Provides the stack trace for last Tcl error."
},
{
"code": null,
"e": 2918,
"s": 2902,
"text": "tcl_interactive"
},
{
"code": null,
"e": 3020,
"s": 2918,
"text": "Used to switch between interactive and non-interactive modes by setting this to 1 and 0 respectively."
},
{
"code": null,
"e": 3032,
"s": 3020,
"text": "tcl_library"
},
{
"code": null,
"e": 3089,
"s": 3032,
"text": "Used for setting the location of standard Tcl libraries."
},
{
"code": null,
"e": 3101,
"s": 3089,
"text": "tcl_pkgPath"
},
{
"code": null,
"e": 3174,
"s": 3101,
"text": "Provides the list of directories where packages are generally installed."
},
{
"code": null,
"e": 3189,
"s": 3174,
"text": "tcl_patchLevel"
},
{
"code": null,
"e": 3247,
"s": 3189,
"text": "Refers to the current patch level of the Tcl interpreter."
},
{
"code": null,
"e": 3260,
"s": 3247,
"text": "tcl_platform"
},
{
"code": null,
"e": 3376,
"s": 3260,
"text": "Used for representing the array of elements with objects including byteOrder, machine, osVersion, platform, and os."
},
{
"code": null,
"e": 3390,
"s": 3376,
"text": "tcl_precision"
},
{
"code": null,
"e": 3525,
"s": 3390,
"text": "Refers to the precision i.e. number of digits to retain when converting to floating-point numbers to strings. The default value is 12."
},
{
"code": null,
"e": 3537,
"s": 3525,
"text": "tcl_prompt1"
},
{
"code": null,
"e": 3567,
"s": 3537,
"text": "Refers to the primary prompt."
},
{
"code": null,
"e": 3579,
"s": 3567,
"text": "tcl_prompt2"
},
{
"code": null,
"e": 3633,
"s": 3579,
"text": "Refers to the secondary prompt with invalid commands."
},
{
"code": null,
"e": 3648,
"s": 3633,
"text": "tcl_rcFileName"
},
{
"code": null,
"e": 3689,
"s": 3648,
"text": "Provides the user specific startup file."
},
{
"code": null,
"e": 3706,
"s": 3689,
"text": "tcl_traceCompile"
},
{
"code": null,
"e": 3820,
"s": 3706,
"text": "Used for controlling the tracing of bytecode compilation. Use 0 for no output, 1 for summary, and 2 for detailed."
},
{
"code": null,
"e": 3834,
"s": 3820,
"text": "tcl_traceExec"
},
{
"code": null,
"e": 3946,
"s": 3834,
"text": "Used for controlling the tracing of bytecode execution. Use 0 for no output, 1 for summary, and 2 for detailed."
},
{
"code": null,
"e": 3958,
"s": 3946,
"text": "tcl_version"
},
{
"code": null,
"e": 4010,
"s": 3958,
"text": "Returns the current version of the Tcl interpreter."
},
{
"code": null,
"e": 4091,
"s": 4010,
"text": "The above special variables have their special meanings for the Tcl interpreter."
},
{
"code": null,
"e": 4138,
"s": 4091,
"text": "Let's see some examples for special variables."
},
{
"code": null,
"e": 4174,
"s": 4138,
"text": "#!/usr/bin/tclsh\n\nputs $tcl_version"
},
{
"code": null,
"e": 4247,
"s": 4174,
"text": "When you run the program, you will get a similar output as shown below −"
},
{
"code": null,
"e": 4252,
"s": 4247,
"text": "8.6\n"
},
{
"code": null,
"e": 4286,
"s": 4252,
"text": "#!/usr/bin/tclsh\n\nputs $env(PATH)"
},
{
"code": null,
"e": 4359,
"s": 4286,
"text": "When you run the program, you will get a similar output as shown below −"
},
{
"code": null,
"e": 4937,
"s": 4359,
"text": "/home/cg/root/GNUstep/Tools:/usr/GNUstep/Local/Tools:/usr/GNUstep/\nSystem/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/webmaster/.local/bin:/\nhome/webmaster/bin:/usr/local/scriba/bin:/usr/local/smlnj/\nbin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/\nlocal/dart/bin:/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/opt/mono/\nbin:/opt/mono/lib/mono/4.5:/usr/local/bin:.:/usr/libexec/sdcc:/usr/local/\nicon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/jdk1.7.0_75/bin:/\nopt/jdk1.7.0_75/jre/bin:/opt/pash/Source/PashConsole/bin/Debug/\n"
},
{
"code": null,
"e": 4973,
"s": 4937,
"text": "#!/usr/bin/tclsh\n\nputs $tcl_pkgPath"
},
{
"code": null,
"e": 5046,
"s": 4973,
"text": "When you run the program, you will get a similar output as shown below −"
},
{
"code": null,
"e": 5117,
"s": 5046,
"text": "/usr/lib64/tcl8.6 /usr/share/tcl8.6 /usr/lib64/tk8.6 /usr/share/tk8.6\n"
},
{
"code": null,
"e": 5153,
"s": 5117,
"text": "#!/usr/bin/tclsh\n\nputs $tcl_library"
},
{
"code": null,
"e": 5226,
"s": 5153,
"text": "When you run the program, you will get a similar output as shown below −"
},
{
"code": null,
"e": 5245,
"s": 5226,
"text": "/usr/share/tcl8.6\n"
},
{
"code": null,
"e": 5284,
"s": 5245,
"text": "#!/usr/bin/tclsh\n\nputs $tcl_patchLevel"
},
{
"code": null,
"e": 5357,
"s": 5284,
"text": "When you run the program, you will get a similar output as shown below −"
},
{
"code": null,
"e": 5364,
"s": 5357,
"text": "8.6.6\n"
},
{
"code": null,
"e": 5402,
"s": 5364,
"text": "#!/usr/bin/tclsh\n\nputs $tcl_precision"
},
{
"code": null,
"e": 5475,
"s": 5402,
"text": "When you run the program, you will get a similar output as shown below −"
},
{
"code": null,
"e": 5478,
"s": 5475,
"text": "0\n"
},
{
"code": null,
"e": 5517,
"s": 5478,
"text": "#!/usr/bin/tclsh\n\nputs $tcl_rcFileName"
}
] |
Linux Virtualization – Chroot Jail
|
21 Jul, 2021
What is a chroot Jail?
A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. The programs that run in this modified environment cannot access the files outside the designated directory tree. This essentially limits their access to a directory tree and thus they get the name “chroot jail”.
The idea is that you create a directory tree where you copy or link in all the system files needed for a process to run. You then use the chroot system call to change the root directory to be at the base of this new tree and start the process running in that chrooted environment. Since it can’t actually reference paths outside the modified root, it can’t maliciously read or write to those locations.
Why is it required and how is it different from the virtual machines?This is a Operating-system-level virtualization and is often used instead of virtual machines to create multiple isolated instances of the host OS. This is a kernel level virtualization and has practically no overhead as compared to Virtual Machines, which are a application layer virtualization, as a result it provides a very good method for creating multiple isolated instances on the same hardware. A virtual machine (VM) is a software implementation of a machine and they often exploit what is know as the Hardware Virtualization to render a virtual images of a working operating system.
How do i use it?The basic command to create a chroot jail is as follows:
chroot /path/to/new/root command
OR
chroot /path/to/new/root /path/to/server
OR
chroot [options] /path/to/new/root /path/to/server
Note: Only a root/privileged user can use the chroot system call. A non-privileged user with the access to the command can bypass the chroot jail.
Steps to create a mini-jail for the ‘bash’ and the ‘ls’ command
1. Create a directory which will act as the root of the command.
$ mkdir jailed
$ cd jailed
2. Create all the essential directories for the command to run: Depending on your operating system, the required directories may change. Logically, we create all these directories to keep a copy of required libraries. To see what all directories are required, see Step 4.
$ mkdir -p bin lib64/x86_64-linux-gnu lib/x86_64-linux-gnu
3.Run the ‘which’ command: Run the ‘which’ command to find the location of ls and bash command.After running which command,copy those binaries in the ‘bin’ directory of our jail. Make sure you don’t have any of these commands aliased. From now on, we would be referring to our directory as ‘Jailed’ directory for convenience.
$ unalias ls # Required only if you have aliased ls command
$ unalias bash # Required only if you have aliased bash command
$ cp $(which ls) ./bin/
$ cp $(which bash) ./bin/
4. Copy appropriate libraries/objects: For the executables in our Jaileddirectory to work we need to copy the appropriate libraries/objects in the JAILED directory. By default, the executable looks at the locations starting with ‘/’. To find the dependencies we use the command ‘ldd’
$ ldd $(which bash)
linux-vdso.so.1 => (0x00007ffc75dd4000)
libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007f6577768000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f6577564000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f657719a000)
/lib64/ld-linux-x86-64.so.2 (0x000055979f3fd000)
Run the following commands to create appropriate directories.
$ cp /lib/x86_64-linux-gnu/libtinfo.so.5 lib/x86_64-linux-gnu/
$ cp /lib/x86_64-linux-gnu/libdl.so.2 lib/x86_64-linux-gnu/
$ cp /lib/x86_64-linux-gnu/libc.so.6 lib/x86_64-linux-gnu/
$ cp /lib64/ld-linux-x86-64.so.2 lib64/
Similarly for ls,
$ ldd $(which ls)
linux-vdso.so.1 => (0x00007fff4f05d000)
libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f9a2fd07000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9a2f93e000)
libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f9a2f6cd000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9a2f4c9000)
/lib64/ld-linux-x86-64.so.2 (0x000055e836c69000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9a2f2ac000)
$ cp /lib/x86_64-linux-gnu/libselinux.so.1 lib/x86_64-linux-gnu/
$ cp /lib/x86_64-linux-gnu/libc.so.6 lib/x86_64-linux-gnu/
$ cp /lib/x86_64-linux-gnu/libpcre.so.3 lib/x86_64-linux-gnu/
$ cp /lib/x86_64-linux-gnu/libdl.so.2 lib/x86_64-linux-gnu/
$ cp /lib64/ld-linux-x86-64.so.2 lib64/
$ cp /lib/x86_64-linux-gnu/libpthread.so.0 lib/x86_64-linux-gnu/
The final directory structure must be similar to this,
5. Sudo chroot:Run this command to change the root to the JAILED directory, along with the path to the shell. By default it will try to load ‘/bin/sh’ shell.
$ cd ..
$ sudo chroot jailed /bin/bash
You might face this error while running the chroot command,
chroot: failed to run command `/bin/bash': No such file or directory
This may be due to 2 reasons, either the file does not exist(which is obvious), or when the loading library fails or is not available. Double-Check if the libraries are in correct location.
6. A new shell must pop up:Its our jailed bash. We currently have only 2 commands installed, bash and ls. Fortunately cd and pwd are builtin commands in bash shell, and so you can use them as well.
Roam around the directory, try accessing ‘cd /../’ or something similar. Try to break the jail, probably you won’t be able to.
To exit from the jail,
$ exit
The most important and interesting part is that, when you run,
$ ps aux
and find the process, you’ll find that there is only one process,
root 24958 ... 03:21 0:00 /usr/bin/sudo -E chroot jailed/ /bin/bash
Interestingly, processes in the jailed shell run as a simple child process of this shell. All the processes inside the JAILED environment, are just simple user level process in the host OS and are isolated by the namespaces provided by the kernel, thus there is minimal overhead and as an added benefit we get isolation.
A copy of jailed-bash-directory explained here can be downloaded from here.
Similarly, you can add more commands to you virtual jailed environment. To add more complex programs, you might need to create more directories, like, ‘/proc’ and ‘/dev’. These increase the complexity of the process. Hopefully we do not require it for our purpose.
This is all you need to know about chroot and the jailing of directories. Our ultimate aim is to understand what are containers and how are services like AWS (Amazon Web Services), Google Cloud and Docker able to provide so many virtual instances of operating systems on demand. Also, how does sys-admin run multiple web-servers for multiple domains on a single physical machine.This was just one step towards understanding it
References:
https://help.ubuntu.com/community/DebootstrapChroot
https://wiki.archlinux.org/index.php/Install_from_existing_Linux
http://serverfault.com/questions/162362/chroot-fails-cannot-run-command-bin-bash-no-such-file-or-directory
https://wiki.archlinux.org/index.php/change_root
About the Author:Pinkesh Badjatiya hails from IIIT Hyderabad. He is a geek at heart with ample projects worth looking for. His project work can be seen here.
If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.
surinderdawra388
kapoorsagar226
virtualization
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 75,
"s": 52,
"text": "What is a chroot Jail?"
},
{
"code": null,
"e": 430,
"s": 75,
"text": "A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. The programs that run in this modified environment cannot access the files outside the designated directory tree. This essentially limits their access to a directory tree and thus they get the name “chroot jail”."
},
{
"code": null,
"e": 833,
"s": 430,
"text": "The idea is that you create a directory tree where you copy or link in all the system files needed for a process to run. You then use the chroot system call to change the root directory to be at the base of this new tree and start the process running in that chrooted environment. Since it can’t actually reference paths outside the modified root, it can’t maliciously read or write to those locations."
},
{
"code": null,
"e": 1495,
"s": 833,
"text": "Why is it required and how is it different from the virtual machines?This is a Operating-system-level virtualization and is often used instead of virtual machines to create multiple isolated instances of the host OS. This is a kernel level virtualization and has practically no overhead as compared to Virtual Machines, which are a application layer virtualization, as a result it provides a very good method for creating multiple isolated instances on the same hardware. A virtual machine (VM) is a software implementation of a machine and they often exploit what is know as the Hardware Virtualization to render a virtual images of a working operating system."
},
{
"code": null,
"e": 1569,
"s": 1495,
"text": "How do i use it?The basic command to create a chroot jail is as follows: "
},
{
"code": null,
"e": 1741,
"s": 1569,
"text": " chroot /path/to/new/root command\n OR\n chroot /path/to/new/root /path/to/server\n OR\n chroot [options] /path/to/new/root /path/to/server"
},
{
"code": null,
"e": 1888,
"s": 1741,
"text": "Note: Only a root/privileged user can use the chroot system call. A non-privileged user with the access to the command can bypass the chroot jail."
},
{
"code": null,
"e": 1952,
"s": 1888,
"text": "Steps to create a mini-jail for the ‘bash’ and the ‘ls’ command"
},
{
"code": null,
"e": 2017,
"s": 1952,
"text": "1. Create a directory which will act as the root of the command."
},
{
"code": null,
"e": 2048,
"s": 2017,
"text": " $ mkdir jailed\n $ cd jailed"
},
{
"code": null,
"e": 2320,
"s": 2048,
"text": "2. Create all the essential directories for the command to run: Depending on your operating system, the required directories may change. Logically, we create all these directories to keep a copy of required libraries. To see what all directories are required, see Step 4."
},
{
"code": null,
"e": 2381,
"s": 2320,
"text": " $ mkdir -p bin lib64/x86_64-linux-gnu lib/x86_64-linux-gnu"
},
{
"code": null,
"e": 2707,
"s": 2381,
"text": "3.Run the ‘which’ command: Run the ‘which’ command to find the location of ls and bash command.After running which command,copy those binaries in the ‘bin’ directory of our jail. Make sure you don’t have any of these commands aliased. From now on, we would be referring to our directory as ‘Jailed’ directory for convenience."
},
{
"code": null,
"e": 2905,
"s": 2707,
"text": " $ unalias ls # Required only if you have aliased ls command\n $ unalias bash # Required only if you have aliased bash command\n $ cp $(which ls) ./bin/\n $ cp $(which bash) ./bin/"
},
{
"code": null,
"e": 3189,
"s": 2905,
"text": "4. Copy appropriate libraries/objects: For the executables in our Jaileddirectory to work we need to copy the appropriate libraries/objects in the JAILED directory. By default, the executable looks at the locations starting with ‘/’. To find the dependencies we use the command ‘ldd’"
},
{
"code": null,
"e": 3527,
"s": 3189,
"text": "$ ldd $(which bash)\n linux-vdso.so.1 => (0x00007ffc75dd4000)\n libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007f6577768000)\n libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f6577564000)\n libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f657719a000)\n /lib64/ld-linux-x86-64.so.2 (0x000055979f3fd000)"
},
{
"code": null,
"e": 3590,
"s": 3527,
"text": "Run the following commands to create appropriate directories. "
},
{
"code": null,
"e": 3812,
"s": 3590,
"text": "$ cp /lib/x86_64-linux-gnu/libtinfo.so.5 lib/x86_64-linux-gnu/\n$ cp /lib/x86_64-linux-gnu/libdl.so.2 lib/x86_64-linux-gnu/\n$ cp /lib/x86_64-linux-gnu/libc.so.6 lib/x86_64-linux-gnu/\n$ cp /lib64/ld-linux-x86-64.so.2 lib64/"
},
{
"code": null,
"e": 3831,
"s": 3812,
"text": "Similarly for ls, "
},
{
"code": null,
"e": 4329,
"s": 3831,
"text": "$ ldd $(which ls)\n linux-vdso.so.1 => (0x00007fff4f05d000)\n libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f9a2fd07000)\n libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9a2f93e000)\n libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f9a2f6cd000)\n libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9a2f4c9000)\n /lib64/ld-linux-x86-64.so.2 (0x000055e836c69000)\n libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9a2f2ac000)"
},
{
"code": null,
"e": 4681,
"s": 4329,
"text": "$ cp /lib/x86_64-linux-gnu/libselinux.so.1 lib/x86_64-linux-gnu/\n$ cp /lib/x86_64-linux-gnu/libc.so.6 lib/x86_64-linux-gnu/\n$ cp /lib/x86_64-linux-gnu/libpcre.so.3 lib/x86_64-linux-gnu/\n$ cp /lib/x86_64-linux-gnu/libdl.so.2 lib/x86_64-linux-gnu/\n$ cp /lib64/ld-linux-x86-64.so.2 lib64/\n$ cp /lib/x86_64-linux-gnu/libpthread.so.0 lib/x86_64-linux-gnu/"
},
{
"code": null,
"e": 4736,
"s": 4681,
"text": "The final directory structure must be similar to this,"
},
{
"code": null,
"e": 4894,
"s": 4736,
"text": "5. Sudo chroot:Run this command to change the root to the JAILED directory, along with the path to the shell. By default it will try to load ‘/bin/sh’ shell."
},
{
"code": null,
"e": 4939,
"s": 4894,
"text": " $ cd ..\n $ sudo chroot jailed /bin/bash"
},
{
"code": null,
"e": 5000,
"s": 4939,
"text": "You might face this error while running the chroot command, "
},
{
"code": null,
"e": 5069,
"s": 5000,
"text": "chroot: failed to run command `/bin/bash': No such file or directory"
},
{
"code": null,
"e": 5259,
"s": 5069,
"text": "This may be due to 2 reasons, either the file does not exist(which is obvious), or when the loading library fails or is not available. Double-Check if the libraries are in correct location."
},
{
"code": null,
"e": 5457,
"s": 5259,
"text": "6. A new shell must pop up:Its our jailed bash. We currently have only 2 commands installed, bash and ls. Fortunately cd and pwd are builtin commands in bash shell, and so you can use them as well."
},
{
"code": null,
"e": 5585,
"s": 5457,
"text": "Roam around the directory, try accessing ‘cd /../’ or something similar. Try to break the jail, probably you won’t be able to. "
},
{
"code": null,
"e": 5609,
"s": 5585,
"text": "To exit from the jail, "
},
{
"code": null,
"e": 5622,
"s": 5609,
"text": " $ exit"
},
{
"code": null,
"e": 5686,
"s": 5622,
"text": "The most important and interesting part is that, when you run, "
},
{
"code": null,
"e": 5699,
"s": 5686,
"text": " $ ps aux"
},
{
"code": null,
"e": 5766,
"s": 5699,
"text": "and find the process, you’ll find that there is only one process, "
},
{
"code": null,
"e": 5842,
"s": 5766,
"text": "root 24958 ... 03:21 0:00 /usr/bin/sudo -E chroot jailed/ /bin/bash"
},
{
"code": null,
"e": 6163,
"s": 5842,
"text": "Interestingly, processes in the jailed shell run as a simple child process of this shell. All the processes inside the JAILED environment, are just simple user level process in the host OS and are isolated by the namespaces provided by the kernel, thus there is minimal overhead and as an added benefit we get isolation."
},
{
"code": null,
"e": 6240,
"s": 6163,
"text": "A copy of jailed-bash-directory explained here can be downloaded from here. "
},
{
"code": null,
"e": 6505,
"s": 6240,
"text": "Similarly, you can add more commands to you virtual jailed environment. To add more complex programs, you might need to create more directories, like, ‘/proc’ and ‘/dev’. These increase the complexity of the process. Hopefully we do not require it for our purpose."
},
{
"code": null,
"e": 6933,
"s": 6505,
"text": "This is all you need to know about chroot and the jailing of directories. Our ultimate aim is to understand what are containers and how are services like AWS (Amazon Web Services), Google Cloud and Docker able to provide so many virtual instances of operating systems on demand. Also, how does sys-admin run multiple web-servers for multiple domains on a single physical machine.This was just one step towards understanding it "
},
{
"code": null,
"e": 6946,
"s": 6933,
"text": "References: "
},
{
"code": null,
"e": 6998,
"s": 6946,
"text": "https://help.ubuntu.com/community/DebootstrapChroot"
},
{
"code": null,
"e": 7063,
"s": 6998,
"text": "https://wiki.archlinux.org/index.php/Install_from_existing_Linux"
},
{
"code": null,
"e": 7170,
"s": 7063,
"text": "http://serverfault.com/questions/162362/chroot-fails-cannot-run-command-bin-bash-no-such-file-or-directory"
},
{
"code": null,
"e": 7219,
"s": 7170,
"text": "https://wiki.archlinux.org/index.php/change_root"
},
{
"code": null,
"e": 7377,
"s": 7219,
"text": "About the Author:Pinkesh Badjatiya hails from IIIT Hyderabad. He is a geek at heart with ample projects worth looking for. His project work can be seen here."
},
{
"code": null,
"e": 7480,
"s": 7377,
"text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks."
},
{
"code": null,
"e": 7497,
"s": 7480,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7512,
"s": 7497,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 7527,
"s": 7512,
"text": "virtualization"
},
{
"code": null,
"e": 7538,
"s": 7527,
"text": "Linux-Unix"
},
{
"code": null,
"e": 7636,
"s": 7538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7671,
"s": 7636,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 7704,
"s": 7671,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 7742,
"s": 7704,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 7778,
"s": 7742,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 7804,
"s": 7778,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 7842,
"s": 7804,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 7877,
"s": 7842,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 7913,
"s": 7877,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 7948,
"s": 7913,
"text": "Cat command in Linux with examples"
}
] |
Hibernate Architecture
|
02 Aug, 2018
Prerequisites: Introduction of Hibernate
Hibernate: Hibernate is a framework which is used to develop persistence logic which is independent of Database software. In JDBC to develop persistence logic we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic which are independent of database software.
Hibernate Architecture:
Configuration:
Configuration is a class which is present in org.hibernate.cfg package. It activates Hibernate framework. It reads both configuration file and mapping files.It activate Hibernate Framework
Configuration cfg=new Configuration();
It read both cfg file and mapping files
cfg.configure();
It activate Hibernate Framework
Configuration cfg=new Configuration();
It read both cfg file and mapping files
cfg.configure();
It checks whether the config file is syntactically correct or not.
If the config file is not valid then it will throw an exception. If it is valid then it creates a meta-data in memory and returns the meta-data to object to represent the config file.
SessionFactory:
SessionFactory is an Interface which is present in org.hibernate package and it is used to create Session Object.
It is immutable and thread-safe in nature.buildSessionFactory() method gathers the meta-data which is in the cfg Object.
From cfg object it takes the JDBC information and create a JDBC Connection.
SessionFactory factory=cfg.buildSessionFactory();
buildSessionFactory() method gathers the meta-data which is in the cfg Object.
From cfg object it takes the JDBC information and create a JDBC Connection.
SessionFactory factory=cfg.buildSessionFactory();
Session:
Session is an interface which is present in org.hibernate package. Session object is created based upon SessionFactory object i.e. factory.
It opens the Connection/Session with Database software through Hibernate Framework.
It is a light-weight object and it is not thread-safe.
Session object is used to perform CRUD operations.Session session=factory.buildSession();
Session session=factory.buildSession();
Transaction:
Transaction object is used whenever we perform any operation and based upon that operation there is some change in database.
Transaction object is used to give the instruction to the database to make the changes that happen because of operation as a permanent by using commit() method.Transaction tx=session.beginTransaction();
tx.commit();
Transaction tx=session.beginTransaction();
tx.commit();
Query:
Query is an interface that present inside org.hibernate package.
A Query instance is obtained by calling Session.createQuery().
This interface exposes some extra functionality beyond that provided by Session.iterate() and Session.find():A particular page of the result set may be selected by calling setMaxResults(), setFirstResult().Named query parameters may be used.
A particular page of the result set may be selected by calling setMaxResults(), setFirstResult().Named query parameters may be used.
A particular page of the result set may be selected by calling setMaxResults(), setFirstResult().
Named query parameters may be used.
Query query=session.createQuery();
Criteria:
Criteria is a simplified API for retrieving entities by composing Criterion objects.
The Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on Restrictions.
Criteria criteria=session.createCriteria();
Flow of working during operation in Hibernate Framework :
Suppose We want to insert an Object to the database. Here Object is nothing but persistence logic which we write on java program and create an object of that program. If we want to insert that object in the database or we want to retrieve the object from the database. Now the question is that how hibernate save the Object to the database or retrieve the object from the database. There are several layers through which Hibernate framework go to achieve the above task. Let us understathe nd the layers/flow of Hibernate framework during performing operations:
Stage I: In first stage, we will write the persistence logic to perform some specific operations to the database with the help of Hibernate Configuration file and Hibernate mapping file. And after that we create an object of the particular class on which we wrote the persistence logic.
Stage II:In second stage, our class which contains the persistence logic will interact with the hibernate framework where hibernate framework gives some abstraction do perform some task. Now here the picture of java class is over. Now Hibernate is responsible to perform the persistence logic with the help of layers which is below of Hibernate framework or we can say that the layers which are the internal implementation of Hibernate.
Stage III:In third stage, our hibernate framework interact which JDBC, JNDI, JTA etc to go to the database to perform that persistence logic.
Stage IV & V:In fourth & fifth stage, hibernate is interact with Database with the help of JDBC driver. Now here hibernate perform that persistence logic which is nothing but CRUD operation. If our persistence logic is to retrieve an record then in the reverse order it will display on the console of our java program in terms of Object.
JDBC
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": "\n02 Aug, 2018"
},
{
"code": null,
"e": 93,
"s": 52,
"text": "Prerequisites: Introduction of Hibernate"
},
{
"code": null,
"e": 398,
"s": 93,
"text": "Hibernate: Hibernate is a framework which is used to develop persistence logic which is independent of Database software. In JDBC to develop persistence logic we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic which are independent of database software."
},
{
"code": null,
"e": 422,
"s": 398,
"text": "Hibernate Architecture:"
},
{
"code": null,
"e": 437,
"s": 422,
"text": "Configuration:"
},
{
"code": null,
"e": 723,
"s": 437,
"text": "Configuration is a class which is present in org.hibernate.cfg package. It activates Hibernate framework. It reads both configuration file and mapping files.It activate Hibernate Framework\nConfiguration cfg=new Configuration();\nIt read both cfg file and mapping files\ncfg.configure();\n"
},
{
"code": null,
"e": 852,
"s": 723,
"text": "It activate Hibernate Framework\nConfiguration cfg=new Configuration();\nIt read both cfg file and mapping files\ncfg.configure();\n"
},
{
"code": null,
"e": 919,
"s": 852,
"text": "It checks whether the config file is syntactically correct or not."
},
{
"code": null,
"e": 1103,
"s": 919,
"text": "If the config file is not valid then it will throw an exception. If it is valid then it creates a meta-data in memory and returns the meta-data to object to represent the config file."
},
{
"code": null,
"e": 1119,
"s": 1103,
"text": "SessionFactory:"
},
{
"code": null,
"e": 1233,
"s": 1119,
"text": "SessionFactory is an Interface which is present in org.hibernate package and it is used to create Session Object."
},
{
"code": null,
"e": 1482,
"s": 1233,
"text": "It is immutable and thread-safe in nature.buildSessionFactory() method gathers the meta-data which is in the cfg Object. \nFrom cfg object it takes the JDBC information and create a JDBC Connection.\nSessionFactory factory=cfg.buildSessionFactory();\n"
},
{
"code": null,
"e": 1689,
"s": 1482,
"text": "buildSessionFactory() method gathers the meta-data which is in the cfg Object. \nFrom cfg object it takes the JDBC information and create a JDBC Connection.\nSessionFactory factory=cfg.buildSessionFactory();\n"
},
{
"code": null,
"e": 1698,
"s": 1689,
"text": "Session:"
},
{
"code": null,
"e": 1838,
"s": 1698,
"text": "Session is an interface which is present in org.hibernate package. Session object is created based upon SessionFactory object i.e. factory."
},
{
"code": null,
"e": 1922,
"s": 1838,
"text": "It opens the Connection/Session with Database software through Hibernate Framework."
},
{
"code": null,
"e": 1977,
"s": 1922,
"text": "It is a light-weight object and it is not thread-safe."
},
{
"code": null,
"e": 2068,
"s": 1977,
"text": "Session object is used to perform CRUD operations.Session session=factory.buildSession();\n"
},
{
"code": null,
"e": 2109,
"s": 2068,
"text": "Session session=factory.buildSession();\n"
},
{
"code": null,
"e": 2122,
"s": 2109,
"text": "Transaction:"
},
{
"code": null,
"e": 2247,
"s": 2122,
"text": "Transaction object is used whenever we perform any operation and based upon that operation there is some change in database."
},
{
"code": null,
"e": 2464,
"s": 2247,
"text": "Transaction object is used to give the instruction to the database to make the changes that happen because of operation as a permanent by using commit() method.Transaction tx=session.beginTransaction();\ntx.commit();\n"
},
{
"code": null,
"e": 2521,
"s": 2464,
"text": "Transaction tx=session.beginTransaction();\ntx.commit();\n"
},
{
"code": null,
"e": 2528,
"s": 2521,
"text": "Query:"
},
{
"code": null,
"e": 2593,
"s": 2528,
"text": "Query is an interface that present inside org.hibernate package."
},
{
"code": null,
"e": 2656,
"s": 2593,
"text": "A Query instance is obtained by calling Session.createQuery()."
},
{
"code": null,
"e": 2898,
"s": 2656,
"text": "This interface exposes some extra functionality beyond that provided by Session.iterate() and Session.find():A particular page of the result set may be selected by calling setMaxResults(), setFirstResult().Named query parameters may be used."
},
{
"code": null,
"e": 3031,
"s": 2898,
"text": "A particular page of the result set may be selected by calling setMaxResults(), setFirstResult().Named query parameters may be used."
},
{
"code": null,
"e": 3129,
"s": 3031,
"text": "A particular page of the result set may be selected by calling setMaxResults(), setFirstResult()."
},
{
"code": null,
"e": 3165,
"s": 3129,
"text": "Named query parameters may be used."
},
{
"code": null,
"e": 3201,
"s": 3165,
"text": "Query query=session.createQuery();\n"
},
{
"code": null,
"e": 3211,
"s": 3201,
"text": "Criteria:"
},
{
"code": null,
"e": 3296,
"s": 3211,
"text": "Criteria is a simplified API for retrieving entities by composing Criterion objects."
},
{
"code": null,
"e": 3417,
"s": 3296,
"text": "The Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on Restrictions."
},
{
"code": null,
"e": 3462,
"s": 3417,
"text": "Criteria criteria=session.createCriteria();\n"
},
{
"code": null,
"e": 3520,
"s": 3462,
"text": "Flow of working during operation in Hibernate Framework :"
},
{
"code": null,
"e": 4082,
"s": 3520,
"text": "Suppose We want to insert an Object to the database. Here Object is nothing but persistence logic which we write on java program and create an object of that program. If we want to insert that object in the database or we want to retrieve the object from the database. Now the question is that how hibernate save the Object to the database or retrieve the object from the database. There are several layers through which Hibernate framework go to achieve the above task. Let us understathe nd the layers/flow of Hibernate framework during performing operations:"
},
{
"code": null,
"e": 4369,
"s": 4082,
"text": "Stage I: In first stage, we will write the persistence logic to perform some specific operations to the database with the help of Hibernate Configuration file and Hibernate mapping file. And after that we create an object of the particular class on which we wrote the persistence logic."
},
{
"code": null,
"e": 4806,
"s": 4369,
"text": "Stage II:In second stage, our class which contains the persistence logic will interact with the hibernate framework where hibernate framework gives some abstraction do perform some task. Now here the picture of java class is over. Now Hibernate is responsible to perform the persistence logic with the help of layers which is below of Hibernate framework or we can say that the layers which are the internal implementation of Hibernate."
},
{
"code": null,
"e": 4948,
"s": 4806,
"text": "Stage III:In third stage, our hibernate framework interact which JDBC, JNDI, JTA etc to go to the database to perform that persistence logic."
},
{
"code": null,
"e": 5286,
"s": 4948,
"text": "Stage IV & V:In fourth & fifth stage, hibernate is interact with Database with the help of JDBC driver. Now here hibernate perform that persistence logic which is nothing but CRUD operation. If our persistence logic is to retrieve an record then in the reverse order it will display on the console of our java program in terms of Object."
},
{
"code": null,
"e": 5291,
"s": 5286,
"text": "JDBC"
},
{
"code": null,
"e": 5296,
"s": 5291,
"text": "Java"
},
{
"code": null,
"e": 5301,
"s": 5296,
"text": "Java"
}
] |
LinkedList clone() Method in Java
|
10 Dec, 2018
The Java.util.LinkedList.clone() method is used to create a shallow copy of the mentioned linked list. It just creates a copy of the list.
Syntax:
LinkedList.clone()
Parameters: This method does not take any parameters.
Return Value: This function returns a copy of the instance of Linked list.
Below program illustrate the Java.util.LinkedList.clone() method:
// Java code to illustrate clone() methodimport java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the list System.out.println("First LinkedList:" + list); // Creating another linked list and copying LinkedList sec_list = new LinkedList(); sec_list = (LinkedList) list.clone(); // Displaying the other linked list System.out.println("Second LinkedList is:" + sec_list); }}
First LinkedList:[Geeks, for, Geeks, 10, 20]
Second LinkedList is:[Geeks, for, Geeks, 10, 20]
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Abstraction in Java
HashSet in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "The Java.util.LinkedList.clone() method is used to create a shallow copy of the mentioned linked list. It just creates a copy of the list."
},
{
"code": null,
"e": 175,
"s": 167,
"text": "Syntax:"
},
{
"code": null,
"e": 194,
"s": 175,
"text": "LinkedList.clone()"
},
{
"code": null,
"e": 248,
"s": 194,
"text": "Parameters: This method does not take any parameters."
},
{
"code": null,
"e": 323,
"s": 248,
"text": "Return Value: This function returns a copy of the instance of Linked list."
},
{
"code": null,
"e": 389,
"s": 323,
"text": "Below program illustrate the Java.util.LinkedList.clone() method:"
},
{
"code": "// Java code to illustrate clone() methodimport java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Displaying the list System.out.println(\"First LinkedList:\" + list); // Creating another linked list and copying LinkedList sec_list = new LinkedList(); sec_list = (LinkedList) list.clone(); // Displaying the other linked list System.out.println(\"Second LinkedList is:\" + sec_list); }}",
"e": 1206,
"s": 389,
"text": null
},
{
"code": null,
"e": 1301,
"s": 1206,
"text": "First LinkedList:[Geeks, for, Geeks, 10, 20]\nSecond LinkedList is:[Geeks, for, Geeks, 10, 20]\n"
},
{
"code": null,
"e": 1321,
"s": 1301,
"text": "Java - util package"
},
{
"code": null,
"e": 1338,
"s": 1321,
"text": "Java-Collections"
},
{
"code": null,
"e": 1353,
"s": 1338,
"text": "Java-Functions"
},
{
"code": null,
"e": 1369,
"s": 1353,
"text": "java-LinkedList"
},
{
"code": null,
"e": 1374,
"s": 1369,
"text": "Java"
},
{
"code": null,
"e": 1379,
"s": 1374,
"text": "Java"
},
{
"code": null,
"e": 1396,
"s": 1379,
"text": "Java-Collections"
},
{
"code": null,
"e": 1494,
"s": 1396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1509,
"s": 1494,
"text": "Stream In Java"
},
{
"code": null,
"e": 1530,
"s": 1509,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1551,
"s": 1530,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1570,
"s": 1551,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1587,
"s": 1570,
"text": "Generics in Java"
},
{
"code": null,
"e": 1617,
"s": 1587,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 1643,
"s": 1617,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1659,
"s": 1643,
"text": "Strings in Java"
},
{
"code": null,
"e": 1679,
"s": 1659,
"text": "Abstraction in Java"
}
] |
JODA-Time
|
07 Aug, 2018
Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java.util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.time package.
To include we need to import following :
import java.time.*;
Basic Features of JODA-TIME
It uses easy field accessors like getYear(), getDayOfWeek(), getDayofYear().
It supports 7 Calendar Systems like Buddhist, Coptic, Ethiopic, Gregorian, GregorianJulian, Islamic, Julian.
There is a Provision to create our own Calendar system.
It Provides rich Set of Methods for date and Time calculations.
It uses a database for time zones. This database updated manually several times in a year.
Its Methods executes faster compared to earlier methods of java 7.0; thus, provides better performance
Its Objects are immutable. So, they are thread-safe
Important Classes in java.time package.
DateTime : Immutable replacement for JDK Calendar. DateTime dt = new DateTime(); // which creates a datetime object representing the current date and time in milliseconds as determined by the system clock. It is constructed using the ISO calendar in the default time zone.LocalDate :This class represents a date in the form of year-month-day and useful for representing a date without time and time zone.LocalDate today = LocalDate.now()
//gives System date into LocalDate object using now method.
System.out.println(today)
// 2018-08-03
int d = today.getDayOfMonth();
// 03
LocalTime : This class represents the time of the day without time zone.LocalTime time = LocalTime.now(); //gives System time into localTime object
System.out.println(time); // 10:19:58
LocalDateTime : This class handles both date and time without considering the time zone.// get current date and time
LocalDateTime dt = LocalTime.now();
System.out.println("%s", dt);
Setting up EnvironmentCreate your java project in eclipse.Download the latest JodaTime .tar.gz file Click Here, and extract its contents.In Eclipse, look for your project at package explorer and right click on it then call it New -> Folder -> libsCopy/Drag joda-time-2.1.jar into the new created libs folder.Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1.jarNow you can test with this code :DateTime test = new DateTime();Basic Example// Java program to illustrate// functions of JODA timeimport org.joda.time.DateTime;import org.joda.time.LocalDateTime;public class JodaTime { public static void main(String[] args) { DateTime now = new DateTime(); System.out.println("Current Day: " + now.dayOfWeek().getAsText()); System.out.println("Current Month: " + now.monthOfYear().getAsText()); System.out.println("Current Year: " + now.year().getAsText()); System.out.println("Current Year is Leap Year: " + now.year().isLeap()); // get current date and time LocalDateTime dt = LocalDateTime.now(); System.out.println(dt); }}OutputCurrent Day: Monday
Current Month: August
Current Year: 2018
Current Year is Leap Year: false
2018-08-06T13:12:16.672
Advantages:Similar usage across multiple Java platforms.Supports additional calendars such as Buddhist and Ethiopic.Self-reported better performance.Easy interoperability: The library internally uses a millisecond instant which is identical to the JDK and similar to other common time representations. This makes interoperability easy, and Joda-Time comes with out-of-the-box JDK interoperability.Disadvantages:Requires installation of package and perhaps updates from Joda.org.ReferencesHierarchy For Package org.joda.timehttp://www.joda.org/joda-time/http://www.joda.org/joda-time/quickstart.htmlMy Personal Notes
arrow_drop_upSave
DateTime : Immutable replacement for JDK Calendar. DateTime dt = new DateTime(); // which creates a datetime object representing the current date and time in milliseconds as determined by the system clock. It is constructed using the ISO calendar in the default time zone.
DateTime dt = new DateTime();
// which creates a datetime object representing the current date and time in milliseconds as determined by the system clock. It is constructed using the ISO calendar in the default time zone.
LocalDate :This class represents a date in the form of year-month-day and useful for representing a date without time and time zone.LocalDate today = LocalDate.now()
//gives System date into LocalDate object using now method.
System.out.println(today)
// 2018-08-03
int d = today.getDayOfMonth();
// 03
LocalDate today = LocalDate.now()
//gives System date into LocalDate object using now method.
System.out.println(today)
// 2018-08-03
int d = today.getDayOfMonth();
// 03
LocalTime : This class represents the time of the day without time zone.LocalTime time = LocalTime.now(); //gives System time into localTime object
System.out.println(time); // 10:19:58
LocalTime time = LocalTime.now(); //gives System time into localTime object
System.out.println(time); // 10:19:58
LocalDateTime : This class handles both date and time without considering the time zone.// get current date and time
LocalDateTime dt = LocalTime.now();
System.out.println("%s", dt);
// get current date and time
LocalDateTime dt = LocalTime.now();
System.out.println("%s", dt);
Setting up Environment
Create your java project in eclipse.Download the latest JodaTime .tar.gz file Click Here, and extract its contents.In Eclipse, look for your project at package explorer and right click on it then call it New -> Folder -> libsCopy/Drag joda-time-2.1.jar into the new created libs folder.Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1.jarNow you can test with this code :DateTime test = new DateTime();
Create your java project in eclipse.
Download the latest JodaTime .tar.gz file Click Here, and extract its contents.
In Eclipse, look for your project at package explorer and right click on it then call it New -> Folder -> libs
Copy/Drag joda-time-2.1.jar into the new created libs folder.
Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1.jar
Now you can test with this code :DateTime test = new DateTime();
DateTime test = new DateTime();
Basic Example
// Java program to illustrate// functions of JODA timeimport org.joda.time.DateTime;import org.joda.time.LocalDateTime;public class JodaTime { public static void main(String[] args) { DateTime now = new DateTime(); System.out.println("Current Day: " + now.dayOfWeek().getAsText()); System.out.println("Current Month: " + now.monthOfYear().getAsText()); System.out.println("Current Year: " + now.year().getAsText()); System.out.println("Current Year is Leap Year: " + now.year().isLeap()); // get current date and time LocalDateTime dt = LocalDateTime.now(); System.out.println(dt); }}
Output
Current Day: Monday
Current Month: August
Current Year: 2018
Current Year is Leap Year: false
2018-08-06T13:12:16.672
Advantages:
Similar usage across multiple Java platforms.
Supports additional calendars such as Buddhist and Ethiopic.
Self-reported better performance.
Easy interoperability: The library internally uses a millisecond instant which is identical to the JDK and similar to other common time representations. This makes interoperability easy, and Joda-Time comes with out-of-the-box JDK interoperability.
Disadvantages:
Requires installation of package and perhaps updates from Joda.org.
ReferencesHierarchy For Package org.joda.timehttp://www.joda.org/joda-time/http://www.joda.org/joda-time/quickstart.html
Java - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Strings in Java
Different ways of Reading a text file in Java
Reverse an array in Java
How to remove an element from ArrayList in Java?
Checked vs Unchecked Exceptions in Java
ArrayList get(index) Method in Java with Examples
ArrayList to Array Conversion in Java : toArray() Methods
Comparator Interface in Java with Examples
Exceptions in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Aug, 2018"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java.util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.time package."
},
{
"code": null,
"e": 333,
"s": 292,
"text": "To include we need to import following :"
},
{
"code": null,
"e": 353,
"s": 333,
"text": "import java.time.*;"
},
{
"code": null,
"e": 381,
"s": 353,
"text": "Basic Features of JODA-TIME"
},
{
"code": null,
"e": 458,
"s": 381,
"text": "It uses easy field accessors like getYear(), getDayOfWeek(), getDayofYear()."
},
{
"code": null,
"e": 567,
"s": 458,
"text": "It supports 7 Calendar Systems like Buddhist, Coptic, Ethiopic, Gregorian, GregorianJulian, Islamic, Julian."
},
{
"code": null,
"e": 623,
"s": 567,
"text": "There is a Provision to create our own Calendar system."
},
{
"code": null,
"e": 687,
"s": 623,
"text": "It Provides rich Set of Methods for date and Time calculations."
},
{
"code": null,
"e": 778,
"s": 687,
"text": "It uses a database for time zones. This database updated manually several times in a year."
},
{
"code": null,
"e": 881,
"s": 778,
"text": "Its Methods executes faster compared to earlier methods of java 7.0; thus, provides better performance"
},
{
"code": null,
"e": 933,
"s": 881,
"text": "Its Objects are immutable. So, they are thread-safe"
},
{
"code": null,
"e": 973,
"s": 933,
"text": "Important Classes in java.time package."
},
{
"code": null,
"e": 3856,
"s": 973,
"text": "DateTime : Immutable replacement for JDK Calendar. DateTime dt = new DateTime(); // which creates a datetime object representing the current date and time in milliseconds as determined by the system clock. It is constructed using the ISO calendar in the default time zone.LocalDate :This class represents a date in the form of year-month-day and useful for representing a date without time and time zone.LocalDate today = LocalDate.now()\n//gives System date into LocalDate object using now method.\n\nSystem.out.println(today) \n// 2018-08-03\nint d = today.getDayOfMonth(); \n// 03\nLocalTime : This class represents the time of the day without time zone.LocalTime time = LocalTime.now(); //gives System time into localTime object\nSystem.out.println(time); // 10:19:58\nLocalDateTime : This class handles both date and time without considering the time zone.// get current date and time\nLocalDateTime dt = LocalTime.now(); \nSystem.out.println(\"%s\", dt);\nSetting up EnvironmentCreate your java project in eclipse.Download the latest JodaTime .tar.gz file Click Here, and extract its contents.In Eclipse, look for your project at package explorer and right click on it then call it New -> Folder -> libsCopy/Drag joda-time-2.1.jar into the new created libs folder.Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1.jarNow you can test with this code :DateTime test = new DateTime();Basic Example// Java program to illustrate// functions of JODA timeimport org.joda.time.DateTime;import org.joda.time.LocalDateTime;public class JodaTime { public static void main(String[] args) { DateTime now = new DateTime(); System.out.println(\"Current Day: \" + now.dayOfWeek().getAsText()); System.out.println(\"Current Month: \" + now.monthOfYear().getAsText()); System.out.println(\"Current Year: \" + now.year().getAsText()); System.out.println(\"Current Year is Leap Year: \" + now.year().isLeap()); // get current date and time LocalDateTime dt = LocalDateTime.now(); System.out.println(dt); }}OutputCurrent Day: Monday\nCurrent Month: August\nCurrent Year: 2018\nCurrent Year is Leap Year: false\n2018-08-06T13:12:16.672\nAdvantages:Similar usage across multiple Java platforms.Supports additional calendars such as Buddhist and Ethiopic.Self-reported better performance.Easy interoperability: The library internally uses a millisecond instant which is identical to the JDK and similar to other common time representations. This makes interoperability easy, and Joda-Time comes with out-of-the-box JDK interoperability.Disadvantages:Requires installation of package and perhaps updates from Joda.org.ReferencesHierarchy For Package org.joda.timehttp://www.joda.org/joda-time/http://www.joda.org/joda-time/quickstart.htmlMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4132,
"s": 3856,
"text": "DateTime : Immutable replacement for JDK Calendar. DateTime dt = new DateTime(); // which creates a datetime object representing the current date and time in milliseconds as determined by the system clock. It is constructed using the ISO calendar in the default time zone."
},
{
"code": null,
"e": 4167,
"s": 4132,
"text": " DateTime dt = new DateTime(); "
},
{
"code": null,
"e": 4359,
"s": 4167,
"text": "// which creates a datetime object representing the current date and time in milliseconds as determined by the system clock. It is constructed using the ISO calendar in the default time zone."
},
{
"code": null,
"e": 4666,
"s": 4359,
"text": "LocalDate :This class represents a date in the form of year-month-day and useful for representing a date without time and time zone.LocalDate today = LocalDate.now()\n//gives System date into LocalDate object using now method.\n\nSystem.out.println(today) \n// 2018-08-03\nint d = today.getDayOfMonth(); \n// 03\n"
},
{
"code": null,
"e": 4841,
"s": 4666,
"text": "LocalDate today = LocalDate.now()\n//gives System date into LocalDate object using now method.\n\nSystem.out.println(today) \n// 2018-08-03\nint d = today.getDayOfMonth(); \n// 03\n"
},
{
"code": null,
"e": 5028,
"s": 4841,
"text": "LocalTime : This class represents the time of the day without time zone.LocalTime time = LocalTime.now(); //gives System time into localTime object\nSystem.out.println(time); // 10:19:58\n"
},
{
"code": null,
"e": 5143,
"s": 5028,
"text": "LocalTime time = LocalTime.now(); //gives System time into localTime object\nSystem.out.println(time); // 10:19:58\n"
},
{
"code": null,
"e": 5328,
"s": 5143,
"text": "LocalDateTime : This class handles both date and time without considering the time zone.// get current date and time\nLocalDateTime dt = LocalTime.now(); \nSystem.out.println(\"%s\", dt);\n"
},
{
"code": null,
"e": 5425,
"s": 5328,
"text": "// get current date and time\nLocalDateTime dt = LocalTime.now(); \nSystem.out.println(\"%s\", dt);\n"
},
{
"code": null,
"e": 5448,
"s": 5425,
"text": "Setting up Environment"
},
{
"code": null,
"e": 5935,
"s": 5448,
"text": "Create your java project in eclipse.Download the latest JodaTime .tar.gz file Click Here, and extract its contents.In Eclipse, look for your project at package explorer and right click on it then call it New -> Folder -> libsCopy/Drag joda-time-2.1.jar into the new created libs folder.Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1.jarNow you can test with this code :DateTime test = new DateTime();"
},
{
"code": null,
"e": 5972,
"s": 5935,
"text": "Create your java project in eclipse."
},
{
"code": null,
"e": 6052,
"s": 5972,
"text": "Download the latest JodaTime .tar.gz file Click Here, and extract its contents."
},
{
"code": null,
"e": 6163,
"s": 6052,
"text": "In Eclipse, look for your project at package explorer and right click on it then call it New -> Folder -> libs"
},
{
"code": null,
"e": 6225,
"s": 6163,
"text": "Copy/Drag joda-time-2.1.jar into the new created libs folder."
},
{
"code": null,
"e": 6362,
"s": 6225,
"text": "Right click on your project again (in package explorer) then Properties -> Java Build Path -> Libraries -> Add Jars -> joda-time-2.1.jar"
},
{
"code": null,
"e": 6427,
"s": 6362,
"text": "Now you can test with this code :DateTime test = new DateTime();"
},
{
"code": null,
"e": 6459,
"s": 6427,
"text": "DateTime test = new DateTime();"
},
{
"code": null,
"e": 6473,
"s": 6459,
"text": "Basic Example"
},
{
"code": "// Java program to illustrate// functions of JODA timeimport org.joda.time.DateTime;import org.joda.time.LocalDateTime;public class JodaTime { public static void main(String[] args) { DateTime now = new DateTime(); System.out.println(\"Current Day: \" + now.dayOfWeek().getAsText()); System.out.println(\"Current Month: \" + now.monthOfYear().getAsText()); System.out.println(\"Current Year: \" + now.year().getAsText()); System.out.println(\"Current Year is Leap Year: \" + now.year().isLeap()); // get current date and time LocalDateTime dt = LocalDateTime.now(); System.out.println(dt); }}",
"e": 7127,
"s": 6473,
"text": null
},
{
"code": null,
"e": 7134,
"s": 7127,
"text": "Output"
},
{
"code": null,
"e": 7253,
"s": 7134,
"text": "Current Day: Monday\nCurrent Month: August\nCurrent Year: 2018\nCurrent Year is Leap Year: false\n2018-08-06T13:12:16.672\n"
},
{
"code": null,
"e": 7265,
"s": 7253,
"text": "Advantages:"
},
{
"code": null,
"e": 7311,
"s": 7265,
"text": "Similar usage across multiple Java platforms."
},
{
"code": null,
"e": 7372,
"s": 7311,
"text": "Supports additional calendars such as Buddhist and Ethiopic."
},
{
"code": null,
"e": 7406,
"s": 7372,
"text": "Self-reported better performance."
},
{
"code": null,
"e": 7655,
"s": 7406,
"text": "Easy interoperability: The library internally uses a millisecond instant which is identical to the JDK and similar to other common time representations. This makes interoperability easy, and Joda-Time comes with out-of-the-box JDK interoperability."
},
{
"code": null,
"e": 7670,
"s": 7655,
"text": "Disadvantages:"
},
{
"code": null,
"e": 7738,
"s": 7670,
"text": "Requires installation of package and perhaps updates from Joda.org."
},
{
"code": null,
"e": 7859,
"s": 7738,
"text": "ReferencesHierarchy For Package org.joda.timehttp://www.joda.org/joda-time/http://www.joda.org/joda-time/quickstart.html"
},
{
"code": null,
"e": 7879,
"s": 7859,
"text": "Java - util package"
},
{
"code": null,
"e": 7884,
"s": 7879,
"text": "Java"
},
{
"code": null,
"e": 7889,
"s": 7884,
"text": "Java"
},
{
"code": null,
"e": 7987,
"s": 7889,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8024,
"s": 7987,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 8040,
"s": 8024,
"text": "Strings in Java"
},
{
"code": null,
"e": 8086,
"s": 8040,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 8111,
"s": 8086,
"text": "Reverse an array in Java"
},
{
"code": null,
"e": 8160,
"s": 8111,
"text": "How to remove an element from ArrayList in Java?"
},
{
"code": null,
"e": 8200,
"s": 8160,
"text": "Checked vs Unchecked Exceptions in Java"
},
{
"code": null,
"e": 8250,
"s": 8200,
"text": "ArrayList get(index) Method in Java with Examples"
},
{
"code": null,
"e": 8308,
"s": 8250,
"text": "ArrayList to Array Conversion in Java : toArray() Methods"
},
{
"code": null,
"e": 8351,
"s": 8308,
"text": "Comparator Interface in Java with Examples"
}
] |
C++ Program for Sum of squares of first n natural numbers
|
16 Dec, 2021
Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2.
Examples:
Input : N = 4
Output : 30
12 + 22 + 32 + 42
= 1 + 4 + 9 + 16
= 30
Input : N = 5
Output : 55
Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum.
CPP
// CPP Program to find sum of square of first n natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of the square // of first n natural numbersint squaresum(int n){ // Iterate i from 1 and n // finding square of i and add to sum. int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum;} // Driven Programint main(){ int n = 4; cout << squaresum(n) << endl; return 0;}
30
Method 2: O(1)Proof:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
We know,
(k + 1)3 = k3 + 3 * k2 + 3 * k + 1
We can write the above identity for k from 1 to n:
23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1)
33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2)
43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3)
53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4)
...
n3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1)
(n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n)
Putting equation (n - 1) in equation n,
(n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1
= (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1
By putting all equation, we get
(n + 1)3 = 13 + 3 * Σ k2 + 3 * Σ k + Σ 1
n3 + 3 * n2 + 3 * n + 1 = 1 + 3 * Σ k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 3 * n = 3 * Σ k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n + 1) * (n + 2 - 3/2) = 3 * Σ k2
n * (n + 1) * (2 * n + 1)/2 = 3 * Σ k2
n * (n + 1) * (2 * n + 1)/6 = Σ k2
CPP
// CPP Program to find sum// of square of first n// natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of square of// first n natural numbersint squaresum(int n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driven Programint main(){ int n = 4; cout << squaresum(n) << endl; return 0;}
30
Avoiding early overflow:For large n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid overflow up to some extent using the fact that n*(n+1) must be divisible by 2.
CPP
// CPP Program to find sum of square of first// n natural numbers. This program avoids// overflow upto some extent for large value// of n.#include <bits/stdc++.h>using namespace std; // Return the sum of square of first n natural// numbersint squaresum(int n){ return (n * (n + 1) / 2) * (2 * n + 1) / 3;} // Driven Programint main(){ int n = 4; cout << squaresum(n) << endl; return 0;}
30
Please refer complete article on Sum of squares of first n natural numbers for more details!
varshagumber28
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Different ways to print elements of vector
Dynamic _Cast in C++
string::npos in C++ with Examples
Why it is important to write "using namespace std" in C++ program?
How to convert a Vector to Set in C++
Maximum value of long long int in C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2."
},
{
"code": null,
"e": 113,
"s": 103,
"text": "Examples:"
},
{
"code": null,
"e": 207,
"s": 113,
"text": "Input : N = 4\nOutput : 30\n12 + 22 + 32 + 42\n= 1 + 4 + 9 + 16\n= 30\n\nInput : N = 5\nOutput : 55\n"
},
{
"code": null,
"e": 305,
"s": 207,
"text": "Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum."
},
{
"code": null,
"e": 309,
"s": 305,
"text": "CPP"
},
{
"code": "// CPP Program to find sum of square of first n natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of the square // of first n natural numbersint squaresum(int n){ // Iterate i from 1 and n // finding square of i and add to sum. int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum;} // Driven Programint main(){ int n = 4; cout << squaresum(n) << endl; return 0;}",
"e": 750,
"s": 309,
"text": null
},
{
"code": null,
"e": 754,
"s": 750,
"text": "30\n"
},
{
"code": null,
"e": 775,
"s": 754,
"text": "Method 2: O(1)Proof:"
},
{
"code": null,
"e": 784,
"s": 775,
"text": "Chapters"
},
{
"code": null,
"e": 811,
"s": 784,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 861,
"s": 811,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 884,
"s": 861,
"text": "captions off, selected"
},
{
"code": null,
"e": 892,
"s": 884,
"text": "English"
},
{
"code": null,
"e": 916,
"s": 892,
"text": "This is a modal window."
},
{
"code": null,
"e": 985,
"s": 916,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1007,
"s": 985,
"text": "End of dialog window."
},
{
"code": null,
"e": 2053,
"s": 1007,
"text": "We know,\n(k + 1)3 = k3 + 3 * k2 + 3 * k + 1\nWe can write the above identity for k from 1 to n:\n23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1)\n33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2)\n43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3)\n53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4)\n...\nn3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1)\n(n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n)\n\nPutting equation (n - 1) in equation n,\n(n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1\n = (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1\n\nBy putting all equation, we get\n(n + 1)3 = 13 + 3 * Σ k2 + 3 * Σ k + Σ 1\nn3 + 3 * n2 + 3 * n + 1 = 1 + 3 * Σ k2 + 3 * (n * (n + 1))/2 + n\nn3 + 3 * n2 + 3 * n = 3 * Σ k2 + 3 * (n * (n + 1))/2 + n\nn3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n + 1) * (n + 2 - 3/2) = 3 * Σ k2\nn * (n + 1) * (2 * n + 1)/2 = 3 * Σ k2\nn * (n + 1) * (2 * n + 1)/6 = Σ k2\n"
},
{
"code": null,
"e": 2057,
"s": 2053,
"text": "CPP"
},
{
"code": "// CPP Program to find sum// of square of first n// natural numbers#include <bits/stdc++.h>using namespace std; // Return the sum of square of// first n natural numbersint squaresum(int n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driven Programint main(){ int n = 4; cout << squaresum(n) << endl; return 0;}",
"e": 2383,
"s": 2057,
"text": null
},
{
"code": null,
"e": 2387,
"s": 2383,
"text": "30\n"
},
{
"code": null,
"e": 2573,
"s": 2387,
"text": "Avoiding early overflow:For large n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid overflow up to some extent using the fact that n*(n+1) must be divisible by 2."
},
{
"code": null,
"e": 2577,
"s": 2573,
"text": "CPP"
},
{
"code": "// CPP Program to find sum of square of first// n natural numbers. This program avoids// overflow upto some extent for large value// of n.#include <bits/stdc++.h>using namespace std; // Return the sum of square of first n natural// numbersint squaresum(int n){ return (n * (n + 1) / 2) * (2 * n + 1) / 3;} // Driven Programint main(){ int n = 4; cout << squaresum(n) << endl; return 0;}",
"e": 2978,
"s": 2577,
"text": null
},
{
"code": null,
"e": 2982,
"s": 2978,
"text": "30\n"
},
{
"code": null,
"e": 3075,
"s": 2982,
"text": "Please refer complete article on Sum of squares of first n natural numbers for more details!"
},
{
"code": null,
"e": 3090,
"s": 3075,
"text": "varshagumber28"
},
{
"code": null,
"e": 3103,
"s": 3090,
"text": "C++ Programs"
},
{
"code": null,
"e": 3201,
"s": 3103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3242,
"s": 3201,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 3263,
"s": 3242,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 3275,
"s": 3263,
"text": "cout in C++"
},
{
"code": null,
"e": 3334,
"s": 3275,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 3377,
"s": 3334,
"text": "Different ways to print elements of vector"
},
{
"code": null,
"e": 3398,
"s": 3377,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 3432,
"s": 3398,
"text": "string::npos in C++ with Examples"
},
{
"code": null,
"e": 3499,
"s": 3432,
"text": "Why it is important to write \"using namespace std\" in C++ program?"
},
{
"code": null,
"e": 3537,
"s": 3499,
"text": "How to convert a Vector to Set in C++"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.