title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Recursive program to print all subsets with given sum | 12 Jul, 2021
Given an array and a number, print all subsets with sum equal to given the sum.Examples:
Input : arr[] = {2, 5, 8, 4, 6, 11}, sum = 13
Output :
5 8
2 11
2 5 6
Input : arr[] = {1, 5, 8, 4, 6, 11}, sum = 9
Output :
5 4
1 8
This problem is an extension of check if there is a subset with given sum. We recursively generate all subsets. We keep track of elements of current subset. If sum of elements in current subset becomes equal to given sum, we print the subset.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print all subsets with given sum#include <bits/stdc++.h>using namespace std; // The vector v stores current subset.void printAllSubsetsRec(int arr[], int n, vector<int> v, int sum){ // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (auto x : v) cout << x << " "; cout << endl; return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); v.push_back(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1]);} // Wrapper over printAllSubsetsRec()void printAllSubsets(int arr[], int n, int sum){ vector<int> v; printAllSubsetsRec(arr, n, v, sum);} // Driver codeint main(){ int arr[] = { 2, 5, 8, 4, 6, 11 }; int sum = 13; int n = sizeof(arr) / sizeof(arr[0]); printAllSubsets(arr, n, sum); return 0;}
// Java program to print all subsets with given sumimport java.util.*; class Solution{ // The vector v stores current subset.static void printAllSubsetsRec(int arr[], int n, Vector<Integer> v, int sum){ // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (int i=0;i<v.size();i++) System.out.print( v.get(i) + " "); System.out.println(); return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); Vector<Integer> v1=new Vector<Integer>(v); v1.add(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]);} // Wrapper over printAllSubsetsRec()static void printAllSubsets(int arr[], int n, int sum){ Vector<Integer> v= new Vector<Integer>(); printAllSubsetsRec(arr, n, v, sum);} // Driver codepublic static void main(String args[]){ int arr[] = { 2, 5, 8, 4, 6, 11 }; int sum = 13; int n = arr.length; printAllSubsets(arr, n, sum); }}//contributed by Arnab Kundu
# Python program to print all subsets with given sum # The vector v stores current subset.def printAllSubsetsRec(arr, n, v, sum) : # If remaining sum is 0, then print all # elements of current subset. if (sum == 0) : for value in v : print(value, end=" ") print() return # If no remaining elements, if (n == 0): return # We consider two cases for every element. # a) We do not include last element. # b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum) v1 = [] + v v1.append(arr[n - 1]) printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]) # Wrapper over printAllSubsetsRec()def printAllSubsets(arr, n, sum): v = [] printAllSubsetsRec(arr, n, v, sum) # Driver code arr = [ 2, 5, 8, 4, 6, 11 ]sum = 13n = len(arr)printAllSubsets(arr, n, sum) # This code is contributed by ihritik
// C# program to print all subsets with given sumusing System;using System.Collections.Generic; class GFG{ // The vector v stores current subset. static void printAllSubsetsRec(int []arr, int n, List<int> v, int sum) { // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (int i = 0; i < v.Count; i++) Console.Write( v[i]+ " "); Console.WriteLine(); return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); List<int> v1 = new List<int>(v); v1.Add(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]); } // Wrapper over printAllSubsetsRec() static void printAllSubsets(int []arr, int n, int sum) { List<int> v = new List<int>(); printAllSubsetsRec(arr, n, v, sum); } // Driver code public static void Main() { int []arr = { 2, 5, 8, 4, 6, 11 }; int sum = 13; int n = arr.Length; printAllSubsets(arr, n, sum); }} // This code is contributed by Rajput-Ji
<?php// PHP program to print all subsets with given sum // The vector v stores current subset.function printAllSubsetsRec($arr, $n, $v, $sum){ // If remaining sum is 0, then print all // elements of current subset. if ($sum == 0) { for ($i = 0; $i < count($v); $i++) echo $v[$i] . " "; echo "\n"; return; } // If no remaining elements, if ($n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec($arr, $n - 1, $v, $sum); array_push($v, $arr[$n - 1]); printAllSubsetsRec($arr, $n - 1, $v, $sum - $arr[$n - 1]);} // Wrapper over printAllSubsetsRec()function printAllSubsets($arr, $n, $sum){ $v = array(); printAllSubsetsRec($arr, $n, $v, $sum);} // Driver code$arr = array( 2, 5, 8, 4, 6, 11 );$sum = 13;$n = count($arr);printAllSubsets($arr, $n, $sum); // This code is contributed by mits?>
<script> // JavaScript Program for the above approach // The vector v stores current subset. function printAllSubsetsRec(arr, n, v, sum) { // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (let x of v) document.write(x + " "); document.write("<br>") return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); v.push(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1]); v.pop(); } // Wrapper over printAllSubsetsRec() function printAllSubsets(arr, n, sum) { let v = []; printAllSubsetsRec(arr, n, v, sum); } // Driver code let arr = [2, 5, 8, 4, 6, 11]; let sum = 13; let n = arr.length; printAllSubsets(arr, n, sum); // This code is contributed by Potta Lokesh </script>
8 5
6 5 2
11 2
Time Complexity : O(2n)Please refer below post for an optimized solution based on Dynamic Programming. Print all subsets with given sum using Dynamic Programming
andrew1234
Rajput-Ji
ihritik
Mithun Kumar
lokeshpotta20
subset
Recursion
Recursion
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible combinations of r elements in a given array of size n
Reverse a stack using recursion
Write a program to reverse digits of a number
Recursive Practice Problems with Solutions
Sum of digit of a number using recursion
3 Different ways to print Fibonacci series in Java
Check if a number is Palindrome | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 145,
"s": 54,
"text": "Given an array and a number, print all subsets with sum equal to given the sum.Examples: "
},
{
"code": null,
"e": 282,
"s": 145,
"text": "Input : arr[] = {2, 5, 8, 4, 6, 11}, sum = 13\nOutput : \n5 8\n2 11\n2 5 6\n\nInput : arr[] = {1, 5, 8, 4, 6, 11}, sum = 9\nOutput :\n5 4\n1 8"
},
{
"code": null,
"e": 529,
"s": 284,
"text": "This problem is an extension of check if there is a subset with given sum. We recursively generate all subsets. We keep track of elements of current subset. If sum of elements in current subset becomes equal to given sum, we print the subset. "
},
{
"code": null,
"e": 533,
"s": 529,
"text": "C++"
},
{
"code": null,
"e": 538,
"s": 533,
"text": "Java"
},
{
"code": null,
"e": 546,
"s": 538,
"text": "Python3"
},
{
"code": null,
"e": 549,
"s": 546,
"text": "C#"
},
{
"code": null,
"e": 553,
"s": 549,
"text": "PHP"
},
{
"code": null,
"e": 564,
"s": 553,
"text": "Javascript"
},
{
"code": "// CPP program to print all subsets with given sum#include <bits/stdc++.h>using namespace std; // The vector v stores current subset.void printAllSubsetsRec(int arr[], int n, vector<int> v, int sum){ // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (auto x : v) cout << x << \" \"; cout << endl; return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); v.push_back(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1]);} // Wrapper over printAllSubsetsRec()void printAllSubsets(int arr[], int n, int sum){ vector<int> v; printAllSubsetsRec(arr, n, v, sum);} // Driver codeint main(){ int arr[] = { 2, 5, 8, 4, 6, 11 }; int sum = 13; int n = sizeof(arr) / sizeof(arr[0]); printAllSubsets(arr, n, sum); return 0;}",
"e": 1622,
"s": 564,
"text": null
},
{
"code": "// Java program to print all subsets with given sumimport java.util.*; class Solution{ // The vector v stores current subset.static void printAllSubsetsRec(int arr[], int n, Vector<Integer> v, int sum){ // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (int i=0;i<v.size();i++) System.out.print( v.get(i) + \" \"); System.out.println(); return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); Vector<Integer> v1=new Vector<Integer>(v); v1.add(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]);} // Wrapper over printAllSubsetsRec()static void printAllSubsets(int arr[], int n, int sum){ Vector<Integer> v= new Vector<Integer>(); printAllSubsetsRec(arr, n, v, sum);} // Driver codepublic static void main(String args[]){ int arr[] = { 2, 5, 8, 4, 6, 11 }; int sum = 13; int n = arr.length; printAllSubsets(arr, n, sum); }}//contributed by Arnab Kundu",
"e": 2827,
"s": 1622,
"text": null
},
{
"code": "# Python program to print all subsets with given sum # The vector v stores current subset.def printAllSubsetsRec(arr, n, v, sum) : # If remaining sum is 0, then print all # elements of current subset. if (sum == 0) : for value in v : print(value, end=\" \") print() return # If no remaining elements, if (n == 0): return # We consider two cases for every element. # a) We do not include last element. # b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum) v1 = [] + v v1.append(arr[n - 1]) printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]) # Wrapper over printAllSubsetsRec()def printAllSubsets(arr, n, sum): v = [] printAllSubsetsRec(arr, n, v, sum) # Driver code arr = [ 2, 5, 8, 4, 6, 11 ]sum = 13n = len(arr)printAllSubsets(arr, n, sum) # This code is contributed by ihritik",
"e": 3731,
"s": 2827,
"text": null
},
{
"code": "// C# program to print all subsets with given sumusing System;using System.Collections.Generic; class GFG{ // The vector v stores current subset. static void printAllSubsetsRec(int []arr, int n, List<int> v, int sum) { // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (int i = 0; i < v.Count; i++) Console.Write( v[i]+ \" \"); Console.WriteLine(); return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); List<int> v1 = new List<int>(v); v1.Add(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]); } // Wrapper over printAllSubsetsRec() static void printAllSubsets(int []arr, int n, int sum) { List<int> v = new List<int>(); printAllSubsetsRec(arr, n, v, sum); } // Driver code public static void Main() { int []arr = { 2, 5, 8, 4, 6, 11 }; int sum = 13; int n = arr.Length; printAllSubsets(arr, n, sum); }} // This code is contributed by Rajput-Ji",
"e": 5082,
"s": 3731,
"text": null
},
{
"code": "<?php// PHP program to print all subsets with given sum // The vector v stores current subset.function printAllSubsetsRec($arr, $n, $v, $sum){ // If remaining sum is 0, then print all // elements of current subset. if ($sum == 0) { for ($i = 0; $i < count($v); $i++) echo $v[$i] . \" \"; echo \"\\n\"; return; } // If no remaining elements, if ($n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec($arr, $n - 1, $v, $sum); array_push($v, $arr[$n - 1]); printAllSubsetsRec($arr, $n - 1, $v, $sum - $arr[$n - 1]);} // Wrapper over printAllSubsetsRec()function printAllSubsets($arr, $n, $sum){ $v = array(); printAllSubsetsRec($arr, $n, $v, $sum);} // Driver code$arr = array( 2, 5, 8, 4, 6, 11 );$sum = 13;$n = count($arr);printAllSubsets($arr, $n, $sum); // This code is contributed by mits?>",
"e": 6091,
"s": 5082,
"text": null
},
{
"code": "<script> // JavaScript Program for the above approach // The vector v stores current subset. function printAllSubsetsRec(arr, n, v, sum) { // If remaining sum is 0, then print all // elements of current subset. if (sum == 0) { for (let x of v) document.write(x + \" \"); document.write(\"<br>\") return; } // If no remaining elements, if (n == 0) return; // We consider two cases for every element. // a) We do not include last element. // b) We include last element in current subset. printAllSubsetsRec(arr, n - 1, v, sum); v.push(arr[n - 1]); printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1]); v.pop(); } // Wrapper over printAllSubsetsRec() function printAllSubsets(arr, n, sum) { let v = []; printAllSubsetsRec(arr, n, v, sum); } // Driver code let arr = [2, 5, 8, 4, 6, 11]; let sum = 13; let n = arr.length; printAllSubsets(arr, n, sum); // This code is contributed by Potta Lokesh </script>",
"e": 7328,
"s": 6091,
"text": null
},
{
"code": null,
"e": 7345,
"s": 7328,
"text": "8 5 \n6 5 2 \n11 2"
},
{
"code": null,
"e": 7510,
"s": 7347,
"text": "Time Complexity : O(2n)Please refer below post for an optimized solution based on Dynamic Programming. Print all subsets with given sum using Dynamic Programming "
},
{
"code": null,
"e": 7521,
"s": 7510,
"text": "andrew1234"
},
{
"code": null,
"e": 7531,
"s": 7521,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7539,
"s": 7531,
"text": "ihritik"
},
{
"code": null,
"e": 7552,
"s": 7539,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7566,
"s": 7552,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 7573,
"s": 7566,
"text": "subset"
},
{
"code": null,
"e": 7583,
"s": 7573,
"text": "Recursion"
},
{
"code": null,
"e": 7593,
"s": 7583,
"text": "Recursion"
},
{
"code": null,
"e": 7600,
"s": 7593,
"text": "subset"
},
{
"code": null,
"e": 7698,
"s": 7600,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7726,
"s": 7698,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 7797,
"s": 7726,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 7870,
"s": 7797,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 7902,
"s": 7870,
"text": "Reverse a stack using recursion"
},
{
"code": null,
"e": 7948,
"s": 7902,
"text": "Write a program to reverse digits of a number"
},
{
"code": null,
"e": 7991,
"s": 7948,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 8032,
"s": 7991,
"text": "Sum of digit of a number using recursion"
},
{
"code": null,
"e": 8083,
"s": 8032,
"text": "3 Different ways to print Fibonacci series in Java"
}
] |
Rotate image without cutting off sides using Python – OpenCV | 03 Nov, 2021
Prerequisite: Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection)
Rotating images with OpenCV is easy, but sometimes simple rotation tasks cropped/cut sides of an image, which leads to a half image. Now, In this tutorial, We will explore a solution to safely rotate an image without cropping/cutting sides of an image so that the entire image will include in rotation, and also compare the conventional rotation method with the modified rotation version.
Step-by-step approach:
In-order to rotate an image without cutting off sides, we will create an explicit function named ModifedWay() which will take the image itself and the angle to which the image is to be rotated as an argument.
In the function, first, get the height and width of the image.
Locate the center of the image.
Then compute the 2D rotation matrix
Extract the absolute sin and cos values from the rotation matrix.
Get the new height and width of the image and update the values of the rotation matrix to ensure that there is no cropping.
Finally, use the wrapAffine() method to perform the actual rotation of the image.
Below is the implementation of the approach:
Python3
def ModifiedWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now will take out sin and cos values from rotationMatrix # Also used numpy absolute function to make positive value cosofRotationMatrix = np.abs(rotationMatrix[0][0]) sinofRotationMatrix = np.abs(rotationMatrix[0][1]) # Now will compute new height & width of # an image so that we can use it in # warpAffine function to prevent cropping of image sides newImageHeight = int((imgHeight * sinofRotationMatrix) + (imgWidth * cosofRotationMatrix)) newImageWidth = int((imgHeight * cosofRotationMatrix) + (imgWidth * sinofRotationMatrix)) # After computing the new height & width of an image # we also need to update the values of rotation matrix rotationMatrix[0][2] += (newImageWidth/2) - centreX rotationMatrix[1][2] += (newImageHeight/2) - centreY # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (newImageWidth, newImageHeight)) return rotatingimage
Below are some examples which depict how to rotate an image without cutting off sides using the above function:
Example 1:
Below is the implementation of the modified rotation version along with its comparison with normal rotation version:
Python3
# Importing Required Librariesimport cv2import numpy as np # The below function is for conventionally way of rotating# an Image without preventing cutting off sidesdef SimpleWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (imgWidth, imgHeight)) return rotatingimage # The Below function is a modified version of the# conventional way to rotate an image without# cropping/cutting sides.def ModifiedWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now will take out sin and cos values from rotationMatrix # Also used numpy absolute function to make positive value cosofRotationMatrix = np.abs(rotationMatrix[0][0]) sinofRotationMatrix = np.abs(rotationMatrix[0][1]) # Now will compute new height & width of # an image so that we can use it in # warpAffine function to prevent cropping of image sides newImageHeight = int((imgHeight * sinofRotationMatrix) + (imgWidth * cosofRotationMatrix)) newImageWidth = int((imgHeight * cosofRotationMatrix) + (imgWidth * sinofRotationMatrix)) # After computing the new height & width of an image # we also need to update the values of rotation matrix rotationMatrix[0][2] += (newImageWidth/2) - centreX rotationMatrix[1][2] += (newImageHeight/2) - centreY # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (newImageWidth, newImageHeight)) return rotatingimage # Driver Code # Loading an Image from DiskDogImage = cv2.imread("doggy.png", 1) # Performing 40 degree rotationNormalRotation = SimpleWay(DogImage, 40)ModifiedVersionRotation = ModifiedWay(DogImage, 40) # Display image on Screencv2.imshow("Original Image", DogImage) # Display rotated image on Screencv2.imshow("Normal Rotation", NormalRotation)cv2.imshow("Modified Version Rotation", ModifiedVersionRotation) # To hold the GUI screen and control until it is detected# the input for closing it, Once it is closed# control will be releasedcv2.waitKey(0) # To destroy and remove all created GUI windows from#screen and memorycv2.destroyAllWindows()
Output:
Original Image
Normal Rotation with SimpleWay() function
Rotation with ModifiedWay() function
Example 2:
Here is another example that depicts the modern rotation method:
Python3
# Importing Required Librariesimport cv2import numpy as np # The Below function is a modified version of the# conventional way to rotate an image without# cropping/cutting sides.def ModifiedWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now will take out sin and cos values from rotationMatrix # Also used numpy absolute function to make positive value cosofRotationMatrix = np.abs(rotationMatrix[0][0]) sinofRotationMatrix = np.abs(rotationMatrix[0][1]) # Now will compute new height & width of # an image so that we can use it in # warpAffine function to prevent cropping of image sides newImageHeight = int((imgHeight * sinofRotationMatrix) + (imgWidth * cosofRotationMatrix)) newImageWidth = int((imgHeight * cosofRotationMatrix) + (imgWidth * sinofRotationMatrix)) # After computing the new height & width of an image # we also need to update the values of rotation matrix rotationMatrix[0][2] += (newImageWidth/2) - centreX rotationMatrix[1][2] += (newImageHeight/2) - centreY # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (newImageWidth, newImageHeight)) return rotatingimage # Driver Code# Loading an Image from DiskImage = cv2.imread("gfg.png", 1) # Performing 40 degree rotationModifiedVersionRotation = ModifiedWay(Image, 40) # Display image on Screencv2.imshow("Original Image", Image) # Display rotated image on Screencv2.imshow("Modified Version Rotation", ModifiedVersionRotation) # To hold the GUI screen and control until it is detected# the input for closing it, Once it is closed# control will be releasedcv2.waitKey(0) # To destroy and remove all created GUI windows from#screen and memorycv2.destroyAllWindows()
Output:
himanshukanojiya
RavitejaDattaAkella
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 118,
"s": 28,
"text": "Prerequisite: Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection)"
},
{
"code": null,
"e": 508,
"s": 118,
"text": "Rotating images with OpenCV is easy, but sometimes simple rotation tasks cropped/cut sides of an image, which leads to a half image. Now, In this tutorial, We will explore a solution to safely rotate an image without cropping/cutting sides of an image so that the entire image will include in rotation, and also compare the conventional rotation method with the modified rotation version."
},
{
"code": null,
"e": 531,
"s": 508,
"text": "Step-by-step approach:"
},
{
"code": null,
"e": 740,
"s": 531,
"text": "In-order to rotate an image without cutting off sides, we will create an explicit function named ModifedWay() which will take the image itself and the angle to which the image is to be rotated as an argument."
},
{
"code": null,
"e": 803,
"s": 740,
"text": "In the function, first, get the height and width of the image."
},
{
"code": null,
"e": 835,
"s": 803,
"text": "Locate the center of the image."
},
{
"code": null,
"e": 871,
"s": 835,
"text": "Then compute the 2D rotation matrix"
},
{
"code": null,
"e": 937,
"s": 871,
"text": "Extract the absolute sin and cos values from the rotation matrix."
},
{
"code": null,
"e": 1061,
"s": 937,
"text": "Get the new height and width of the image and update the values of the rotation matrix to ensure that there is no cropping."
},
{
"code": null,
"e": 1143,
"s": 1061,
"text": "Finally, use the wrapAffine() method to perform the actual rotation of the image."
},
{
"code": null,
"e": 1188,
"s": 1143,
"text": "Below is the implementation of the approach:"
},
{
"code": null,
"e": 1196,
"s": 1188,
"text": "Python3"
},
{
"code": "def ModifiedWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now will take out sin and cos values from rotationMatrix # Also used numpy absolute function to make positive value cosofRotationMatrix = np.abs(rotationMatrix[0][0]) sinofRotationMatrix = np.abs(rotationMatrix[0][1]) # Now will compute new height & width of # an image so that we can use it in # warpAffine function to prevent cropping of image sides newImageHeight = int((imgHeight * sinofRotationMatrix) + (imgWidth * cosofRotationMatrix)) newImageWidth = int((imgHeight * cosofRotationMatrix) + (imgWidth * sinofRotationMatrix)) # After computing the new height & width of an image # we also need to update the values of rotation matrix rotationMatrix[0][2] += (newImageWidth/2) - centreX rotationMatrix[1][2] += (newImageHeight/2) - centreY # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (newImageWidth, newImageHeight)) return rotatingimage",
"e": 2600,
"s": 1196,
"text": null
},
{
"code": null,
"e": 2712,
"s": 2600,
"text": "Below are some examples which depict how to rotate an image without cutting off sides using the above function:"
},
{
"code": null,
"e": 2723,
"s": 2712,
"text": "Example 1:"
},
{
"code": null,
"e": 2840,
"s": 2723,
"text": "Below is the implementation of the modified rotation version along with its comparison with normal rotation version:"
},
{
"code": null,
"e": 2848,
"s": 2840,
"text": "Python3"
},
{
"code": "# Importing Required Librariesimport cv2import numpy as np # The below function is for conventionally way of rotating# an Image without preventing cutting off sidesdef SimpleWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (imgWidth, imgHeight)) return rotatingimage # The Below function is a modified version of the# conventional way to rotate an image without# cropping/cutting sides.def ModifiedWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now will take out sin and cos values from rotationMatrix # Also used numpy absolute function to make positive value cosofRotationMatrix = np.abs(rotationMatrix[0][0]) sinofRotationMatrix = np.abs(rotationMatrix[0][1]) # Now will compute new height & width of # an image so that we can use it in # warpAffine function to prevent cropping of image sides newImageHeight = int((imgHeight * sinofRotationMatrix) + (imgWidth * cosofRotationMatrix)) newImageWidth = int((imgHeight * cosofRotationMatrix) + (imgWidth * sinofRotationMatrix)) # After computing the new height & width of an image # we also need to update the values of rotation matrix rotationMatrix[0][2] += (newImageWidth/2) - centreX rotationMatrix[1][2] += (newImageHeight/2) - centreY # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (newImageWidth, newImageHeight)) return rotatingimage # Driver Code # Loading an Image from DiskDogImage = cv2.imread(\"doggy.png\", 1) # Performing 40 degree rotationNormalRotation = SimpleWay(DogImage, 40)ModifiedVersionRotation = ModifiedWay(DogImage, 40) # Display image on Screencv2.imshow(\"Original Image\", DogImage) # Display rotated image on Screencv2.imshow(\"Normal Rotation\", NormalRotation)cv2.imshow(\"Modified Version Rotation\", ModifiedVersionRotation) # To hold the GUI screen and control until it is detected# the input for closing it, Once it is closed# control will be releasedcv2.waitKey(0) # To destroy and remove all created GUI windows from#screen and memorycv2.destroyAllWindows()",
"e": 5753,
"s": 2848,
"text": null
},
{
"code": null,
"e": 5761,
"s": 5753,
"text": "Output:"
},
{
"code": null,
"e": 5776,
"s": 5761,
"text": "Original Image"
},
{
"code": null,
"e": 5818,
"s": 5776,
"text": "Normal Rotation with SimpleWay() function"
},
{
"code": null,
"e": 5855,
"s": 5818,
"text": "Rotation with ModifiedWay() function"
},
{
"code": null,
"e": 5866,
"s": 5855,
"text": "Example 2:"
},
{
"code": null,
"e": 5931,
"s": 5866,
"text": "Here is another example that depicts the modern rotation method:"
},
{
"code": null,
"e": 5939,
"s": 5931,
"text": "Python3"
},
{
"code": "# Importing Required Librariesimport cv2import numpy as np # The Below function is a modified version of the# conventional way to rotate an image without# cropping/cutting sides.def ModifiedWay(rotateImage, angle): # Taking image height and width imgHeight, imgWidth = rotateImage.shape[0], rotateImage.shape[1] # Computing the centre x,y coordinates # of an image centreY, centreX = imgHeight//2, imgWidth//2 # Computing 2D rotation Matrix to rotate an image rotationMatrix = cv2.getRotationMatrix2D((centreY, centreX), angle, 1.0) # Now will take out sin and cos values from rotationMatrix # Also used numpy absolute function to make positive value cosofRotationMatrix = np.abs(rotationMatrix[0][0]) sinofRotationMatrix = np.abs(rotationMatrix[0][1]) # Now will compute new height & width of # an image so that we can use it in # warpAffine function to prevent cropping of image sides newImageHeight = int((imgHeight * sinofRotationMatrix) + (imgWidth * cosofRotationMatrix)) newImageWidth = int((imgHeight * cosofRotationMatrix) + (imgWidth * sinofRotationMatrix)) # After computing the new height & width of an image # we also need to update the values of rotation matrix rotationMatrix[0][2] += (newImageWidth/2) - centreX rotationMatrix[1][2] += (newImageHeight/2) - centreY # Now, we will perform actual image rotation rotatingimage = cv2.warpAffine( rotateImage, rotationMatrix, (newImageWidth, newImageHeight)) return rotatingimage # Driver Code# Loading an Image from DiskImage = cv2.imread(\"gfg.png\", 1) # Performing 40 degree rotationModifiedVersionRotation = ModifiedWay(Image, 40) # Display image on Screencv2.imshow(\"Original Image\", Image) # Display rotated image on Screencv2.imshow(\"Modified Version Rotation\", ModifiedVersionRotation) # To hold the GUI screen and control until it is detected# the input for closing it, Once it is closed# control will be releasedcv2.waitKey(0) # To destroy and remove all created GUI windows from#screen and memorycv2.destroyAllWindows()",
"e": 8086,
"s": 5939,
"text": null
},
{
"code": null,
"e": 8094,
"s": 8086,
"text": "Output:"
},
{
"code": null,
"e": 8111,
"s": 8094,
"text": "himanshukanojiya"
},
{
"code": null,
"e": 8131,
"s": 8111,
"text": "RavitejaDattaAkella"
},
{
"code": null,
"e": 8145,
"s": 8131,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 8152,
"s": 8145,
"text": "Python"
},
{
"code": null,
"e": 8250,
"s": 8152,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8282,
"s": 8250,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8309,
"s": 8282,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8330,
"s": 8309,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8353,
"s": 8330,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8409,
"s": 8353,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 8440,
"s": 8409,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8482,
"s": 8440,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 8524,
"s": 8482,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 8563,
"s": 8524,
"text": "Python | Get unique values from a list"
}
] |
Python | Extracting rows using Pandas .iloc[] | 09 Jun, 2022
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier.
The Pandas library provides a unique method to retrieve rows from a Data Frame. Dataframe.iloc[] method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3....n or in case the user doesn’t know the index label. Rows can be extracted using an imaginary index position which isn’t visible in the data frame.
Syntax: pandas.DataFrame.iloc[]
Parameters:
Index Position: Index position of rows in integer or list of integer.
Return type: Data frame or Series depending on parameters
To download the CSV used in code, click here. Example #1: Extracting single row and comparing with .loc[] In this example, same index number row is extracted by both .iloc[] and.loc[] method and compared. Since the index column by default is numeric, hence the index label will also be integers.
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # retrieving rows by loc methodrow1 = data.loc[3] # retrieving rows by iloc methodrow2 = data.iloc[3] # checking if values are equalrow1 == row2
Output:
As shown in the output image, the results returned by both methods are the same.
Example #2: Extracting multiple rows with index In this example, multiple rows are extracted, first by passing a list and then by passing integers to extract rows between that range. After that, both the values are compared.
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # retrieving rows by loc methodrow1 = data.iloc[[4, 5, 6, 7]] # retrieving rows by loc methodrow2 = data.iloc[4:8] # comparing valuesrow1 == row2
Output:
As shown in the output image, the results returned by both methods are the same. All values are True except values in the college column since those were NaN values.
urvishmahajan
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 268,
"s": 52,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. "
},
{
"code": null,
"e": 620,
"s": 268,
"text": "The Pandas library provides a unique method to retrieve rows from a Data Frame. Dataframe.iloc[] method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3....n or in case the user doesn’t know the index label. Rows can be extracted using an imaginary index position which isn’t visible in the data frame."
},
{
"code": null,
"e": 653,
"s": 620,
"text": "Syntax: pandas.DataFrame.iloc[] "
},
{
"code": null,
"e": 666,
"s": 653,
"text": "Parameters: "
},
{
"code": null,
"e": 737,
"s": 666,
"text": "Index Position: Index position of rows in integer or list of integer. "
},
{
"code": null,
"e": 795,
"s": 737,
"text": "Return type: Data frame or Series depending on parameters"
},
{
"code": null,
"e": 1093,
"s": 795,
"text": "To download the CSV used in code, click here. Example #1: Extracting single row and comparing with .loc[] In this example, same index number row is extracted by both .iloc[] and.loc[] method and compared. Since the index column by default is numeric, hence the index label will also be integers. "
},
{
"code": null,
"e": 1101,
"s": 1093,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # retrieving rows by loc methodrow1 = data.loc[3] # retrieving rows by iloc methodrow2 = data.iloc[3] # checking if values are equalrow1 == row2",
"e": 1355,
"s": 1101,
"text": null
},
{
"code": null,
"e": 1364,
"s": 1355,
"text": "Output: "
},
{
"code": null,
"e": 1445,
"s": 1364,
"text": "As shown in the output image, the results returned by both methods are the same."
},
{
"code": null,
"e": 1676,
"s": 1450,
"text": "Example #2: Extracting multiple rows with index In this example, multiple rows are extracted, first by passing a list and then by passing integers to extract rows between that range. After that, both the values are compared. "
},
{
"code": null,
"e": 1684,
"s": 1676,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # retrieving rows by loc methodrow1 = data.iloc[[4, 5, 6, 7]] # retrieving rows by loc methodrow2 = data.iloc[4:8] # comparing valuesrow1 == row2",
"e": 1939,
"s": 1684,
"text": null
},
{
"code": null,
"e": 1948,
"s": 1939,
"text": "Output: "
},
{
"code": null,
"e": 2115,
"s": 1948,
"text": "As shown in the output image, the results returned by both methods are the same. All values are True except values in the college column since those were NaN values. "
},
{
"code": null,
"e": 2129,
"s": 2115,
"text": "urvishmahajan"
},
{
"code": null,
"e": 2153,
"s": 2129,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2185,
"s": 2153,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2199,
"s": 2185,
"text": "Python-pandas"
},
{
"code": null,
"e": 2206,
"s": 2199,
"text": "Python"
},
{
"code": null,
"e": 2304,
"s": 2206,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2332,
"s": 2304,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2382,
"s": 2332,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2404,
"s": 2382,
"text": "Python map() function"
},
{
"code": null,
"e": 2448,
"s": 2404,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2490,
"s": 2448,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2512,
"s": 2490,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2547,
"s": 2512,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2573,
"s": 2547,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2605,
"s": 2573,
"text": "How to Install PIP on Windows ?"
}
] |
How React Native works? | 07 Feb, 2018
In the previous blog post, we built starter app which Displays “GeeksForGeeks is Awesome!” text and learned some JavaScript code using React Native platform.
But what happens in the low level code, in the native project?So before digging into React Native Examples, Lets first know what exactly happens in the low level code.
Threads in React Native App
There are 4 threads in the React Native App :
1) UI Thread : Also known as Main Thread. This is used for native android or iOS UI rendering. For example, In android this thread is used for android measure/layout/draw happens.
2) JS Thread : JS thread or Javascript thread is the thread where the logic will run. For e.g., this is the thread where the application’s javascript code is executed, api calls are made, touch events are processed and many other. Updates to native views are batched and sent over to native side at the end of each event loop in the JS thread (and are executed eventually in UI thread).
To maintain good performance, JS thread should be able to send batched updates to UI thread before next frame rendering deadline. For example, iOS display 60 frames per sec and this lead to new frame every 16.67ms. If you do some complex processing in your javascript event loop that leads to UI changes and it takes more than 16.67ms, then UI will appear sluggish.
One exception are the native views that happen completely in UI thread, for example, navigatorIOS or scrollview run completely in UI thread and hence are not blocked due to a slow js thread.
3) Native Modules Thread: Sometimes an app needs access to platform API, and this happens as part of native module thread.
4) Render Thread : Only in Android L (5.0), react native render thread is used to generate actual OpenGL commands used to draw your UI.
Process involved in working of React Native
1) At the first start of the app, the main thread starts execution and starts loading JS bundles.
2) When JavaScript code has been loaded successfully, the main thread sends it to another JS thread because when JS does some heavy calculations stuff the thread for a while, the UI thread will not suffer at all any time.
3) When React start rendering Reconciler starts “diffing”, and when it generates a new virtual DOM(layout) it sends changes to another thread(Shadow thread).
4) Shadow thread calculates layout and then sends layout parameters/objects to the main(UI) thread. ( Here you may wonder why we call it “shadow”? It’s because it generates shadow nodes )
5) Since only the main thread is able to render something on the screen, shadow thread should send generated layout to the main thread, and only then UI renders.
Separation of React Native
Generally, we can separate React Native into 3 parts :
1) React Native – Native side
2) React Native – JS side
3) React Native – Bridge
This is often called “The 3 Parts of React Native”
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GBlog
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Feb, 2018"
},
{
"code": null,
"e": 211,
"s": 53,
"text": "In the previous blog post, we built starter app which Displays “GeeksForGeeks is Awesome!” text and learned some JavaScript code using React Native platform."
},
{
"code": null,
"e": 379,
"s": 211,
"text": "But what happens in the low level code, in the native project?So before digging into React Native Examples, Lets first know what exactly happens in the low level code."
},
{
"code": null,
"e": 407,
"s": 379,
"text": "Threads in React Native App"
},
{
"code": null,
"e": 453,
"s": 407,
"text": "There are 4 threads in the React Native App :"
},
{
"code": null,
"e": 633,
"s": 453,
"text": "1) UI Thread : Also known as Main Thread. This is used for native android or iOS UI rendering. For example, In android this thread is used for android measure/layout/draw happens."
},
{
"code": null,
"e": 1020,
"s": 633,
"text": "2) JS Thread : JS thread or Javascript thread is the thread where the logic will run. For e.g., this is the thread where the application’s javascript code is executed, api calls are made, touch events are processed and many other. Updates to native views are batched and sent over to native side at the end of each event loop in the JS thread (and are executed eventually in UI thread)."
},
{
"code": null,
"e": 1386,
"s": 1020,
"text": "To maintain good performance, JS thread should be able to send batched updates to UI thread before next frame rendering deadline. For example, iOS display 60 frames per sec and this lead to new frame every 16.67ms. If you do some complex processing in your javascript event loop that leads to UI changes and it takes more than 16.67ms, then UI will appear sluggish."
},
{
"code": null,
"e": 1577,
"s": 1386,
"text": "One exception are the native views that happen completely in UI thread, for example, navigatorIOS or scrollview run completely in UI thread and hence are not blocked due to a slow js thread."
},
{
"code": null,
"e": 1700,
"s": 1577,
"text": "3) Native Modules Thread: Sometimes an app needs access to platform API, and this happens as part of native module thread."
},
{
"code": null,
"e": 1836,
"s": 1700,
"text": "4) Render Thread : Only in Android L (5.0), react native render thread is used to generate actual OpenGL commands used to draw your UI."
},
{
"code": null,
"e": 1880,
"s": 1836,
"text": "Process involved in working of React Native"
},
{
"code": null,
"e": 1978,
"s": 1880,
"text": "1) At the first start of the app, the main thread starts execution and starts loading JS bundles."
},
{
"code": null,
"e": 2200,
"s": 1978,
"text": "2) When JavaScript code has been loaded successfully, the main thread sends it to another JS thread because when JS does some heavy calculations stuff the thread for a while, the UI thread will not suffer at all any time."
},
{
"code": null,
"e": 2358,
"s": 2200,
"text": "3) When React start rendering Reconciler starts “diffing”, and when it generates a new virtual DOM(layout) it sends changes to another thread(Shadow thread)."
},
{
"code": null,
"e": 2546,
"s": 2358,
"text": "4) Shadow thread calculates layout and then sends layout parameters/objects to the main(UI) thread. ( Here you may wonder why we call it “shadow”? It’s because it generates shadow nodes )"
},
{
"code": null,
"e": 2708,
"s": 2546,
"text": "5) Since only the main thread is able to render something on the screen, shadow thread should send generated layout to the main thread, and only then UI renders."
},
{
"code": null,
"e": 2735,
"s": 2708,
"text": "Separation of React Native"
},
{
"code": null,
"e": 2790,
"s": 2735,
"text": "Generally, we can separate React Native into 3 parts :"
},
{
"code": null,
"e": 2820,
"s": 2790,
"text": "1) React Native – Native side"
},
{
"code": null,
"e": 2846,
"s": 2820,
"text": "2) React Native – JS side"
},
{
"code": null,
"e": 2871,
"s": 2846,
"text": "3) React Native – Bridge"
},
{
"code": null,
"e": 2922,
"s": 2871,
"text": "This is often called “The 3 Parts of React Native”"
},
{
"code": null,
"e": 3221,
"s": 2922,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3346,
"s": 3221,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3352,
"s": 3346,
"text": "GBlog"
},
{
"code": null,
"e": 3369,
"s": 3352,
"text": "Web Technologies"
}
] |
jQuery | attr() Method | 27 Feb, 2019
The attr() method in jQuery is used to set or return the attributes and values of the selected elements.
Syntax:
To return the value of an attribute:$(selector).attr(attribute)
$(selector).attr(attribute)
To set the attribute and value:$(selector).attr(attribute, value)
$(selector).attr(attribute, value)
To set attribute and value using a function:$(selector).attr(attribute, function(index, currentvalue))
$(selector).attr(attribute, function(index, currentvalue))
To set multiple attributes and values:$(selector).attr({attribute:value, attribute:value, ...})
$(selector).attr({attribute:value, attribute:value, ...})
Parameter
attribute: This parameter is used to specify the name of the attribute
value: It is used to specify the value of the attribute
function(index, currentvalue): It is used to specify a function that returns the attribute value to set
index: Index position of the element received with the help of this parameter.
currentvalue: It is used to receive the current attribute value of selected elements.
Example-1:
<!DOCTYPE html><html> <head> <title>jQuery attr() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style="color:lightgreen;"> </h3> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132-120x300.png" alt="" width="120" height="300" class="alignnone size-medium wp-image-915678" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $("button").click(function() { $("img").attr("width", "300"); }); }); </script> </center></body> </html>
Output:Before Click on the button:
After Click on the button:
Example-2:
<!DOCTYPE html><html> <head> <title>jQuery attr() Method</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style="color:lightgreen;"></h3> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132-120x300.png" alt="" width="120" height="300" class= "alignnone size-medium wp-image-915678" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $("button").click(function() { alert("Image width: " + $("img").attr("width")); }); }); </script> </center></body> </html>
Output:
Before Click on the button:
After Click on the button:
Example-3:
<!DOCTYPE html><html> <head> <title>jQuery attr() Method</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style="color:lightgreen;"> </h3> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132.png" alt="" width="120" height="300" class= "alignnone size-medium wp-image-915678" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $("button").click(function() { $("img").attr("width", function(n, v) { return v - 50; }); }); }); </script> </center></body> </html>
Output:
Before Click on the button:
After Click on the button:
Example-4:
<!DOCTYPE html><html> <head> <title>jQuery attr() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <center> <h1 style= "color:green;"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style="color:lightgreen;"></h3> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132.png" alt="" width="120" height="300" class= "alignnone size-medium wp-image-915678" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $("button").click(function() { $("img").attr({ width: "150", height: "100" }); }); }); </script> </center></body> </html>
Output:
Before Click on the button:
After Click on the button:
jQuery-Methods
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
How to fetch data from JSON file and display in HTML table using jQuery ?
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": "\n27 Feb, 2019"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "The attr() method in jQuery is used to set or return the attributes and values of the selected elements."
},
{
"code": null,
"e": 141,
"s": 133,
"text": "Syntax:"
},
{
"code": null,
"e": 205,
"s": 141,
"text": "To return the value of an attribute:$(selector).attr(attribute)"
},
{
"code": null,
"e": 233,
"s": 205,
"text": "$(selector).attr(attribute)"
},
{
"code": null,
"e": 299,
"s": 233,
"text": "To set the attribute and value:$(selector).attr(attribute, value)"
},
{
"code": null,
"e": 334,
"s": 299,
"text": "$(selector).attr(attribute, value)"
},
{
"code": null,
"e": 437,
"s": 334,
"text": "To set attribute and value using a function:$(selector).attr(attribute, function(index, currentvalue))"
},
{
"code": null,
"e": 496,
"s": 437,
"text": "$(selector).attr(attribute, function(index, currentvalue))"
},
{
"code": null,
"e": 592,
"s": 496,
"text": "To set multiple attributes and values:$(selector).attr({attribute:value, attribute:value, ...})"
},
{
"code": null,
"e": 650,
"s": 592,
"text": "$(selector).attr({attribute:value, attribute:value, ...})"
},
{
"code": null,
"e": 660,
"s": 650,
"text": "Parameter"
},
{
"code": null,
"e": 731,
"s": 660,
"text": "attribute: This parameter is used to specify the name of the attribute"
},
{
"code": null,
"e": 787,
"s": 731,
"text": "value: It is used to specify the value of the attribute"
},
{
"code": null,
"e": 891,
"s": 787,
"text": "function(index, currentvalue): It is used to specify a function that returns the attribute value to set"
},
{
"code": null,
"e": 970,
"s": 891,
"text": "index: Index position of the element received with the help of this parameter."
},
{
"code": null,
"e": 1056,
"s": 970,
"text": "currentvalue: It is used to receive the current attribute value of selected elements."
},
{
"code": null,
"e": 1067,
"s": 1056,
"text": "Example-1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>jQuery attr() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style=\"color:lightgreen;\"> </h3> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132-120x300.png\" alt=\"\" width=\"120\" height=\"300\" class=\"alignnone size-medium wp-image-915678\" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"img\").attr(\"width\", \"300\"); }); }); </script> </center></body> </html>",
"e": 1936,
"s": 1067,
"text": null
},
{
"code": null,
"e": 1971,
"s": 1936,
"text": "Output:Before Click on the button:"
},
{
"code": null,
"e": 1998,
"s": 1971,
"text": "After Click on the button:"
},
{
"code": null,
"e": 2009,
"s": 1998,
"text": "Example-2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>jQuery attr() Method</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style=\"color:lightgreen;\"></h3> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132-120x300.png\" alt=\"\" width=\"120\" height=\"300\" class= \"alignnone size-medium wp-image-915678\" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $(\"button\").click(function() { alert(\"Image width: \" + $(\"img\").attr(\"width\")); }); }); </script> </center></body> </html>",
"e": 2908,
"s": 2009,
"text": null
},
{
"code": null,
"e": 2916,
"s": 2908,
"text": "Output:"
},
{
"code": null,
"e": 2944,
"s": 2916,
"text": "Before Click on the button:"
},
{
"code": null,
"e": 2971,
"s": 2944,
"text": "After Click on the button:"
},
{
"code": null,
"e": 2982,
"s": 2971,
"text": "Example-3:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>jQuery attr() Method</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style=\"color:lightgreen;\"> </h3> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132.png\" alt=\"\" width=\"120\" height=\"300\" class= \"alignnone size-medium wp-image-915678\" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"img\").attr(\"width\", function(n, v) { return v - 50; }); }); }); </script> </center></body> </html>",
"e": 3903,
"s": 2982,
"text": null
},
{
"code": null,
"e": 3911,
"s": 3903,
"text": "Output:"
},
{
"code": null,
"e": 3939,
"s": 3911,
"text": "Before Click on the button:"
},
{
"code": null,
"e": 3966,
"s": 3939,
"text": "After Click on the button:"
},
{
"code": null,
"e": 3977,
"s": 3966,
"text": "Example-4:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>jQuery attr() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <center> <h1 style= \"color:green;\"> GeeksForGeeks</h1> <h2> jQuery attr() Method</h2> <h3 style=\"color:lightgreen;\"></h3> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190221153831/1132.png\" alt=\"\" width=\"120\" height=\"300\" class= \"alignnone size-medium wp-image-915678\" /> <br> <br> <button>Click</button> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"img\").attr({ width: \"150\", height: \"100\" }); }); }); </script> </center></body> </html>",
"e": 4936,
"s": 3977,
"text": null
},
{
"code": null,
"e": 4944,
"s": 4936,
"text": "Output:"
},
{
"code": null,
"e": 4972,
"s": 4944,
"text": "Before Click on the button:"
},
{
"code": null,
"e": 4999,
"s": 4972,
"text": "After Click on the button:"
},
{
"code": null,
"e": 5014,
"s": 4999,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 5021,
"s": 5014,
"text": "Picked"
},
{
"code": null,
"e": 5028,
"s": 5021,
"text": "JQuery"
},
{
"code": null,
"e": 5045,
"s": 5028,
"text": "Web Technologies"
},
{
"code": null,
"e": 5143,
"s": 5045,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5189,
"s": 5143,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 5218,
"s": 5189,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5281,
"s": 5218,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 5334,
"s": 5281,
"text": "How to add options to a select element using jQuery?"
},
{
"code": null,
"e": 5408,
"s": 5334,
"text": "How to fetch data from JSON file and display in HTML table using jQuery ?"
},
{
"code": null,
"e": 5470,
"s": 5408,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5503,
"s": 5470,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5564,
"s": 5503,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5614,
"s": 5564,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Number of unique pairs in an array | 30 Jun, 2021
Given an array of N elements, the task is to find all the unique pairs that can be formed using the elements of a given array. Examples:
Input: arr[] = {1, 1, 2} Output: 4 (1, 1), (1, 2), (2, 1), (2, 2) are the only possible pairs.
Input: arr[] = {1, 2, 3} Output: 9
Naive approach: The simple solution is to iterate through every possible pair and add them to a set and then find out the size of the set.
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 return the number// of unique pairs in the arrayint countUnique(int arr[], int n){ // Set to store unique pairs set<pair<int, int> > s; // Make all possible pairs for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) s.insert(make_pair(arr[i], arr[j])); // Return the size of the set return s.size();} // Driver codeint main(){ int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countUnique(arr, n); return 0;}
// Java implementation of the approachimport java.awt.Point;import java.util.*; class GFG{ // Function to return the number// of unique pairs in the arraystatic int countUnique(int arr[], int n){ // Set to store unique pairs Set<Point> s = new HashSet<>(); // Make all possible pairs for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) s.add(new Point(arr[i], arr[j])); // Return the size of the set return s.size();} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = arr.length; System.out.print(countUnique(arr, n));}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # Function to return the number# of unique pairs in the arraydef countUnique(arr, n): # Set to store unique pairs s = set() # Make all possible pairs for i in range(n): for j in range(n): s.add((arr[i], arr[j])) # Return the size of the set return len(s) # Driver code arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]n = len(arr)print(countUnique(arr, n)) # This code is contributed by ankush_953
// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ public class store : IComparer<KeyValuePair<int, int>>{ public int Compare(KeyValuePair<int, int> x, KeyValuePair<int, int> y) { if (x.Key != y.Key) { return x.Key.CompareTo(y.Key); } else { return x.Value.CompareTo(y.Value); } }} // Function to return the number// of unique pairs in the arraystatic int countUnique(int []arr, int n){ // Set to store unique pairs SortedSet<KeyValuePair<int, int>> s = new SortedSet<KeyValuePair<int, int>>(new store()); // Make all possible pairs for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) s.Add(new KeyValuePair<int, int>(arr[i], arr[j])); // Return the size of the set return s.Count;} // Driver code public static void Main(string []arg){ int []arr = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = arr.Length; Console.Write(countUnique(arr, n));}} // This code is contributed by rutvik_56
<script> // JavaScript implementation of the approach // Function to return the number // of unique pairs in the array function countUnique(arr,n) { // Set to store unique pairs let s = new Set(); // Make all possible pairs for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) s.add((arr[i], arr[j])); // Return the size of the set return 5*s.size; } // Driver code let arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]; let n = arr.length; document.write(countUnique(arr, n)); </script>
25
Time Complexity: Time complexity of the above implementation is O(n2 Log n). We can optimize it to O(n2) using unordered_set with user defined hash function.
Efficient approach: First find out the number of unique elements in an array. Let the number of unique elements be x. Then, the number of unique pairs would be x2. This is because each unique element can form a pair with every other unique element including itself.
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 return the number// of unique pairs in the arrayint countUnique(int arr[], int n){ unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr[i]); int count = pow(s.size(), 2); return count;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countUnique(arr, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the number // of unique pairs in the array static int countUnique(int arr[], int n) { HashSet<Integer> s = new HashSet<>(); for (int i = 0; i < n; i++) { s.add(arr[i]); } int count = (int) Math.pow(s.size(), 2); return count; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 2, 4, 2, 5, 3, 5}; int n = arr.length; System.out.println(countUnique(arr, n)); }} /* This code has been contributedby PrinciRaj1992*/
# Python3 implementation of the approach # Function to return the number# of unique pairs in the arraydef countUnique(arr, n): s = set() for i in range(n): s.add(arr[i]) count = pow(len(s), 2) return count # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ] n = len(arr) print(countUnique(arr, n)) # This code is contributed by Ryuga
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the number // of unique pairs in the array static int countUnique(int []arr, int n) { HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { s.Add(arr[i]); } int count = (int) Math.Pow(s.Count, 2); return count; } // Driver code static void Main() { int []arr = {1, 2, 2, 4, 2, 5, 3, 5}; int n = arr.Length; Console.WriteLine(countUnique(arr, n)); }} // This code has been contributed by mits
<script> // JavaScript Program to implement// the above approach // Function to return the number // of unique pairs in the array function countUnique(arr, n){ let s = new Set(); for (let i = 0; i < n; i++) { s.add(arr[i]); } let count = Math.pow(s.size, 2); return count; }// Driver Code let arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]; let n = arr.length; document.write(countUnique(arr, n)); </script>
25
Time Complexity: O(n)
princiraj1992
ankthon
Mithun Kumar
ankush_953
29AjayKumar
rutvik_56
aniruddhkotte
susmitakundugoaldanga
vaibhavrabadiya117
cpp-unordered_set
Arrays
Combinatorial
Hash
Arrays
Hash
Combinatorial
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
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
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": 53,
"s": 25,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 191,
"s": 53,
"text": "Given an array of N elements, the task is to find all the unique pairs that can be formed using the elements of a given array. Examples: "
},
{
"code": null,
"e": 286,
"s": 191,
"text": "Input: arr[] = {1, 1, 2} Output: 4 (1, 1), (1, 2), (2, 1), (2, 2) are the only possible pairs."
},
{
"code": null,
"e": 322,
"s": 286,
"text": "Input: arr[] = {1, 2, 3} Output: 9 "
},
{
"code": null,
"e": 461,
"s": 322,
"text": "Naive approach: The simple solution is to iterate through every possible pair and add them to a set and then find out the size of the set."
},
{
"code": null,
"e": 512,
"s": 461,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 516,
"s": 512,
"text": "C++"
},
{
"code": null,
"e": 521,
"s": 516,
"text": "Java"
},
{
"code": null,
"e": 529,
"s": 521,
"text": "Python3"
},
{
"code": null,
"e": 532,
"s": 529,
"text": "C#"
},
{
"code": null,
"e": 543,
"s": 532,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of unique pairs in the arrayint countUnique(int arr[], int n){ // Set to store unique pairs set<pair<int, int> > s; // Make all possible pairs for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) s.insert(make_pair(arr[i], arr[j])); // Return the size of the set return s.size();} // Driver codeint main(){ int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countUnique(arr, n); return 0;}",
"e": 1140,
"s": 543,
"text": null
},
{
"code": "// Java implementation of the approachimport java.awt.Point;import java.util.*; class GFG{ // Function to return the number// of unique pairs in the arraystatic int countUnique(int arr[], int n){ // Set to store unique pairs Set<Point> s = new HashSet<>(); // Make all possible pairs for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) s.add(new Point(arr[i], arr[j])); // Return the size of the set return s.size();} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = arr.length; System.out.print(countUnique(arr, n));}} // This code is contributed by 29AjayKumar",
"e": 1809,
"s": 1140,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the number# of unique pairs in the arraydef countUnique(arr, n): # Set to store unique pairs s = set() # Make all possible pairs for i in range(n): for j in range(n): s.add((arr[i], arr[j])) # Return the size of the set return len(s) # Driver code arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]n = len(arr)print(countUnique(arr, n)) # This code is contributed by ankush_953",
"e": 2270,
"s": 1809,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ public class store : IComparer<KeyValuePair<int, int>>{ public int Compare(KeyValuePair<int, int> x, KeyValuePair<int, int> y) { if (x.Key != y.Key) { return x.Key.CompareTo(y.Key); } else { return x.Value.CompareTo(y.Value); } }} // Function to return the number// of unique pairs in the arraystatic int countUnique(int []arr, int n){ // Set to store unique pairs SortedSet<KeyValuePair<int, int>> s = new SortedSet<KeyValuePair<int, int>>(new store()); // Make all possible pairs for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) s.Add(new KeyValuePair<int, int>(arr[i], arr[j])); // Return the size of the set return s.Count;} // Driver code public static void Main(string []arg){ int []arr = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = arr.Length; Console.Write(countUnique(arr, n));}} // This code is contributed by rutvik_56",
"e": 3479,
"s": 2270,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the number // of unique pairs in the array function countUnique(arr,n) { // Set to store unique pairs let s = new Set(); // Make all possible pairs for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) s.add((arr[i], arr[j])); // Return the size of the set return 5*s.size; } // Driver code let arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]; let n = arr.length; document.write(countUnique(arr, n)); </script>",
"e": 4062,
"s": 3479,
"text": null
},
{
"code": null,
"e": 4065,
"s": 4062,
"text": "25"
},
{
"code": null,
"e": 4225,
"s": 4067,
"text": "Time Complexity: Time complexity of the above implementation is O(n2 Log n). We can optimize it to O(n2) using unordered_set with user defined hash function."
},
{
"code": null,
"e": 4491,
"s": 4225,
"text": "Efficient approach: First find out the number of unique elements in an array. Let the number of unique elements be x. Then, the number of unique pairs would be x2. This is because each unique element can form a pair with every other unique element including itself."
},
{
"code": null,
"e": 4543,
"s": 4491,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 4547,
"s": 4543,
"text": "C++"
},
{
"code": null,
"e": 4552,
"s": 4547,
"text": "Java"
},
{
"code": null,
"e": 4560,
"s": 4552,
"text": "Python3"
},
{
"code": null,
"e": 4563,
"s": 4560,
"text": "C#"
},
{
"code": null,
"e": 4574,
"s": 4563,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of unique pairs in the arrayint countUnique(int arr[], int n){ unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr[i]); int count = pow(s.size(), 2); return count;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countUnique(arr, n); return 0;}",
"e": 5046,
"s": 4574,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the number // of unique pairs in the array static int countUnique(int arr[], int n) { HashSet<Integer> s = new HashSet<>(); for (int i = 0; i < n; i++) { s.add(arr[i]); } int count = (int) Math.pow(s.size(), 2); return count; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 2, 4, 2, 5, 3, 5}; int n = arr.length; System.out.println(countUnique(arr, n)); }} /* This code has been contributedby PrinciRaj1992*/",
"e": 5680,
"s": 5046,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the number# of unique pairs in the arraydef countUnique(arr, n): s = set() for i in range(n): s.add(arr[i]) count = pow(len(s), 2) return count # Driver codeif __name__ == \"__main__\" : arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ] n = len(arr) print(countUnique(arr, n)) # This code is contributed by Ryuga",
"e": 6077,
"s": 5680,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the number // of unique pairs in the array static int countUnique(int []arr, int n) { HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { s.Add(arr[i]); } int count = (int) Math.Pow(s.Count, 2); return count; } // Driver code static void Main() { int []arr = {1, 2, 2, 4, 2, 5, 3, 5}; int n = arr.Length; Console.WriteLine(countUnique(arr, n)); }} // This code has been contributed by mits",
"e": 6703,
"s": 6077,
"text": null
},
{
"code": "<script> // JavaScript Program to implement// the above approach // Function to return the number // of unique pairs in the array function countUnique(arr, n){ let s = new Set(); for (let i = 0; i < n; i++) { s.add(arr[i]); } let count = Math.pow(s.size, 2); return count; }// Driver Code let arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]; let n = arr.length; document.write(countUnique(arr, n)); </script>",
"e": 7178,
"s": 6703,
"text": null
},
{
"code": null,
"e": 7181,
"s": 7178,
"text": "25"
},
{
"code": null,
"e": 7206,
"s": 7183,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 7220,
"s": 7206,
"text": "princiraj1992"
},
{
"code": null,
"e": 7228,
"s": 7220,
"text": "ankthon"
},
{
"code": null,
"e": 7241,
"s": 7228,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7252,
"s": 7241,
"text": "ankush_953"
},
{
"code": null,
"e": 7264,
"s": 7252,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7274,
"s": 7264,
"text": "rutvik_56"
},
{
"code": null,
"e": 7288,
"s": 7274,
"text": "aniruddhkotte"
},
{
"code": null,
"e": 7310,
"s": 7288,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 7329,
"s": 7310,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 7347,
"s": 7329,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 7354,
"s": 7347,
"text": "Arrays"
},
{
"code": null,
"e": 7368,
"s": 7354,
"text": "Combinatorial"
},
{
"code": null,
"e": 7373,
"s": 7368,
"text": "Hash"
},
{
"code": null,
"e": 7380,
"s": 7373,
"text": "Arrays"
},
{
"code": null,
"e": 7385,
"s": 7380,
"text": "Hash"
},
{
"code": null,
"e": 7399,
"s": 7385,
"text": "Combinatorial"
},
{
"code": null,
"e": 7497,
"s": 7399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7565,
"s": 7497,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 7609,
"s": 7565,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 7641,
"s": 7609,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 7689,
"s": 7641,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 7703,
"s": 7689,
"text": "Linear Search"
},
{
"code": null,
"e": 7763,
"s": 7703,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 7801,
"s": 7763,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 7838,
"s": 7801,
"text": "Count of subsets with sum equal to X"
}
] |
SQL Query to Combine Two Tables Without a Common Column | 19 May, 2021
In most of the queries in the learning process, we usually use to join those tables which have some common columns or relationships between them. But when it comes to real-life problems, then such easiest conditions are rarely found. Complex tasks like joining two tables without a common column is majorly found.
Let’s first have a look at our tables which we will be joining in this example:
Creating the Database:
Use the below SQL statement to create a database called geeks:
CREATE DATABASE GFG;
Using the Database:
Use the below SQL statement to switch the database context to geeks:
USE GFG;
Adding Tables:
Now we create two tables named as table1 and table2
CREATE TABLE table1
(
Name1 VARCHAR(20),
ID1 INT PRIMARY KEY,
Salary1 INT
);
CREATE TABLE table2
(
Name2 VARCHAR(20),
ID2 INT PRIMARY KEY,
Salary2 INT
);
Now, adding data to tables
INSERT INTO table1
ValUES
('Harish',1,1000),
('Rakesh',2,2000),
('Mukesh',3,3000),
('Suresh',4,4000),
('Ramesh',5,4000);
INSERT INTO table2
VALUES
('Astitva',1,4000),
('Maharaj',2,41000);
To verify the contents of the table use the below statement:
For table1:
SELECT * FROM table1;
For table2:
SELECT * FROM table2;
Now as we can see there are no two columns that are the same in the above two tables. Now to merge them into a single table we are having 3 different methods.
Method 1 (Cross Join): As you might have heard of several joins like inner join, outer join, in the same way cross join is there, which is used to form the Cartesian product of the tables without or with common columns. So since these joins doesn’t check for any column just they do a product of the two tables, so these joins are not regarded good for any query since repetition of data will be resulted from these joins. Also, inconsistency would be there. But since we are interested in knowing the methods so we are discussing it.
To do cross join we are just required to specify the name of table in FROM clause. No, WHERE clause is needed.
SELECT * FROM table1, table2;
5*2=10
Method 2 (UNION Method): This method is different from the above one as it is not merely a join. Its main aim is to combine the table through Row by Row method. It just adds the number of UNIQUE rows of the two tables and name the columns based on the first table specified in the method.
SELECT *
FROM TABLE1
UNION
SELECT *
FROM TABLE2;
This returns all the rows(unique) combined together under the column name of the TABLE1.
We can also query single columns or rename the columns in this method as shown below:
SELECT salary1 as salary
FROM TABLE1
UNION
SELECT salary2 as salary
FROM TABLE2;
Hence we are able to select all the salaries possible and given to different clients in the two tables. This method returns unique data.
Method 3 (UNION ALL): The only difference between the UNION and UNIONALL method is that the previous one allows non-duplicates(unique) rows, but latter one results in all possible rows by combining the duplicates also.
SELECT salary1 as salary
FROM TABLE1
UNION all
SELECT salary2 as salary
FROM TABLE2;
Hence we are able to see the three different methods to combine table with non-common columns. These methods are used under separate conditions as demanded.
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL using Python
Introduction to NoSQL
Window functions in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions | Set 1
Advantages and Disadvantages of SQL
SQL | Subquery
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL vs NoSQL: Which one is better to use? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 343,
"s": 28,
"text": "In most of the queries in the learning process, we usually use to join those tables which have some common columns or relationships between them. But when it comes to real-life problems, then such easiest conditions are rarely found. Complex tasks like joining two tables without a common column is majorly found. "
},
{
"code": null,
"e": 423,
"s": 343,
"text": "Let’s first have a look at our tables which we will be joining in this example:"
},
{
"code": null,
"e": 446,
"s": 423,
"text": "Creating the Database:"
},
{
"code": null,
"e": 509,
"s": 446,
"text": "Use the below SQL statement to create a database called geeks:"
},
{
"code": null,
"e": 530,
"s": 509,
"text": "CREATE DATABASE GFG;"
},
{
"code": null,
"e": 550,
"s": 530,
"text": "Using the Database:"
},
{
"code": null,
"e": 619,
"s": 550,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 628,
"s": 619,
"text": "USE GFG;"
},
{
"code": null,
"e": 643,
"s": 628,
"text": "Adding Tables:"
},
{
"code": null,
"e": 695,
"s": 643,
"text": "Now we create two tables named as table1 and table2"
},
{
"code": null,
"e": 874,
"s": 695,
"text": "CREATE TABLE table1\n(\n Name1 VARCHAR(20),\n ID1 INT PRIMARY KEY,\n Salary1 INT\n);\n\nCREATE TABLE table2\n(\n Name2 VARCHAR(20),\n ID2 INT PRIMARY KEY,\n Salary2 INT\n);"
},
{
"code": null,
"e": 901,
"s": 874,
"text": "Now, adding data to tables"
},
{
"code": null,
"e": 1090,
"s": 901,
"text": "INSERT INTO table1\nValUES\n('Harish',1,1000),\n('Rakesh',2,2000),\n('Mukesh',3,3000),\n('Suresh',4,4000),\n('Ramesh',5,4000);\n\nINSERT INTO table2\nVALUES\n('Astitva',1,4000),\n('Maharaj',2,41000);"
},
{
"code": null,
"e": 1151,
"s": 1090,
"text": "To verify the contents of the table use the below statement:"
},
{
"code": null,
"e": 1163,
"s": 1151,
"text": "For table1:"
},
{
"code": null,
"e": 1185,
"s": 1163,
"text": "SELECT * FROM table1;"
},
{
"code": null,
"e": 1197,
"s": 1185,
"text": "For table2:"
},
{
"code": null,
"e": 1219,
"s": 1197,
"text": "SELECT * FROM table2;"
},
{
"code": null,
"e": 1378,
"s": 1219,
"text": "Now as we can see there are no two columns that are the same in the above two tables. Now to merge them into a single table we are having 3 different methods."
},
{
"code": null,
"e": 1913,
"s": 1378,
"text": "Method 1 (Cross Join): As you might have heard of several joins like inner join, outer join, in the same way cross join is there, which is used to form the Cartesian product of the tables without or with common columns. So since these joins doesn’t check for any column just they do a product of the two tables, so these joins are not regarded good for any query since repetition of data will be resulted from these joins. Also, inconsistency would be there. But since we are interested in knowing the methods so we are discussing it."
},
{
"code": null,
"e": 2024,
"s": 1913,
"text": "To do cross join we are just required to specify the name of table in FROM clause. No, WHERE clause is needed."
},
{
"code": null,
"e": 2054,
"s": 2024,
"text": "SELECT * FROM table1, table2;"
},
{
"code": null,
"e": 2061,
"s": 2054,
"text": "5*2=10"
},
{
"code": null,
"e": 2350,
"s": 2061,
"text": "Method 2 (UNION Method): This method is different from the above one as it is not merely a join. Its main aim is to combine the table through Row by Row method. It just adds the number of UNIQUE rows of the two tables and name the columns based on the first table specified in the method."
},
{
"code": null,
"e": 2399,
"s": 2350,
"text": "SELECT *\nFROM TABLE1\nUNION\nSELECT *\nFROM TABLE2;"
},
{
"code": null,
"e": 2488,
"s": 2399,
"text": "This returns all the rows(unique) combined together under the column name of the TABLE1."
},
{
"code": null,
"e": 2574,
"s": 2488,
"text": "We can also query single columns or rename the columns in this method as shown below:"
},
{
"code": null,
"e": 2655,
"s": 2574,
"text": "SELECT salary1 as salary\nFROM TABLE1\nUNION\nSELECT salary2 as salary\nFROM TABLE2;"
},
{
"code": null,
"e": 2792,
"s": 2655,
"text": "Hence we are able to select all the salaries possible and given to different clients in the two tables. This method returns unique data."
},
{
"code": null,
"e": 3011,
"s": 2792,
"text": "Method 3 (UNION ALL): The only difference between the UNION and UNIONALL method is that the previous one allows non-duplicates(unique) rows, but latter one results in all possible rows by combining the duplicates also."
},
{
"code": null,
"e": 3096,
"s": 3011,
"text": "SELECT salary1 as salary\nFROM TABLE1\nUNION all\nSELECT salary2 as salary\nFROM TABLE2;"
},
{
"code": null,
"e": 3253,
"s": 3096,
"text": "Hence we are able to see the three different methods to combine table with non-common columns. These methods are used under separate conditions as demanded."
},
{
"code": null,
"e": 3260,
"s": 3253,
"text": "Picked"
},
{
"code": null,
"e": 3270,
"s": 3260,
"text": "SQL-Query"
},
{
"code": null,
"e": 3274,
"s": 3270,
"text": "SQL"
},
{
"code": null,
"e": 3278,
"s": 3274,
"text": "SQL"
},
{
"code": null,
"e": 3376,
"s": 3278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3393,
"s": 3376,
"text": "SQL using Python"
},
{
"code": null,
"e": 3415,
"s": 3393,
"text": "Introduction to NoSQL"
},
{
"code": null,
"e": 3439,
"s": 3415,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 3505,
"s": 3439,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 3537,
"s": 3505,
"text": "SQL Interview Questions | Set 1"
},
{
"code": null,
"e": 3573,
"s": 3537,
"text": "Advantages and Disadvantages of SQL"
},
{
"code": null,
"e": 3588,
"s": 3573,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 3621,
"s": 3588,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 3653,
"s": 3621,
"text": "What is Temporary Table in SQL?"
}
] |
How to set the size of specific flex-item using CSS? - GeeksforGeeks | 23 Apr, 2021
CSS provides Flexible box layout module, also known as flexbox, which makes it easier to design flexible responsive layout. To start using a flexbox model, we need to first define a flex container and the direct child elements of the container are called flex items.
Flex has following pre-defined properties in order to change the size of the flex items.
order
flex-grow
flex-shrink
flex-basis
flex
align-self
Syntax:
flex-item: order | flex-grow | flex-shrink |
flex-basis | auto | align-self |
flex | initial | inherit;
Sample code:
HTML
<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: "#000000"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class="flex-container"> <div>A</div> <div>B</div> <div>C</div> </div></body> </html>
Output:
1. order: This property can be used to specify the order of the flex items.
Example: Below code illustrates the use of flex order.
HTML
<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: "#000000"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class="flex-container"> <div style="order: 2">A</div> <div style="order: 3">B</div> <div style="order: 1">C</div> </div></body> </html>
Output:
2. flex-grow: This property can be used to specify how much an item can grow relative to other items in the container.
Example: Below code illustrates the use of flex-grow property value.
HTML
<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 80%; } .flex-container > div { background-color: rgb(33, 246, 107); color: "#000000"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class="flex-container"> <div style="flex-grow: 1">A</div> <div style="flex-grow: 3">B</div> <div style="flex-grow: 6">C</div> </div></body> </html>
Output:
3. flex-shrink: This property can be used to specify how a much an item can shrink relative to other items in the container. Its default value is 1.
Example: Below code illustrates the use of flex-shrink property value.
HTML
<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: "#000000"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class="flex-container"> <div>A</div> <div style="flex-shrink: 0">B</div> <div>C</div> <div>D</div> <div>E</div> <div>F</div> </div></body> </html>
Output:
4. flex-basis: This property can be used to specify the initial length of an item in the flex container.
Example: Below code illustrates the use of flex-basis.
HTML
<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: "#000000"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class="flex-container"> <div>A</div> <div style="flex-basis: 250px">B</div> <div>C</div> </div></body> </html>
Output:
5. flex: This property is a compilation of flex-grow, flex-shrink and flex-basis. You can specify all the three properties within flex.
Example: Below code illustrates the use of flex.
HTML
<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: "#000000"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class="flex-container"> <div>A</div> <div style="flex: 2 0 200px">B</div> <div>C</div> </div></body> </html>
Output:
6. align-self: This property can be used to specify the alignment of the selected element. When defined, it overrides the alignment defined by the container. It takes values: center, flex-start or flex-end.
Example: Below code illustrates the use of flex align-self property value.
HTML
<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; height: 250px; } .flex-container > div { background-color: rgb(33, 246, 107); color: "#000000"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class="flex-container"> <div style="align-self: flex-start">A</div> <div style="align-self: center">B</div> <div style="align-self: flex-end">C</div> </div></body> </html>
Output:
CSS-Properties
CSS-Questions
Picked
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
How to style a checkbox using CSS?
Search Bar using HTML, CSS and 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 ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 26888,
"s": 26621,
"text": "CSS provides Flexible box layout module, also known as flexbox, which makes it easier to design flexible responsive layout. To start using a flexbox model, we need to first define a flex container and the direct child elements of the container are called flex items."
},
{
"code": null,
"e": 26977,
"s": 26888,
"text": "Flex has following pre-defined properties in order to change the size of the flex items."
},
{
"code": null,
"e": 26983,
"s": 26977,
"text": "order"
},
{
"code": null,
"e": 26993,
"s": 26983,
"text": "flex-grow"
},
{
"code": null,
"e": 27005,
"s": 26993,
"text": "flex-shrink"
},
{
"code": null,
"e": 27016,
"s": 27005,
"text": "flex-basis"
},
{
"code": null,
"e": 27021,
"s": 27016,
"text": "flex"
},
{
"code": null,
"e": 27032,
"s": 27021,
"text": "align-self"
},
{
"code": null,
"e": 27040,
"s": 27032,
"text": "Syntax:"
},
{
"code": null,
"e": 27168,
"s": 27040,
"text": "flex-item: order | flex-grow | flex-shrink | \n flex-basis | auto | align-self | \n flex | initial | inherit;"
},
{
"code": null,
"e": 27181,
"s": 27168,
"text": "Sample code:"
},
{
"code": null,
"e": 27186,
"s": 27181,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: \"#000000\"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class=\"flex-container\"> <div>A</div> <div>B</div> <div>C</div> </div></body> </html>",
"e": 27673,
"s": 27186,
"text": null
},
{
"code": null,
"e": 27683,
"s": 27675,
"text": "Output:"
},
{
"code": null,
"e": 27759,
"s": 27683,
"text": "1. order: This property can be used to specify the order of the flex items."
},
{
"code": null,
"e": 27814,
"s": 27759,
"text": "Example: Below code illustrates the use of flex order."
},
{
"code": null,
"e": 27819,
"s": 27814,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: \"#000000\"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class=\"flex-container\"> <div style=\"order: 2\">A</div> <div style=\"order: 3\">B</div> <div style=\"order: 1\">C</div> </div></body> </html>",
"e": 28357,
"s": 27819,
"text": null
},
{
"code": null,
"e": 28365,
"s": 28357,
"text": "Output:"
},
{
"code": null,
"e": 28484,
"s": 28365,
"text": "2. flex-grow: This property can be used to specify how much an item can grow relative to other items in the container."
},
{
"code": null,
"e": 28553,
"s": 28484,
"text": "Example: Below code illustrates the use of flex-grow property value."
},
{
"code": null,
"e": 28558,
"s": 28553,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 80%; } .flex-container > div { background-color: rgb(33, 246, 107); color: \"#000000\"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class=\"flex-container\"> <div style=\"flex-grow: 1\">A</div> <div style=\"flex-grow: 3\">B</div> <div style=\"flex-grow: 6\">C</div> </div></body> </html>",
"e": 29114,
"s": 28558,
"text": null
},
{
"code": null,
"e": 29122,
"s": 29114,
"text": "Output:"
},
{
"code": null,
"e": 29271,
"s": 29122,
"text": "3. flex-shrink: This property can be used to specify how a much an item can shrink relative to other items in the container. Its default value is 1."
},
{
"code": null,
"e": 29342,
"s": 29271,
"text": "Example: Below code illustrates the use of flex-shrink property value."
},
{
"code": null,
"e": 29347,
"s": 29342,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: \"#000000\"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class=\"flex-container\"> <div>A</div> <div style=\"flex-shrink: 0\">B</div> <div>C</div> <div>D</div> <div>E</div> <div>F</div> </div></body> </html>",
"e": 29911,
"s": 29347,
"text": null
},
{
"code": null,
"e": 29919,
"s": 29911,
"text": "Output:"
},
{
"code": null,
"e": 30024,
"s": 29919,
"text": "4. flex-basis: This property can be used to specify the initial length of an item in the flex container."
},
{
"code": null,
"e": 30079,
"s": 30024,
"text": "Example: Below code illustrates the use of flex-basis."
},
{
"code": null,
"e": 30084,
"s": 30079,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: \"#000000\"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class=\"flex-container\"> <div>A</div> <div style=\"flex-basis: 250px\">B</div> <div>C</div> </div></body> </html>",
"e": 30597,
"s": 30084,
"text": null
},
{
"code": null,
"e": 30605,
"s": 30597,
"text": "Output:"
},
{
"code": null,
"e": 30741,
"s": 30605,
"text": "5. flex: This property is a compilation of flex-grow, flex-shrink and flex-basis. You can specify all the three properties within flex."
},
{
"code": null,
"e": 30790,
"s": 30741,
"text": "Example: Below code illustrates the use of flex."
},
{
"code": null,
"e": 30795,
"s": 30790,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; } .flex-container > div { background-color: rgb(33, 246, 107); color: \"#000000\"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class=\"flex-container\"> <div>A</div> <div style=\"flex: 2 0 200px\">B</div> <div>C</div> </div></body> </html>",
"e": 31286,
"s": 30795,
"text": null
},
{
"code": null,
"e": 31294,
"s": 31286,
"text": "Output:"
},
{
"code": null,
"e": 31502,
"s": 31294,
"text": "6. align-self: This property can be used to specify the alignment of the selected element. When defined, it overrides the alignment defined by the container. It takes values: center, flex-start or flex-end. "
},
{
"code": null,
"e": 31577,
"s": 31502,
"text": "Example: Below code illustrates the use of flex align-self property value."
},
{
"code": null,
"e": 31582,
"s": 31577,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; background-color: #f1f1f1; width: 50%; height: 250px; } .flex-container > div { background-color: rgb(33, 246, 107); color: \"#000000\"; width: 100px; margin: 15px; text-align: center; line-height: 75px; font-size: 35px; } </style></head> <body> <div class=\"flex-container\"> <div style=\"align-self: flex-start\">A</div> <div style=\"align-self: center\">B</div> <div style=\"align-self: flex-end\">C</div> </div></body> </html>",
"e": 32178,
"s": 31582,
"text": null
},
{
"code": null,
"e": 32186,
"s": 32178,
"text": "Output:"
},
{
"code": null,
"e": 32201,
"s": 32186,
"text": "CSS-Properties"
},
{
"code": null,
"e": 32215,
"s": 32201,
"text": "CSS-Questions"
},
{
"code": null,
"e": 32222,
"s": 32215,
"text": "Picked"
},
{
"code": null,
"e": 32226,
"s": 32222,
"text": "CSS"
},
{
"code": null,
"e": 32243,
"s": 32226,
"text": "Web Technologies"
},
{
"code": null,
"e": 32341,
"s": 32243,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32380,
"s": 32341,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32417,
"s": 32380,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32446,
"s": 32417,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32481,
"s": 32446,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 32523,
"s": 32481,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32563,
"s": 32523,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32596,
"s": 32563,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32641,
"s": 32596,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32684,
"s": 32641,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Find number of months between two dates in R - GeeksforGeeks | 07 Sep, 2021
In this article, we will discuss how to Find the number of months between two dates in the R programming language.
Example:
Input: Date_1 = 2020/02/21
Date_2 = 2020/03/21
Output: 1
Explanation: In Date_1 and Date_2 have only one difference in month.
Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector. It takes the length and difference between values as optional argument.
Syntax: length(seq(from=date_1, to=date_2, by=’month’)) -1
Where: seq is function generates a sequence of numbers, from is starting date, to is ending date.
Example 1: In the below example, we are storing two dates in two different variables and by using length(seq(from=date_1, to=date_2, by=’month’)) we are finding a number of months between these two dates.
R
# creating date_1 variable and storing date in it.date_1<-as.Date("2020-08-10") # creating date_2 variable and storing date in it.date_2<-as.Date("2020-10-10") # Here first date will start from 2020-08-10 and# end by 2020-10-10.Here increment is done by month.# This three dates will be generated as we used# seq and this dates will be stored in a. a = seq(from = date_1, to = date_2, by = 'month')) # Here we are finding length of a and we are subtracting# 1 because we dont need to include current month.length(a)-1
Output:
2
Example 2: Checking with different dates.
R
# creating date_1 variable and storing date in it.date_1<-as.Date("2020-01-23") # creating date_2 variable and storing date in it.date_2<-as.Date("2020-9-25") # Here first date will start from 2020-01-23# and end by 2020-9-25.Here increment is done# by month.This three dates will be generated# as we used seq and this dates will be stored in a. a=seq(from = date_1, to = date_2, by = 'month')) # Here we are finding length of a and we are# subtracting 1 because we dont need to include# current month.length(a)-1
Output:
8
anikakapoor
Picked
R Vector-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
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ? | [
{
"code": null,
"e": 26512,
"s": 26484,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 26628,
"s": 26512,
"text": "In this article, we will discuss how to Find the number of months between two dates in the R programming language. "
},
{
"code": null,
"e": 26637,
"s": 26628,
"text": "Example:"
},
{
"code": null,
"e": 26664,
"s": 26637,
"text": "Input: Date_1 = 2020/02/21"
},
{
"code": null,
"e": 26686,
"s": 26664,
"text": " Date_2 = 2020/03/21"
},
{
"code": null,
"e": 26696,
"s": 26686,
"text": "Output: 1"
},
{
"code": null,
"e": 26765,
"s": 26696,
"text": "Explanation: In Date_1 and Date_2 have only one difference in month."
},
{
"code": null,
"e": 26956,
"s": 26765,
"text": "Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector. It takes the length and difference between values as optional argument."
},
{
"code": null,
"e": 27016,
"s": 26956,
"text": "Syntax: length(seq(from=date_1, to=date_2, by=’month’)) -1 "
},
{
"code": null,
"e": 27114,
"s": 27016,
"text": "Where: seq is function generates a sequence of numbers, from is starting date, to is ending date."
},
{
"code": null,
"e": 27320,
"s": 27114,
"text": " Example 1: In the below example, we are storing two dates in two different variables and by using length(seq(from=date_1, to=date_2, by=’month’)) we are finding a number of months between these two dates."
},
{
"code": null,
"e": 27322,
"s": 27320,
"text": "R"
},
{
"code": "# creating date_1 variable and storing date in it.date_1<-as.Date(\"2020-08-10\") # creating date_2 variable and storing date in it.date_2<-as.Date(\"2020-10-10\") # Here first date will start from 2020-08-10 and# end by 2020-10-10.Here increment is done by month.# This three dates will be generated as we used# seq and this dates will be stored in a. a = seq(from = date_1, to = date_2, by = 'month')) # Here we are finding length of a and we are subtracting# 1 because we dont need to include current month.length(a)-1",
"e": 27842,
"s": 27322,
"text": null
},
{
"code": null,
"e": 27850,
"s": 27842,
"text": "Output:"
},
{
"code": null,
"e": 27852,
"s": 27850,
"text": "2"
},
{
"code": null,
"e": 27894,
"s": 27852,
"text": "Example 2: Checking with different dates."
},
{
"code": null,
"e": 27896,
"s": 27894,
"text": "R"
},
{
"code": "# creating date_1 variable and storing date in it.date_1<-as.Date(\"2020-01-23\") # creating date_2 variable and storing date in it.date_2<-as.Date(\"2020-9-25\") # Here first date will start from 2020-01-23# and end by 2020-9-25.Here increment is done# by month.This three dates will be generated# as we used seq and this dates will be stored in a. a=seq(from = date_1, to = date_2, by = 'month')) # Here we are finding length of a and we are# subtracting 1 because we dont need to include# current month.length(a)-1",
"e": 28412,
"s": 27896,
"text": null
},
{
"code": null,
"e": 28420,
"s": 28412,
"text": "Output:"
},
{
"code": null,
"e": 28422,
"s": 28420,
"text": "8"
},
{
"code": null,
"e": 28434,
"s": 28422,
"text": "anikakapoor"
},
{
"code": null,
"e": 28441,
"s": 28434,
"text": "Picked"
},
{
"code": null,
"e": 28459,
"s": 28441,
"text": "R Vector-Function"
},
{
"code": null,
"e": 28470,
"s": 28459,
"text": "R Language"
},
{
"code": null,
"e": 28568,
"s": 28470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28620,
"s": 28568,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28655,
"s": 28620,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28693,
"s": 28655,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28751,
"s": 28693,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28794,
"s": 28751,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28843,
"s": 28794,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28860,
"s": 28843,
"text": "R - if statement"
},
{
"code": null,
"e": 28910,
"s": 28860,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28962,
"s": 28910,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
JavaScript | trimStart() and trimLeft() Method - GeeksforGeeks | 30 Dec, 2019
The trimStart() method in JavaScript is used to remove whitespace from the beginning of a string. The value of the string is not modified in any manner, including any whitespace present after the string.
Syntax:
string.trimStart()
Return Value: It returns the final string that is stripped out of all the white-space in the beginning.
Example: This example implements the trimStart() method.
<!DOCTYPE html><html> <head> <title> JavaScript trimStart() method </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript | trimStart() method </b> <pre>Output for " GeeksforGeeks " : <span class="output"></span> </pre> <pre>Output for "Hello There! " : <span class="output_2"></span> </pre> <button onclick="trimString()"> Trim Start </button> <script type="text/javascript"> function trimString() { str1 = " GeeksforGeeks "; str2 = "Hello There! "; trimmed_out = str1.trimStart(); trimmed_out2 = str2.trimStart(); document.querySelector('.output') .textContent = '"' + trimmed_out + '"'; document.querySelector('.output_2') .textContent = '"' + trimmed_out2 + '"'; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
The trimLeft() alias: The trimStart() method has an alias which is the trimLeft() method. It performs exactly the same function as trimStart() method.
Syntax:
string.trimLeft()
Return Value: It returns the final string that is stripped out of all the white-space in the beginning.
Example: This example implements the trimLeft() method.
<!DOCTYPE html><html> <head> <title> JavaScript | trimLeft() method </title></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript | trimLeft() method </b> <pre>Output for " GeeksforGeeks " : <span class="output"></span> </pre> <pre>Output for "Portal " : <span class="output_2"></span> </pre> <button onclick="trimString()"> Trim Left </button> <script type="text/javascript"> function trimString() { str1 = " GeeksforGeeks "; str2 = "Portal "; trimmed_out = str1.trimLeft(); trimmed_out2 = str2.trimLeft(); document.querySelector('.output') .textContent = '"' + trimmed_out + '"'; document.querySelector('.output_2') .textContent = '"' + trimmed_out2 + '"'; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Supported Browsers: The browsers supported by trimStart() method are listed below:
Google Chrome 60
Firefox 61
Edge 12
Safari 12
Opera 53
javascript-functions
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 append HTML code to a div using 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 ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25949,
"s": 25921,
"text": "\n30 Dec, 2019"
},
{
"code": null,
"e": 26153,
"s": 25949,
"text": "The trimStart() method in JavaScript is used to remove whitespace from the beginning of a string. The value of the string is not modified in any manner, including any whitespace present after the string."
},
{
"code": null,
"e": 26161,
"s": 26153,
"text": "Syntax:"
},
{
"code": null,
"e": 26180,
"s": 26161,
"text": "string.trimStart()"
},
{
"code": null,
"e": 26284,
"s": 26180,
"text": "Return Value: It returns the final string that is stripped out of all the white-space in the beginning."
},
{
"code": null,
"e": 26341,
"s": 26284,
"text": "Example: This example implements the trimStart() method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript trimStart() method </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript | trimStart() method </b> <pre>Output for \" GeeksforGeeks \" : <span class=\"output\"></span> </pre> <pre>Output for \"Hello There! \" : <span class=\"output_2\"></span> </pre> <button onclick=\"trimString()\"> Trim Start </button> <script type=\"text/javascript\"> function trimString() { str1 = \" GeeksforGeeks \"; str2 = \"Hello There! \"; trimmed_out = str1.trimStart(); trimmed_out2 = str2.trimStart(); document.querySelector('.output') .textContent = '\"' + trimmed_out + '\"'; document.querySelector('.output_2') .textContent = '\"' + trimmed_out2 + '\"'; } </script></body> </html>",
"e": 27337,
"s": 26341,
"text": null
},
{
"code": null,
"e": 27345,
"s": 27337,
"text": "Output:"
},
{
"code": null,
"e": 27373,
"s": 27345,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27400,
"s": 27373,
"text": "After clicking the button:"
},
{
"code": null,
"e": 27551,
"s": 27400,
"text": "The trimLeft() alias: The trimStart() method has an alias which is the trimLeft() method. It performs exactly the same function as trimStart() method."
},
{
"code": null,
"e": 27559,
"s": 27551,
"text": "Syntax:"
},
{
"code": null,
"e": 27577,
"s": 27559,
"text": "string.trimLeft()"
},
{
"code": null,
"e": 27681,
"s": 27577,
"text": "Return Value: It returns the final string that is stripped out of all the white-space in the beginning."
},
{
"code": null,
"e": 27737,
"s": 27681,
"text": "Example: This example implements the trimLeft() method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | trimLeft() method </title></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript | trimLeft() method </b> <pre>Output for \" GeeksforGeeks \" : <span class=\"output\"></span> </pre> <pre>Output for \"Portal \" : <span class=\"output_2\"></span> </pre> <button onclick=\"trimString()\"> Trim Left </button> <script type=\"text/javascript\"> function trimString() { str1 = \" GeeksforGeeks \"; str2 = \"Portal \"; trimmed_out = str1.trimLeft(); trimmed_out2 = str2.trimLeft(); document.querySelector('.output') .textContent = '\"' + trimmed_out + '\"'; document.querySelector('.output_2') .textContent = '\"' + trimmed_out2 + '\"'; } </script></body> </html>",
"e": 28737,
"s": 27737,
"text": null
},
{
"code": null,
"e": 28745,
"s": 28737,
"text": "Output:"
},
{
"code": null,
"e": 28773,
"s": 28745,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 28800,
"s": 28773,
"text": "After clicking the button:"
},
{
"code": null,
"e": 28883,
"s": 28800,
"text": "Supported Browsers: The browsers supported by trimStart() method are listed below:"
},
{
"code": null,
"e": 28900,
"s": 28883,
"text": "Google Chrome 60"
},
{
"code": null,
"e": 28911,
"s": 28900,
"text": "Firefox 61"
},
{
"code": null,
"e": 28919,
"s": 28911,
"text": "Edge 12"
},
{
"code": null,
"e": 28929,
"s": 28919,
"text": "Safari 12"
},
{
"code": null,
"e": 28938,
"s": 28929,
"text": "Opera 53"
},
{
"code": null,
"e": 28959,
"s": 28938,
"text": "javascript-functions"
},
{
"code": null,
"e": 28970,
"s": 28959,
"text": "JavaScript"
},
{
"code": null,
"e": 28987,
"s": 28970,
"text": "Web Technologies"
},
{
"code": null,
"e": 29085,
"s": 28987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29125,
"s": 29085,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29170,
"s": 29125,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29231,
"s": 29170,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29303,
"s": 29231,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29355,
"s": 29303,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29395,
"s": 29355,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29428,
"s": 29395,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29473,
"s": 29428,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29516,
"s": 29473,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
log2() function in C++ with Examples - GeeksforGeeks | 04 May, 2020
The function log2() of cmath header file in C++ is used to find the logarithmic value with base 2 of the passed argument.
Syntax:
log2(x)
Parameters: This function takes a value x, in the range [0, ∞] whose log value is to be found.
Return Type: It returns the logarithmic value, as double, float or long double type, based on the following conditions:
If x > 1: It returns the positive logarithmic value of x.
If x is equals to 1: It returns 0.
If 0 < x < 1: It returns the negative logarithmic value of x.
If x is equals to 0: It returns the negative infinity(-∞).
If x < 0: It returns NaN(Not a Number).
Below examples demonstrate the use of log2() method:
Example 1:
// C++ program to illustrate log2() function #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ long b = 16; float c = 2.5; double d = 10.35; long double e = 25.5; // Logarithmic value of long datatype cout << log2(b) << "\n"; // Logarithmic value of float datatype cout << log2(c) << "\n"; // Logarithmic value of double datatype cout << log2(d) << "\n"; // Logarithmic value of long double datatype cout << log2(e) << "\n"; return 0;}
4
1.32193
3.37156
4.67243
Example 2:
// C++ program to illustrate log2() function #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // To show extreme cases int a = 0; int b = -16; // Logarithmic value of 0 cout << log2(a) << "\n"; // Logarithmic value of negative value cout << log2(b) << "\n"; return 0;}
-inf
nan
Reference: http://www.cplusplus.com/reference/cmath/log2/
CPP-Functions
cpp-math
C++
Mathematical
Mathematical
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++
Program for Fibonacci numbers
Write a program to print all permutations of a given string
Coin Change | DP-7
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 25421,
"s": 25393,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 25543,
"s": 25421,
"text": "The function log2() of cmath header file in C++ is used to find the logarithmic value with base 2 of the passed argument."
},
{
"code": null,
"e": 25551,
"s": 25543,
"text": "Syntax:"
},
{
"code": null,
"e": 25559,
"s": 25551,
"text": "log2(x)"
},
{
"code": null,
"e": 25654,
"s": 25559,
"text": "Parameters: This function takes a value x, in the range [0, ∞] whose log value is to be found."
},
{
"code": null,
"e": 25774,
"s": 25654,
"text": "Return Type: It returns the logarithmic value, as double, float or long double type, based on the following conditions:"
},
{
"code": null,
"e": 25832,
"s": 25774,
"text": "If x > 1: It returns the positive logarithmic value of x."
},
{
"code": null,
"e": 25867,
"s": 25832,
"text": "If x is equals to 1: It returns 0."
},
{
"code": null,
"e": 25929,
"s": 25867,
"text": "If 0 < x < 1: It returns the negative logarithmic value of x."
},
{
"code": null,
"e": 25988,
"s": 25929,
"text": "If x is equals to 0: It returns the negative infinity(-∞)."
},
{
"code": null,
"e": 26028,
"s": 25988,
"text": "If x < 0: It returns NaN(Not a Number)."
},
{
"code": null,
"e": 26081,
"s": 26028,
"text": "Below examples demonstrate the use of log2() method:"
},
{
"code": null,
"e": 26092,
"s": 26081,
"text": "Example 1:"
},
{
"code": "// C++ program to illustrate log2() function #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ long b = 16; float c = 2.5; double d = 10.35; long double e = 25.5; // Logarithmic value of long datatype cout << log2(b) << \"\\n\"; // Logarithmic value of float datatype cout << log2(c) << \"\\n\"; // Logarithmic value of double datatype cout << log2(d) << \"\\n\"; // Logarithmic value of long double datatype cout << log2(e) << \"\\n\"; return 0;}",
"e": 26600,
"s": 26092,
"text": null
},
{
"code": null,
"e": 26627,
"s": 26600,
"text": "4\n1.32193\n3.37156\n4.67243\n"
},
{
"code": null,
"e": 26638,
"s": 26627,
"text": "Example 2:"
},
{
"code": "// C++ program to illustrate log2() function #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // To show extreme cases int a = 0; int b = -16; // Logarithmic value of 0 cout << log2(a) << \"\\n\"; // Logarithmic value of negative value cout << log2(b) << \"\\n\"; return 0;}",
"e": 26961,
"s": 26638,
"text": null
},
{
"code": null,
"e": 26971,
"s": 26961,
"text": "-inf\nnan\n"
},
{
"code": null,
"e": 27029,
"s": 26971,
"text": "Reference: http://www.cplusplus.com/reference/cmath/log2/"
},
{
"code": null,
"e": 27043,
"s": 27029,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27052,
"s": 27043,
"text": "cpp-math"
},
{
"code": null,
"e": 27056,
"s": 27052,
"text": "C++"
},
{
"code": null,
"e": 27069,
"s": 27056,
"text": "Mathematical"
},
{
"code": null,
"e": 27082,
"s": 27069,
"text": "Mathematical"
},
{
"code": null,
"e": 27086,
"s": 27082,
"text": "CPP"
},
{
"code": null,
"e": 27184,
"s": 27086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27212,
"s": 27184,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27232,
"s": 27212,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27265,
"s": 27232,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27289,
"s": 27265,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27314,
"s": 27289,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27344,
"s": 27314,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 27404,
"s": 27344,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 27423,
"s": 27404,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 27447,
"s": 27423,
"text": "Merge two sorted arrays"
}
] |
Create MySQL Database Login Page in Python using Tkinter - GeeksforGeeks | 18 Jan, 2022
Prerequisites: Python GUI – tkinter, Python MySQL – Select QueryTkinter is one of the Python libraries which contains many functions for the development of graphic user interface pages and windows. Login pages are important for the development of any kind of mobile or web application. This page is most essential for user authentication purposes.We will use mysql.connector library to establish a connection between Python project and MySQL workbench. Db is the object created using mysql.connector.connect class which stores all the information about databases such database name, password, and table name.
In the below example,
tk.label and tk.button is used to create labels and buttons on the GUI screen. Every button contains a command in it which includes a function to be executed on click of the button.
The function logintodb is created to login into the MySQL Database. The save query includes the query to be executed on the click of the submit button.
X and Y are the parameters given to adjust objects on the Tkinter window.
Root.mainloop() is included at the last indicating that only components within it are included in the window.
Below is the implementation:
Python3
import tkinter as tkimport mysql.connectorfrom tkinter import * def submitact(): user = Username.get() passw = password.get() print(f"The name entered by you is {user} {passw}") logintodb(user, passw) def logintodb(user, passw): # If password is enetered by the # user if passw: db = mysql.connector.connect(host ="localhost", user = user, password = passw, db ="College") cursor = db.cursor() # If no password is enetered by the # user else: db = mysql.connector.connect(host ="localhost", user = user, db ="College") cursor = db.cursor() # A Table in the database savequery = "select * from STUDENT" try: cursor.execute(savequery) myresult = cursor.fetchall() # Printing the result of the # query for x in myresult: print(x) print("Query Executed successfully") except: db.rollback() print("Error occured") root = tk.Tk()root.geometry("300x300")root.title("DBMS Login Page") # Defining the first rowlblfrstrow = tk.Label(root, text ="Username -", )lblfrstrow.place(x = 50, y = 20) Username = tk.Entry(root, width = 35)Username.place(x = 150, y = 20, width = 100) lblsecrow = tk.Label(root, text ="Password -")lblsecrow.place(x = 50, y = 50) password = tk.Entry(root, width = 35)password.place(x = 150, y = 50, width = 100) submitbtn = tk.Button(root, text ="Login", bg ='blue', command = submitact)submitbtn.place(x = 150, y = 135, width = 55) root.mainloop()
Output:
nidhi_biet
kavania2002
ruhelaa48
adnanirshad158
sumitgumber28
Python-mySQL
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25611,
"s": 25583,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 26221,
"s": 25611,
"text": "Prerequisites: Python GUI – tkinter, Python MySQL – Select QueryTkinter is one of the Python libraries which contains many functions for the development of graphic user interface pages and windows. Login pages are important for the development of any kind of mobile or web application. This page is most essential for user authentication purposes.We will use mysql.connector library to establish a connection between Python project and MySQL workbench. Db is the object created using mysql.connector.connect class which stores all the information about databases such database name, password, and table name. "
},
{
"code": null,
"e": 26244,
"s": 26221,
"text": "In the below example, "
},
{
"code": null,
"e": 26426,
"s": 26244,
"text": "tk.label and tk.button is used to create labels and buttons on the GUI screen. Every button contains a command in it which includes a function to be executed on click of the button."
},
{
"code": null,
"e": 26578,
"s": 26426,
"text": "The function logintodb is created to login into the MySQL Database. The save query includes the query to be executed on the click of the submit button."
},
{
"code": null,
"e": 26652,
"s": 26578,
"text": "X and Y are the parameters given to adjust objects on the Tkinter window."
},
{
"code": null,
"e": 26762,
"s": 26652,
"text": "Root.mainloop() is included at the last indicating that only components within it are included in the window."
},
{
"code": null,
"e": 26791,
"s": 26762,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 26799,
"s": 26791,
"text": "Python3"
},
{
"code": "import tkinter as tkimport mysql.connectorfrom tkinter import * def submitact(): user = Username.get() passw = password.get() print(f\"The name entered by you is {user} {passw}\") logintodb(user, passw) def logintodb(user, passw): # If password is enetered by the # user if passw: db = mysql.connector.connect(host =\"localhost\", user = user, password = passw, db =\"College\") cursor = db.cursor() # If no password is enetered by the # user else: db = mysql.connector.connect(host =\"localhost\", user = user, db =\"College\") cursor = db.cursor() # A Table in the database savequery = \"select * from STUDENT\" try: cursor.execute(savequery) myresult = cursor.fetchall() # Printing the result of the # query for x in myresult: print(x) print(\"Query Executed successfully\") except: db.rollback() print(\"Error occured\") root = tk.Tk()root.geometry(\"300x300\")root.title(\"DBMS Login Page\") # Defining the first rowlblfrstrow = tk.Label(root, text =\"Username -\", )lblfrstrow.place(x = 50, y = 20) Username = tk.Entry(root, width = 35)Username.place(x = 150, y = 20, width = 100) lblsecrow = tk.Label(root, text =\"Password -\")lblsecrow.place(x = 50, y = 50) password = tk.Entry(root, width = 35)password.place(x = 150, y = 50, width = 100) submitbtn = tk.Button(root, text =\"Login\", bg ='blue', command = submitact)submitbtn.place(x = 150, y = 135, width = 55) root.mainloop()",
"e": 28563,
"s": 26799,
"text": null
},
{
"code": null,
"e": 28572,
"s": 28563,
"text": "Output: "
},
{
"code": null,
"e": 28585,
"s": 28574,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28597,
"s": 28585,
"text": "kavania2002"
},
{
"code": null,
"e": 28607,
"s": 28597,
"text": "ruhelaa48"
},
{
"code": null,
"e": 28622,
"s": 28607,
"text": "adnanirshad158"
},
{
"code": null,
"e": 28636,
"s": 28622,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28649,
"s": 28636,
"text": "Python-mySQL"
},
{
"code": null,
"e": 28664,
"s": 28649,
"text": "Python-tkinter"
},
{
"code": null,
"e": 28671,
"s": 28664,
"text": "Python"
},
{
"code": null,
"e": 28769,
"s": 28671,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28787,
"s": 28769,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28822,
"s": 28787,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28854,
"s": 28822,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28876,
"s": 28854,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28918,
"s": 28876,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28948,
"s": 28918,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28974,
"s": 28948,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29003,
"s": 28974,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29047,
"s": 29003,
"text": "Reading and Writing to text files in Python"
}
] |
Insertion sort using C++ STL - GeeksforGeeks | 30 Aug, 2017
Implementation of Insertion Sort using STL functions.
Pre-requisites : Insertion Sort, std::rotate, std::upper_bound, C++ Iterators.
The idea is to use std::upper_bound to find an element making the array unsorted. Then we can rotate the unsorted part so that it ends up sorted. We can traverse the array doing these operations and the result will be a sorted array.
The code is offline on purpose to show hard-coded and easy to understand code.
// C++ program to implement insertion sort using STL.#include <bits/stdc++.h> // Function to sort the arrayvoid insertionSort(std::vector<int> &vec){ for (auto it = vec.begin(); it != vec.end(); it++) { // Searching the upper bound, i.e., first // element greater than *it from beginning auto const insertion_point = std::upper_bound(vec.begin(), it, *it); // Shifting the unsorted part std::rotate(insertion_point, it, it+1); }} // Function to print the arrayvoid print(std::vector<int> vec){ for( int x : vec) std::cout << x << " "; std::cout << '\n';} // Driver codeint main(){ std::vector<int> arr = {2, 1, 5, 3, 7, 5, 4, 6}; insertionSort(arr); print(arr);}
Output:
1 2 3 4 5 5 6 7
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Insertion Sort
STL
Sorting
Sorting
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
C++ Program for QuickSort
Stability in sorting algorithms
Quick Sort vs Merge Sort
Number of visible boxes after putting one inside another
Sorting in Java
Quickselect Algorithm
Find all triplets with zero sum
Recursive Bubble Sort
Segregate 0s and 1s in an array | [
{
"code": null,
"e": 25321,
"s": 25293,
"text": "\n30 Aug, 2017"
},
{
"code": null,
"e": 25375,
"s": 25321,
"text": "Implementation of Insertion Sort using STL functions."
},
{
"code": null,
"e": 25454,
"s": 25375,
"text": "Pre-requisites : Insertion Sort, std::rotate, std::upper_bound, C++ Iterators."
},
{
"code": null,
"e": 25688,
"s": 25454,
"text": "The idea is to use std::upper_bound to find an element making the array unsorted. Then we can rotate the unsorted part so that it ends up sorted. We can traverse the array doing these operations and the result will be a sorted array."
},
{
"code": null,
"e": 25767,
"s": 25688,
"text": "The code is offline on purpose to show hard-coded and easy to understand code."
},
{
"code": "// C++ program to implement insertion sort using STL.#include <bits/stdc++.h> // Function to sort the arrayvoid insertionSort(std::vector<int> &vec){ for (auto it = vec.begin(); it != vec.end(); it++) { // Searching the upper bound, i.e., first // element greater than *it from beginning auto const insertion_point = std::upper_bound(vec.begin(), it, *it); // Shifting the unsorted part std::rotate(insertion_point, it, it+1); }} // Function to print the arrayvoid print(std::vector<int> vec){ for( int x : vec) std::cout << x << \" \"; std::cout << '\\n';} // Driver codeint main(){ std::vector<int> arr = {2, 1, 5, 3, 7, 5, 4, 6}; insertionSort(arr); print(arr);}",
"e": 26550,
"s": 25767,
"text": null
},
{
"code": null,
"e": 26558,
"s": 26550,
"text": "Output:"
},
{
"code": null,
"e": 26575,
"s": 26558,
"text": "1 2 3 4 5 5 6 7\n"
},
{
"code": null,
"e": 26878,
"s": 26575,
"text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27003,
"s": 26878,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27018,
"s": 27003,
"text": "Insertion Sort"
},
{
"code": null,
"e": 27022,
"s": 27018,
"text": "STL"
},
{
"code": null,
"e": 27030,
"s": 27022,
"text": "Sorting"
},
{
"code": null,
"e": 27038,
"s": 27030,
"text": "Sorting"
},
{
"code": null,
"e": 27042,
"s": 27038,
"text": "STL"
},
{
"code": null,
"e": 27140,
"s": 27042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27171,
"s": 27140,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 27197,
"s": 27171,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27229,
"s": 27197,
"text": "Stability in sorting algorithms"
},
{
"code": null,
"e": 27254,
"s": 27229,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 27311,
"s": 27254,
"text": "Number of visible boxes after putting one inside another"
},
{
"code": null,
"e": 27327,
"s": 27311,
"text": "Sorting in Java"
},
{
"code": null,
"e": 27349,
"s": 27327,
"text": "Quickselect Algorithm"
},
{
"code": null,
"e": 27381,
"s": 27349,
"text": "Find all triplets with zero sum"
},
{
"code": null,
"e": 27403,
"s": 27381,
"text": "Recursive Bubble Sort"
}
] |
How to Show Schema of a Table in MySQL Database? - GeeksforGeeks | 26 Sep, 2021
The term “schema” refers to the organization of data as a blueprint of how the database is constructed (divided into database tables in the case of relational databases). The formal definition of a database schema is a set of formulas (sentences) called integrity constraints imposed on a database. In this article, we will learn how to display the Schema of a Table with the help of some SQL queries.
Step 1: Creating the Database
For the purpose of demonstration, we will be creating a Participant table in a database called “GeeksForGeeksDatabase“.
Query:
CREATE DATABASE GeeksForGeeksDatabase;
Step 2: Using the Database
Use the below SQL statement to switch the database context to GeeksForGeeksDatabase.
Query:
USE GeeksForGeeksDatabase;
Step 3: Table Definition
Query:
CREATE TABLE Geeks(
GeekID INTEGER PRIMARY KEY,
GeekName VARCHAR(255) NOT NULL,
GeekRank INTEGER NOT NULL,
GeekSchool VARCHAR(255) NOT NULL
);
Step 4:To display the table structure (Schema) in SQL
In Oracle, we use this query:
Query:
DESC tableName
In the MySQL database, we use this query:
Query:
DESCRIBE databasename.tableName;
In SQL Server we use Transact-SQL :
Query:
EXEC sp_help 'dbo.tableName';
Using the above query we got the whole description of the table, its properties like column names, data types used for each column, constraints.
Blogathon-2021
mysql
Picked
SQL-Server
Blogathon
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
SQL | WITH clause
SQL | Join (Inner, Left, Right and Full Joins)
ACID Properties in DBMS
SQL query to find second highest salary?
Normal Forms in DBMS | [
{
"code": null,
"e": 26121,
"s": 26093,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 26523,
"s": 26121,
"text": "The term “schema” refers to the organization of data as a blueprint of how the database is constructed (divided into database tables in the case of relational databases). The formal definition of a database schema is a set of formulas (sentences) called integrity constraints imposed on a database. In this article, we will learn how to display the Schema of a Table with the help of some SQL queries."
},
{
"code": null,
"e": 26553,
"s": 26523,
"text": "Step 1: Creating the Database"
},
{
"code": null,
"e": 26673,
"s": 26553,
"text": "For the purpose of demonstration, we will be creating a Participant table in a database called “GeeksForGeeksDatabase“."
},
{
"code": null,
"e": 26680,
"s": 26673,
"text": "Query:"
},
{
"code": null,
"e": 26719,
"s": 26680,
"text": "CREATE DATABASE GeeksForGeeksDatabase;"
},
{
"code": null,
"e": 26748,
"s": 26721,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 26833,
"s": 26748,
"text": "Use the below SQL statement to switch the database context to GeeksForGeeksDatabase."
},
{
"code": null,
"e": 26840,
"s": 26833,
"text": "Query:"
},
{
"code": null,
"e": 26867,
"s": 26840,
"text": "USE GeeksForGeeksDatabase;"
},
{
"code": null,
"e": 26892,
"s": 26867,
"text": "Step 3: Table Definition"
},
{
"code": null,
"e": 26899,
"s": 26892,
"text": "Query:"
},
{
"code": null,
"e": 27042,
"s": 26899,
"text": "CREATE TABLE Geeks(\nGeekID INTEGER PRIMARY KEY,\nGeekName VARCHAR(255) NOT NULL,\nGeekRank INTEGER NOT NULL,\nGeekSchool VARCHAR(255) NOT NULL\n);"
},
{
"code": null,
"e": 27096,
"s": 27042,
"text": "Step 4:To display the table structure (Schema) in SQL"
},
{
"code": null,
"e": 27126,
"s": 27096,
"text": "In Oracle, we use this query:"
},
{
"code": null,
"e": 27133,
"s": 27126,
"text": "Query:"
},
{
"code": null,
"e": 27148,
"s": 27133,
"text": "DESC tableName"
},
{
"code": null,
"e": 27190,
"s": 27148,
"text": "In the MySQL database, we use this query:"
},
{
"code": null,
"e": 27197,
"s": 27190,
"text": "Query:"
},
{
"code": null,
"e": 27230,
"s": 27197,
"text": "DESCRIBE databasename.tableName;"
},
{
"code": null,
"e": 27266,
"s": 27230,
"text": "In SQL Server we use Transact-SQL :"
},
{
"code": null,
"e": 27273,
"s": 27266,
"text": "Query:"
},
{
"code": null,
"e": 27303,
"s": 27273,
"text": "EXEC sp_help 'dbo.tableName';"
},
{
"code": null,
"e": 27448,
"s": 27303,
"text": "Using the above query we got the whole description of the table, its properties like column names, data types used for each column, constraints."
},
{
"code": null,
"e": 27463,
"s": 27448,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27469,
"s": 27463,
"text": "mysql"
},
{
"code": null,
"e": 27476,
"s": 27469,
"text": "Picked"
},
{
"code": null,
"e": 27487,
"s": 27476,
"text": "SQL-Server"
},
{
"code": null,
"e": 27497,
"s": 27487,
"text": "Blogathon"
},
{
"code": null,
"e": 27502,
"s": 27497,
"text": "DBMS"
},
{
"code": null,
"e": 27506,
"s": 27502,
"text": "SQL"
},
{
"code": null,
"e": 27511,
"s": 27506,
"text": "DBMS"
},
{
"code": null,
"e": 27515,
"s": 27511,
"text": "SQL"
},
{
"code": null,
"e": 27613,
"s": 27515,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27670,
"s": 27613,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27711,
"s": 27670,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27741,
"s": 27711,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 27776,
"s": 27741,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27820,
"s": 27776,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 27838,
"s": 27820,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 27885,
"s": 27838,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 27909,
"s": 27885,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 27950,
"s": 27909,
"text": "SQL query to find second highest salary?"
}
] |
PyQt5 QLabel - Adding blur effect - GeeksforGeeks | 10 May, 2020
In this article we will see how we can add blur effect to the label, blur means smoothing of the label, by default there is no blur effect to the label although we can add blur effect any time. Below is the representation of label with blur effect.
In order to do this we have to do the following –
1. Create a label2. Create QGraphicsBlurEffect object3. Add this object to the label with the help of setGraphicsEffect method
Syntax :
# creating a blur effect
self.blur_effect = QGraphicsBlurEffect()
# adding blur effect to the label
label.setGraphicsEffect(self.blur_effect)
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel("Label", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # creating a blur effect self.blur_effect = QGraphicsBlurEffect() # adding blur effect to the label label.setGraphicsEffect(self.blur_effect) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-Label
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26215,
"s": 26187,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26464,
"s": 26215,
"text": "In this article we will see how we can add blur effect to the label, blur means smoothing of the label, by default there is no blur effect to the label although we can add blur effect any time. Below is the representation of label with blur effect."
},
{
"code": null,
"e": 26514,
"s": 26464,
"text": "In order to do this we have to do the following –"
},
{
"code": null,
"e": 26641,
"s": 26514,
"text": "1. Create a label2. Create QGraphicsBlurEffect object3. Add this object to the label with the help of setGraphicsEffect method"
},
{
"code": null,
"e": 26650,
"s": 26641,
"text": "Syntax :"
},
{
"code": null,
"e": 26794,
"s": 26650,
"text": "# creating a blur effect\nself.blur_effect = QGraphicsBlurEffect()\n\n# adding blur effect to the label\nlabel.setGraphicsEffect(self.blur_effect)\n"
},
{
"code": null,
"e": 26822,
"s": 26794,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel(\"Label\", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # creating a blur effect self.blur_effect = QGraphicsBlurEffect() # adding blur effect to the label label.setGraphicsEffect(self.blur_effect) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27956,
"s": 26822,
"text": null
},
{
"code": null,
"e": 27965,
"s": 27956,
"text": "Output :"
},
{
"code": null,
"e": 27984,
"s": 27965,
"text": "Python PyQt5-Label"
},
{
"code": null,
"e": 27995,
"s": 27984,
"text": "Python-gui"
},
{
"code": null,
"e": 28007,
"s": 27995,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28014,
"s": 28007,
"text": "Python"
},
{
"code": null,
"e": 28112,
"s": 28014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28130,
"s": 28112,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28165,
"s": 28130,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28197,
"s": 28165,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28219,
"s": 28197,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28261,
"s": 28219,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28291,
"s": 28261,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28317,
"s": 28291,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28346,
"s": 28317,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28390,
"s": 28346,
"text": "Reading and Writing to text files in Python"
}
] |
What is StrictMode in React ? - GeeksforGeeks | 30 Jun, 2021
StrictMode is a React Developer Tool primarily used for highlighting possible problems in a web application. It activates additional deprecation checks and warnings for its child components. One of the reasons for its popularity is the fact that it provides visual feedback (warning/error messages) whenever the React guidelines and recommended practices are not followed. Just like the React Fragment, the React StrictMode Component does not render any visible UI.
The React StrictMode can be viewed as a helper component that allows developers to code efficiently and brings to their attention any suspicious code which might have been accidentally added to the application. The StrictMode can be applied to any section of the application, not necessarily to the entire application. It is especially helpful to use while developing new codes or debugging the application.
Example:
Javascript
import React from 'react'; function StictModeDemo() { return ( <div> <Component1 /> <React.StrictMode> <React.Fragment> <Component2 /> <Component3 /> </React.Fragment> </React.StrictMode> <Component4 /> </div> );}
Explanation: In the above example, the StrictMode checks will be applicable only on Component2 and Component3 (as they the child components of React.StrictMode). Contrary to this, Component1 and Component4 will not have any checks.
Advantages: The React StrictMode helps to identify and detect various warnings/errors during the development phase, namely-
Helps to identify those components having unsafe lifecycles: Some of the legacy component lifecycle methods are considered to be unsafe to use in async applications. The React StrictMode helps to detect the use of such unsafe methods. Once enabled, it displays a list of all components using unsafe lifecycle methods as warning messages.Warns about the usage of the legacy string ref API: Initially, there were two methods to manage refs- legacy string ref API and the callback API. Later, a third alternate method, the createRef API was added, replacing the string refs with object refs, which allowed the StrictMode to give warning messages whenever string refs are used.Warns about the usage of the deprecated findDOMNode: Since the findDOMNode is only a one-time read API, it is not possible to handle changes when a child component attempts to render a different node (other than the one rendered by the parent component). These issues were detected by the React StrictMode and displayed as warning messages.
Helps to identify those components having unsafe lifecycles: Some of the legacy component lifecycle methods are considered to be unsafe to use in async applications. The React StrictMode helps to detect the use of such unsafe methods. Once enabled, it displays a list of all components using unsafe lifecycle methods as warning messages.
Warns about the usage of the legacy string ref API: Initially, there were two methods to manage refs- legacy string ref API and the callback API. Later, a third alternate method, the createRef API was added, replacing the string refs with object refs, which allowed the StrictMode to give warning messages whenever string refs are used.
Warns about the usage of the deprecated findDOMNode: Since the findDOMNode is only a one-time read API, it is not possible to handle changes when a child component attempts to render a different node (other than the one rendered by the parent component). These issues were detected by the React StrictMode and displayed as warning messages.
Additional Important Points to Remember:
Since the StrictMode is a developer tool, it runs only in development mode. It does not affect the production build in any way whatsoever.
In order to identify and detect any problems within the application and show warning messages, StrictMode renders every component inside the application twice.
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26538,
"s": 26071,
"text": "StrictMode is a React Developer Tool primarily used for highlighting possible problems in a web application. It activates additional deprecation checks and warnings for its child components. One of the reasons for its popularity is the fact that it provides visual feedback (warning/error messages) whenever the React guidelines and recommended practices are not followed. Just like the React Fragment, the React StrictMode Component does not render any visible UI. "
},
{
"code": null,
"e": 26946,
"s": 26538,
"text": "The React StrictMode can be viewed as a helper component that allows developers to code efficiently and brings to their attention any suspicious code which might have been accidentally added to the application. The StrictMode can be applied to any section of the application, not necessarily to the entire application. It is especially helpful to use while developing new codes or debugging the application."
},
{
"code": null,
"e": 26955,
"s": 26946,
"text": "Example:"
},
{
"code": null,
"e": 26966,
"s": 26955,
"text": "Javascript"
},
{
"code": "import React from 'react'; function StictModeDemo() { return ( <div> <Component1 /> <React.StrictMode> <React.Fragment> <Component2 /> <Component3 /> </React.Fragment> </React.StrictMode> <Component4 /> </div> );}",
"e": 27241,
"s": 26966,
"text": null
},
{
"code": null,
"e": 27473,
"s": 27241,
"text": "Explanation: In the above example, the StrictMode checks will be applicable only on Component2 and Component3 (as they the child components of React.StrictMode). Contrary to this, Component1 and Component4 will not have any checks."
},
{
"code": null,
"e": 27597,
"s": 27473,
"text": "Advantages: The React StrictMode helps to identify and detect various warnings/errors during the development phase, namely-"
},
{
"code": null,
"e": 28611,
"s": 27597,
"text": "Helps to identify those components having unsafe lifecycles: Some of the legacy component lifecycle methods are considered to be unsafe to use in async applications. The React StrictMode helps to detect the use of such unsafe methods. Once enabled, it displays a list of all components using unsafe lifecycle methods as warning messages.Warns about the usage of the legacy string ref API: Initially, there were two methods to manage refs- legacy string ref API and the callback API. Later, a third alternate method, the createRef API was added, replacing the string refs with object refs, which allowed the StrictMode to give warning messages whenever string refs are used.Warns about the usage of the deprecated findDOMNode: Since the findDOMNode is only a one-time read API, it is not possible to handle changes when a child component attempts to render a different node (other than the one rendered by the parent component). These issues were detected by the React StrictMode and displayed as warning messages."
},
{
"code": null,
"e": 28949,
"s": 28611,
"text": "Helps to identify those components having unsafe lifecycles: Some of the legacy component lifecycle methods are considered to be unsafe to use in async applications. The React StrictMode helps to detect the use of such unsafe methods. Once enabled, it displays a list of all components using unsafe lifecycle methods as warning messages."
},
{
"code": null,
"e": 29286,
"s": 28949,
"text": "Warns about the usage of the legacy string ref API: Initially, there were two methods to manage refs- legacy string ref API and the callback API. Later, a third alternate method, the createRef API was added, replacing the string refs with object refs, which allowed the StrictMode to give warning messages whenever string refs are used."
},
{
"code": null,
"e": 29627,
"s": 29286,
"text": "Warns about the usage of the deprecated findDOMNode: Since the findDOMNode is only a one-time read API, it is not possible to handle changes when a child component attempts to render a different node (other than the one rendered by the parent component). These issues were detected by the React StrictMode and displayed as warning messages."
},
{
"code": null,
"e": 29668,
"s": 29627,
"text": "Additional Important Points to Remember:"
},
{
"code": null,
"e": 29807,
"s": 29668,
"text": "Since the StrictMode is a developer tool, it runs only in development mode. It does not affect the production build in any way whatsoever."
},
{
"code": null,
"e": 29967,
"s": 29807,
"text": "In order to identify and detect any problems within the application and show warning messages, StrictMode renders every component inside the application twice."
},
{
"code": null,
"e": 29974,
"s": 29967,
"text": "Picked"
},
{
"code": null,
"e": 29990,
"s": 29974,
"text": "React-Questions"
},
{
"code": null,
"e": 29998,
"s": 29990,
"text": "ReactJS"
},
{
"code": null,
"e": 30015,
"s": 29998,
"text": "Web Technologies"
},
{
"code": null,
"e": 30113,
"s": 30015,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30140,
"s": 30113,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 30182,
"s": 30140,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 30220,
"s": 30182,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 30255,
"s": 30220,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 30313,
"s": 30255,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 30353,
"s": 30313,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30386,
"s": 30353,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30431,
"s": 30386,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30481,
"s": 30431,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Censor bad words in Python using better-profanity - GeeksforGeeks | 24 Jan, 2021
In this article, we will learn how to Censor bad words using Python. For this, we are using the better_profanity module from python.
Installation
pip install better_profanity
For censoring bad words, we are using profanity.censor() method from better_profanity. So, we discuss first its syntax and arguments.
Syntax: profanity.censor(text, censor_char=’*’)
Parameters:
text : text to be censor
censor_char : ‘*’ by default, character to censor bad words
Return value: censored text
Approach:
Import package (profanity)Declare or input the text to be censored.Use profanity.censor() method and get the censored text.Print censored text.
Import package (profanity)
Declare or input the text to be censored.
Use profanity.censor() method and get the censored text.
Print censored text.
Example 1:
# importing packagefrom better_profanity import profanity # text to be censoredtext = "What the shit are you doing?" # do censoringcensored = profanity.censor(text) # view outputprint(censored)
Output:
What the **** are you doing?
Example 2:
# importing packagefrom better_profanity import profanity # text to be censoredtext = "What the shit are you doing?" # do censoringcensored = profanity.censor(text, '$') # view outputprint(censored)
Output:
What the $$$$ are you doing?
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 25688,
"s": 25555,
"text": "In this article, we will learn how to Censor bad words using Python. For this, we are using the better_profanity module from python."
},
{
"code": null,
"e": 25701,
"s": 25688,
"text": "Installation"
},
{
"code": null,
"e": 25730,
"s": 25701,
"text": "pip install better_profanity"
},
{
"code": null,
"e": 25864,
"s": 25730,
"text": "For censoring bad words, we are using profanity.censor() method from better_profanity. So, we discuss first its syntax and arguments."
},
{
"code": null,
"e": 25912,
"s": 25864,
"text": "Syntax: profanity.censor(text, censor_char=’*’)"
},
{
"code": null,
"e": 25924,
"s": 25912,
"text": "Parameters:"
},
{
"code": null,
"e": 25949,
"s": 25924,
"text": "text : text to be censor"
},
{
"code": null,
"e": 26009,
"s": 25949,
"text": "censor_char : ‘*’ by default, character to censor bad words"
},
{
"code": null,
"e": 26037,
"s": 26009,
"text": "Return value: censored text"
},
{
"code": null,
"e": 26047,
"s": 26037,
"text": "Approach:"
},
{
"code": null,
"e": 26191,
"s": 26047,
"text": "Import package (profanity)Declare or input the text to be censored.Use profanity.censor() method and get the censored text.Print censored text."
},
{
"code": null,
"e": 26218,
"s": 26191,
"text": "Import package (profanity)"
},
{
"code": null,
"e": 26260,
"s": 26218,
"text": "Declare or input the text to be censored."
},
{
"code": null,
"e": 26317,
"s": 26260,
"text": "Use profanity.censor() method and get the censored text."
},
{
"code": null,
"e": 26338,
"s": 26317,
"text": "Print censored text."
},
{
"code": null,
"e": 26349,
"s": 26338,
"text": "Example 1:"
},
{
"code": "# importing packagefrom better_profanity import profanity # text to be censoredtext = \"What the shit are you doing?\" # do censoringcensored = profanity.censor(text) # view outputprint(censored)",
"e": 26546,
"s": 26349,
"text": null
},
{
"code": null,
"e": 26554,
"s": 26546,
"text": "Output:"
},
{
"code": null,
"e": 26583,
"s": 26554,
"text": "What the **** are you doing?"
},
{
"code": null,
"e": 26594,
"s": 26583,
"text": "Example 2:"
},
{
"code": "# importing packagefrom better_profanity import profanity # text to be censoredtext = \"What the shit are you doing?\" # do censoringcensored = profanity.censor(text, '$') # view outputprint(censored)",
"e": 26796,
"s": 26594,
"text": null
},
{
"code": null,
"e": 26804,
"s": 26796,
"text": "Output:"
},
{
"code": null,
"e": 26833,
"s": 26804,
"text": "What the $$$$ are you doing?"
},
{
"code": null,
"e": 26848,
"s": 26833,
"text": "python-modules"
},
{
"code": null,
"e": 26855,
"s": 26848,
"text": "Python"
},
{
"code": null,
"e": 26953,
"s": 26855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26985,
"s": 26953,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27027,
"s": 26985,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27069,
"s": 27027,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27125,
"s": 27069,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27152,
"s": 27125,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27183,
"s": 27152,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27222,
"s": 27183,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27251,
"s": 27222,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27273,
"s": 27251,
"text": "Defaultdict in Python"
}
] |
PHP Database connection - GeeksforGeeks | 02 Nov, 2020
The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development.
Requirements: XAMPP web server procedure:
Start XAMPP server by starting Apache and MySQL.
Write PHP script for connecting to XAMPP.
Run it in the local browser.
Database is successfully created which is based on the PHP code.
In PHP, we can connect to the database using XAMPP web server by using the following path.
"localhost/phpmyadmin"
Steps in Detail:
Open XAMPP and start running Apache, MySQL and FileZilla
Now open your PHP file and write your PHP code to create database and a table in your database.PHP code to create a database:PHPPHP<?php // Server name must be localhost$servername = "localhost"; // In my case, user name will be root$username = "root"; // Password is empty$password = ""; // Creating a connection$conn = new mysqli($servername, $username, $password); // Check connectionif ($conn->connect_error) { die("Connection failure: " . $conn->connect_error);} // Creating a database named geekdata$sql = "CREATE DATABASE geekdata";if ($conn->query($sql) === TRUE) { echo "Database with name geekdata";} else { echo "Error: " . $conn->error;} // Closing connection$conn->close();?>
PHP code to create a database:
PHP
<?php // Server name must be localhost$servername = "localhost"; // In my case, user name will be root$username = "root"; // Password is empty$password = ""; // Creating a connection$conn = new mysqli($servername, $username, $password); // Check connectionif ($conn->connect_error) { die("Connection failure: " . $conn->connect_error);} // Creating a database named geekdata$sql = "CREATE DATABASE geekdata";if ($conn->query($sql) === TRUE) { echo "Database with name geekdata";} else { echo "Error: " . $conn->error;} // Closing connection$conn->close();?>
Save the file as “data.php” in htdocs folder under XAMPP folder.
Then open your web browser and type localhost/data.php
Finally the database is created and connected to PHP.
If you want to see your database, just type localhost/phpmyadmin in the web browser and the database can be found.
PHP-Misc
Technical Scripter 2020
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP | [
{
"code": null,
"e": 26201,
"s": 26173,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 26392,
"s": 26201,
"text": "The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development."
},
{
"code": null,
"e": 26434,
"s": 26392,
"text": "Requirements: XAMPP web server procedure:"
},
{
"code": null,
"e": 26483,
"s": 26434,
"text": "Start XAMPP server by starting Apache and MySQL."
},
{
"code": null,
"e": 26525,
"s": 26483,
"text": "Write PHP script for connecting to XAMPP."
},
{
"code": null,
"e": 26554,
"s": 26525,
"text": "Run it in the local browser."
},
{
"code": null,
"e": 26619,
"s": 26554,
"text": "Database is successfully created which is based on the PHP code."
},
{
"code": null,
"e": 26710,
"s": 26619,
"text": "In PHP, we can connect to the database using XAMPP web server by using the following path."
},
{
"code": null,
"e": 26733,
"s": 26710,
"text": "\"localhost/phpmyadmin\""
},
{
"code": null,
"e": 26750,
"s": 26733,
"text": "Steps in Detail:"
},
{
"code": null,
"e": 26807,
"s": 26750,
"text": "Open XAMPP and start running Apache, MySQL and FileZilla"
},
{
"code": null,
"e": 27533,
"s": 26807,
"text": "Now open your PHP file and write your PHP code to create database and a table in your database.PHP code to create a database:PHPPHP<?php // Server name must be localhost$servername = \"localhost\"; // In my case, user name will be root$username = \"root\"; // Password is empty$password = \"\"; // Creating a connection$conn = new mysqli($servername, $username, $password); // Check connectionif ($conn->connect_error) { die(\"Connection failure: \" . $conn->connect_error);} // Creating a database named geekdata$sql = \"CREATE DATABASE geekdata\";if ($conn->query($sql) === TRUE) { echo \"Database with name geekdata\";} else { echo \"Error: \" . $conn->error;} // Closing connection$conn->close();?>"
},
{
"code": null,
"e": 27564,
"s": 27533,
"text": "PHP code to create a database:"
},
{
"code": null,
"e": 27568,
"s": 27564,
"text": "PHP"
},
{
"code": "<?php // Server name must be localhost$servername = \"localhost\"; // In my case, user name will be root$username = \"root\"; // Password is empty$password = \"\"; // Creating a connection$conn = new mysqli($servername, $username, $password); // Check connectionif ($conn->connect_error) { die(\"Connection failure: \" . $conn->connect_error);} // Creating a database named geekdata$sql = \"CREATE DATABASE geekdata\";if ($conn->query($sql) === TRUE) { echo \"Database with name geekdata\";} else { echo \"Error: \" . $conn->error;} // Closing connection$conn->close();?>",
"e": 28163,
"s": 27568,
"text": null
},
{
"code": null,
"e": 28228,
"s": 28163,
"text": "Save the file as “data.php” in htdocs folder under XAMPP folder."
},
{
"code": null,
"e": 28283,
"s": 28228,
"text": "Then open your web browser and type localhost/data.php"
},
{
"code": null,
"e": 28337,
"s": 28283,
"text": "Finally the database is created and connected to PHP."
},
{
"code": null,
"e": 28452,
"s": 28337,
"text": "If you want to see your database, just type localhost/phpmyadmin in the web browser and the database can be found."
},
{
"code": null,
"e": 28461,
"s": 28452,
"text": "PHP-Misc"
},
{
"code": null,
"e": 28485,
"s": 28461,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28489,
"s": 28485,
"text": "PHP"
},
{
"code": null,
"e": 28502,
"s": 28489,
"text": "PHP Programs"
},
{
"code": null,
"e": 28521,
"s": 28502,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28538,
"s": 28521,
"text": "Web Technologies"
},
{
"code": null,
"e": 28542,
"s": 28538,
"text": "PHP"
},
{
"code": null,
"e": 28640,
"s": 28542,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28690,
"s": 28640,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28730,
"s": 28690,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28780,
"s": 28730,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 28825,
"s": 28780,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 28852,
"s": 28825,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 28902,
"s": 28852,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28942,
"s": 28902,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28994,
"s": 28942,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 29044,
"s": 28994,
"text": "How to check whether an array is empty using PHP?"
}
] |
Randomized Block Design with R Programming - GeeksforGeeks | 22 Oct, 2020
Experimental Designs are part of ANOVA in statistics. They are predefined algorithms that help us in analyzing the differences among group means in an experimental unit. Randomized Block Design (RBD) or Randomized Complete Block Design is one part of the Anova types.
Randomized Block Design:
The three basic principles of designing an experiment are replication, blocking, and randomization. In this type of design, blocking is not a part of the algorithm. The samples of the experiment are random with replications are assigned to specific blocks for each experimental unit. Let’s consider some experiments below and implement the experiment in R programming.
Testing new fertilizers in different types of crops. Crops are divided into 3 different types(blocks). These blocks are again divided into 3 fertilizers that are used on those crops. The figure for this is as follows:
In the above image:
F1 – Fertilizer 1, F2 – Fertilizer 2 , NF – No Fertilizer
The crops are divided into 3 blocks(rice, wheat, and corn). Then they are again divided into fertilizer types. The results of the different blocks will be analyzed. Let’s see the above in the R language.
Note: In R agricolae package can also be used for implementing RCBD. But here we are using a different approach.
Let’s build the dataframe:
R
corn <- factor(rep(c("corn", "rice", "wheat"), each = 3))fert <- factor(rep(c("f1", "f2", "nf"), times = 3))corn
Output:
[1] corn corn corn rice rice rice wheat wheat wheat
Levels: corn rice wheat
R
y <- c(6, 5, 6, 4, 4.2, 5, 5, 4.4, 5.5) # y is the months the crops were healthyresults <- data.frame(y, corn, fert) fit <- aov(y ~ fert+corn, data = results) summary(fit)
Output:
Df Sum Sq Mean Sq F value Pr(>F)
fert 2 1.4022 0.7011 6.505 0.0553 .
corn 2 2.4156 1.2078 11.206 0.0229 *
Residuals 4 0.4311 0.1078
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Explanation:
The value of Mean Sq shows is blocking really necessary for the experiment. Here Mean Sq 0.1078<<0.7011 thus blocking is necessary will give precise values for the experiment. Though this method is a little debatable yet useful. The significance value of every experiment is given by the person taking the experiment. Here lets consider significance has 5% i.e 0.05. The Pr(>F) value is 0.553>0.05. Thus the hypothesis is accepted for the crops experiment. Let’s consider one more experiment.
Comparing the performances of students (male and female) blocks in different environments (at home and at college). To represent this experiment in the figure will be as follows:
Note: It generally is safe to consider an equal number of blocks and treatments for better results.
In the above image:
AC – At College, AH: At Home
Students are divided into blocks as male and female. Then each block is divided into 2 different environments (home and college). Let’s see this in code:
R
stud <- factor(rep(c("male", "female"), each = 2))perf <- factor(rep(c("ah", "ac" ), times = 2))perf
Output:
[1] ah ac ah ac
Levels: ac ah
R
y <- c(5.5, 5, 4, 6.2) # y is the hours students # studied in specific placesresults <- data.frame(y, stud, perf) fit <- aov(y ~ perf+stud, data = results) summary(fit)
Output:
Df Sum Sq Mean Sq F value Pr(>F)
perf 1 0.7225 0.7225 0.396 0.642
stud 1 0.0225 0.0225 0.012 0.930
Residuals 1 1.8225 1.8225
Explanation:
The value of Mean Sq is 0.7225<<1.8225,i.e, here blocking wasn’t necessary. And as Pr value is 0.642 > 0.05 (5% significance) and the hypothesis is accepted.
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 26755,
"s": 26487,
"text": "Experimental Designs are part of ANOVA in statistics. They are predefined algorithms that help us in analyzing the differences among group means in an experimental unit. Randomized Block Design (RBD) or Randomized Complete Block Design is one part of the Anova types."
},
{
"code": null,
"e": 26780,
"s": 26755,
"text": "Randomized Block Design:"
},
{
"code": null,
"e": 27149,
"s": 26780,
"text": "The three basic principles of designing an experiment are replication, blocking, and randomization. In this type of design, blocking is not a part of the algorithm. The samples of the experiment are random with replications are assigned to specific blocks for each experimental unit. Let’s consider some experiments below and implement the experiment in R programming."
},
{
"code": null,
"e": 27367,
"s": 27149,
"text": "Testing new fertilizers in different types of crops. Crops are divided into 3 different types(blocks). These blocks are again divided into 3 fertilizers that are used on those crops. The figure for this is as follows:"
},
{
"code": null,
"e": 27387,
"s": 27367,
"text": "In the above image:"
},
{
"code": null,
"e": 27447,
"s": 27387,
"text": "F1 – Fertilizer 1, F2 – Fertilizer 2 , NF – No Fertilizer "
},
{
"code": null,
"e": 27651,
"s": 27447,
"text": "The crops are divided into 3 blocks(rice, wheat, and corn). Then they are again divided into fertilizer types. The results of the different blocks will be analyzed. Let’s see the above in the R language."
},
{
"code": null,
"e": 27764,
"s": 27651,
"text": "Note: In R agricolae package can also be used for implementing RCBD. But here we are using a different approach."
},
{
"code": null,
"e": 27791,
"s": 27764,
"text": "Let’s build the dataframe:"
},
{
"code": null,
"e": 27793,
"s": 27791,
"text": "R"
},
{
"code": "corn <- factor(rep(c(\"corn\", \"rice\", \"wheat\"), each = 3))fert <- factor(rep(c(\"f1\", \"f2\", \"nf\"), times = 3))corn",
"e": 27906,
"s": 27793,
"text": null
},
{
"code": null,
"e": 27914,
"s": 27906,
"text": "Output:"
},
{
"code": null,
"e": 27998,
"s": 27914,
"text": "[1] corn corn corn rice rice rice wheat wheat wheat\nLevels: corn rice wheat\n\n"
},
{
"code": null,
"e": 28000,
"s": 27998,
"text": "R"
},
{
"code": "y <- c(6, 5, 6, 4, 4.2, 5, 5, 4.4, 5.5) # y is the months the crops were healthyresults <- data.frame(y, corn, fert) fit <- aov(y ~ fert+corn, data = results) summary(fit)",
"e": 28204,
"s": 28000,
"text": null
},
{
"code": null,
"e": 28212,
"s": 28204,
"text": "Output:"
},
{
"code": null,
"e": 28470,
"s": 28212,
"text": " Df Sum Sq Mean Sq F value Pr(>F) \nfert 2 1.4022 0.7011 6.505 0.0553 .\ncorn 2 2.4156 1.2078 11.206 0.0229 *\nResiduals 4 0.4311 0.1078 \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\n"
},
{
"code": null,
"e": 28483,
"s": 28470,
"text": "Explanation:"
},
{
"code": null,
"e": 28976,
"s": 28483,
"text": "The value of Mean Sq shows is blocking really necessary for the experiment. Here Mean Sq 0.1078<<0.7011 thus blocking is necessary will give precise values for the experiment. Though this method is a little debatable yet useful. The significance value of every experiment is given by the person taking the experiment. Here lets consider significance has 5% i.e 0.05. The Pr(>F) value is 0.553>0.05. Thus the hypothesis is accepted for the crops experiment. Let’s consider one more experiment."
},
{
"code": null,
"e": 29155,
"s": 28976,
"text": "Comparing the performances of students (male and female) blocks in different environments (at home and at college). To represent this experiment in the figure will be as follows:"
},
{
"code": null,
"e": 29255,
"s": 29155,
"text": "Note: It generally is safe to consider an equal number of blocks and treatments for better results."
},
{
"code": null,
"e": 29275,
"s": 29255,
"text": "In the above image:"
},
{
"code": null,
"e": 29304,
"s": 29275,
"text": "AC – At College, AH: At Home"
},
{
"code": null,
"e": 29458,
"s": 29304,
"text": "Students are divided into blocks as male and female. Then each block is divided into 2 different environments (home and college). Let’s see this in code:"
},
{
"code": null,
"e": 29460,
"s": 29458,
"text": "R"
},
{
"code": "stud <- factor(rep(c(\"male\", \"female\"), each = 2))perf <- factor(rep(c(\"ah\", \"ac\" ), times = 2))perf",
"e": 29561,
"s": 29460,
"text": null
},
{
"code": null,
"e": 29569,
"s": 29561,
"text": "Output:"
},
{
"code": null,
"e": 29601,
"s": 29569,
"text": "[1] ah ac ah ac\nLevels: ac ah\n\n"
},
{
"code": null,
"e": 29603,
"s": 29601,
"text": "R"
},
{
"code": "y <- c(5.5, 5, 4, 6.2) # y is the hours students # studied in specific placesresults <- data.frame(y, stud, perf) fit <- aov(y ~ perf+stud, data = results) summary(fit)",
"e": 29797,
"s": 29603,
"text": null
},
{
"code": null,
"e": 29805,
"s": 29797,
"text": "Output:"
},
{
"code": null,
"e": 29961,
"s": 29805,
"text": "Df Sum Sq Mean Sq F value Pr(>F)\nperf 1 0.7225 0.7225 0.396 0.642\nstud 1 0.0225 0.0225 0.012 0.930\nResiduals 1 1.8225 1.8225 \n\n"
},
{
"code": null,
"e": 29974,
"s": 29961,
"text": "Explanation:"
},
{
"code": null,
"e": 30133,
"s": 29974,
"text": "The value of Mean Sq is 0.7225<<1.8225,i.e, here blocking wasn’t necessary. And as Pr value is 0.642 > 0.05 (5% significance) and the hypothesis is accepted."
},
{
"code": null,
"e": 30146,
"s": 30133,
"text": "R-Statistics"
},
{
"code": null,
"e": 30157,
"s": 30146,
"text": "R Language"
},
{
"code": null,
"e": 30255,
"s": 30157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30307,
"s": 30255,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30342,
"s": 30307,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30380,
"s": 30342,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30438,
"s": 30380,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30481,
"s": 30438,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30518,
"s": 30481,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30567,
"s": 30518,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30593,
"s": 30567,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 30610,
"s": 30593,
"text": "R - if statement"
}
] |
What is Chaining in Node.js ? - GeeksforGeeks | 21 Jul, 2020
Chaining in Node.js can be achieved using the async npm module. In order to install the async module, we need to run the following script in our directory:
npm init
npm i async
There are two most commonly used methods for chaining functions provided by the async module:
parallel(tasks, callback): The tasks is a collection of functions that runs parallel in practice through I/O switching. If any function in the collection tasks returns an error, the callback function is fired. Once all the functions are completed, the data is passed to the callback function as an array. The callback function is optional.
series(tasks, callback): Each function in tasks run only after the previous function is completed. If any of the functions throw an error, the subsequent functions are not executed and the callback is fired with an error value. On completion of tasks, the data is passed into the callback function as an array.
Example 1: Parallel ChainingFilename: index.js
const async = require('async'); async.parallel([ (callback) => { setTimeout(() => { console.log('This is the first function'); callback(null, 1); }, 500); }, (callback) => { console.log('This is the second function'); callback(null, 2); }], (err, results) => { if (err) console.error(err); console.log(results);});
Run index.js file using the following command:
node index.js
Output:
This is the second function
This is the first function
[ 1, 2 ]
Explanation: It is noted that the two functions were executed asynchronously. Hence the output from the second function was received before the first function finished executing due to the setTimeout() method. However, the data is only passed to the callback once both the functions finish execution.
Example 2: Series ChainingFilename: index.js
const async = require('async'); async.series([ (callback) => { setTimeout(() => { console.log('This is the first function'); callback(null, 1); }, 500); }, (callback) => { console.log('This is the second function'); callback(null, 2); }], (err, results) => { if (err) console.error(err); console.log(results);});
Run index.js file using the following command:
node index.js
Output:
This is the first function
This is the second function
[ 1, 2 ]
Explanation: Unlike the parallel execution, in this case, the second function wasn’t executed until the first function completed its own execution. Similar to the parallel method, the results are only passed to the callback function once all the functions in the tasks collection finish execution.
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
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
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25713,
"s": 25685,
"text": "\n21 Jul, 2020"
},
{
"code": null,
"e": 25869,
"s": 25713,
"text": "Chaining in Node.js can be achieved using the async npm module. In order to install the async module, we need to run the following script in our directory:"
},
{
"code": null,
"e": 25890,
"s": 25869,
"text": "npm init\nnpm i async"
},
{
"code": null,
"e": 25984,
"s": 25890,
"text": "There are two most commonly used methods for chaining functions provided by the async module:"
},
{
"code": null,
"e": 26324,
"s": 25984,
"text": "parallel(tasks, callback): The tasks is a collection of functions that runs parallel in practice through I/O switching. If any function in the collection tasks returns an error, the callback function is fired. Once all the functions are completed, the data is passed to the callback function as an array. The callback function is optional."
},
{
"code": null,
"e": 26635,
"s": 26324,
"text": "series(tasks, callback): Each function in tasks run only after the previous function is completed. If any of the functions throw an error, the subsequent functions are not executed and the callback is fired with an error value. On completion of tasks, the data is passed into the callback function as an array."
},
{
"code": null,
"e": 26682,
"s": 26635,
"text": "Example 1: Parallel ChainingFilename: index.js"
},
{
"code": "const async = require('async'); async.parallel([ (callback) => { setTimeout(() => { console.log('This is the first function'); callback(null, 1); }, 500); }, (callback) => { console.log('This is the second function'); callback(null, 2); }], (err, results) => { if (err) console.error(err); console.log(results);});",
"e": 27066,
"s": 26682,
"text": null
},
{
"code": null,
"e": 27113,
"s": 27066,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 27127,
"s": 27113,
"text": "node index.js"
},
{
"code": null,
"e": 27135,
"s": 27127,
"text": "Output:"
},
{
"code": null,
"e": 27200,
"s": 27135,
"text": "This is the second function\nThis is the first function\n[ 1, 2 ]\n"
},
{
"code": null,
"e": 27501,
"s": 27200,
"text": "Explanation: It is noted that the two functions were executed asynchronously. Hence the output from the second function was received before the first function finished executing due to the setTimeout() method. However, the data is only passed to the callback once both the functions finish execution."
},
{
"code": null,
"e": 27546,
"s": 27501,
"text": "Example 2: Series ChainingFilename: index.js"
},
{
"code": "const async = require('async'); async.series([ (callback) => { setTimeout(() => { console.log('This is the first function'); callback(null, 1); }, 500); }, (callback) => { console.log('This is the second function'); callback(null, 2); }], (err, results) => { if (err) console.error(err); console.log(results);});",
"e": 27928,
"s": 27546,
"text": null
},
{
"code": null,
"e": 27975,
"s": 27928,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 27989,
"s": 27975,
"text": "node index.js"
},
{
"code": null,
"e": 27997,
"s": 27989,
"text": "Output:"
},
{
"code": null,
"e": 28062,
"s": 27997,
"text": "This is the first function\nThis is the second function\n[ 1, 2 ]\n"
},
{
"code": null,
"e": 28360,
"s": 28062,
"text": "Explanation: Unlike the parallel execution, in this case, the second function wasn’t executed until the first function completed its own execution. Similar to the parallel method, the results are only passed to the callback function once all the functions in the tasks collection finish execution."
},
{
"code": null,
"e": 28373,
"s": 28360,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 28380,
"s": 28373,
"text": "Picked"
},
{
"code": null,
"e": 28388,
"s": 28380,
"text": "Node.js"
},
{
"code": null,
"e": 28405,
"s": 28388,
"text": "Web Technologies"
},
{
"code": null,
"e": 28503,
"s": 28405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28533,
"s": 28503,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 28562,
"s": 28533,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 28619,
"s": 28562,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28673,
"s": 28619,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28710,
"s": 28673,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28750,
"s": 28710,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28795,
"s": 28750,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28838,
"s": 28795,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28899,
"s": 28838,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
CSS | visibility Property - GeeksforGeeks | 09 Aug, 2019
This property is used to specify whether an element is visible or not in a web document but the hidden elements take up space in the web document. Use the display property to remove or display property to both hide and delete an element from the browser.
Syntax:
visibility: visible|hidden|collapse|initial|inherit;
Property values:
visible: It is the default value. The element is show or visible normally in the web document.Syntax:visibility:hidden;Example:<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: visible; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:visible;</h2> <p class="geeks"> A computer science portal for geeks </p> </body></html> Output:
Syntax:
visibility:hidden;
Example:
<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: visible; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:visible;</h2> <p class="geeks"> A computer science portal for geeks </p> </body></html>
Output:
hidden: This property hide the element from the page but takes up space in the document.Syntax:visibility:hidden;Example:<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: hidden; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:hidden;</h2> <p class="geeks"> A computer science portal for geeks </p> </body></html> Output:
Syntax:
visibility:hidden;
Example:
<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: hidden; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:hidden;</h2> <p class="geeks"> A computer science portal for geeks </p> </body></html>
Output:
collapse: This property only used for the table elements. It is used to remove the rows and column from the table but it does not affect the layout of the Table. But their space is available for other content.Note:This property is not used for other elements except table elements.Syntax:visibility:collapse;Example:<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> table.geeks { visibility: collapse } table, th, td { border:1px solid red; p { color:green; font-size:25px; } </style> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h2>visibility:collapse;</h2> <p>geeksforgeeks</p> <table style="border:1px solid red;" class="geeks"> <tr> <th>geeks</th> <th>for</th> <th>geeks</th> </tr> </table> <p>A computer science portal for geeks</p> </center> </body></html> Output:
Syntax:
visibility:collapse;
Example:
<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> table.geeks { visibility: collapse } table, th, td { border:1px solid red; p { color:green; font-size:25px; } </style> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h2>visibility:collapse;</h2> <p>geeksforgeeks</p> <table style="border:1px solid red;" class="geeks"> <tr> <th>geeks</th> <th>for</th> <th>geeks</th> </tr> </table> <p>A computer science portal for geeks</p> </center> </body></html>
Output:
Supported browsers: The browsers supported by visibility Property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubham_singh
CSS-Properties
Technical Scripter 2018
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 24905,
"s": 24877,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 25160,
"s": 24905,
"text": "This property is used to specify whether an element is visible or not in a web document but the hidden elements take up space in the web document. Use the display property to remove or display property to both hide and delete an element from the browser."
},
{
"code": null,
"e": 25168,
"s": 25160,
"text": "Syntax:"
},
{
"code": null,
"e": 25221,
"s": 25168,
"text": "visibility: visible|hidden|collapse|initial|inherit;"
},
{
"code": null,
"e": 25238,
"s": 25221,
"text": "Property values:"
},
{
"code": null,
"e": 25912,
"s": 25238,
"text": "visible: It is the default value. The element is show or visible normally in the web document.Syntax:visibility:hidden;Example:<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: visible; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:visible;</h2> <p class=\"geeks\"> A computer science portal for geeks </p> </body></html> Output:"
},
{
"code": null,
"e": 25920,
"s": 25912,
"text": "Syntax:"
},
{
"code": null,
"e": 25939,
"s": 25920,
"text": "visibility:hidden;"
},
{
"code": null,
"e": 25948,
"s": 25939,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: visible; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:visible;</h2> <p class=\"geeks\"> A computer science portal for geeks </p> </body></html> ",
"e": 26488,
"s": 25948,
"text": null
},
{
"code": null,
"e": 26496,
"s": 26488,
"text": "Output:"
},
{
"code": null,
"e": 27150,
"s": 26496,
"text": "hidden: This property hide the element from the page but takes up space in the document.Syntax:visibility:hidden;Example:<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: hidden; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:hidden;</h2> <p class=\"geeks\"> A computer science portal for geeks </p> </body></html> Output:"
},
{
"code": null,
"e": 27158,
"s": 27150,
"text": "Syntax:"
},
{
"code": null,
"e": 27177,
"s": 27158,
"text": "visibility:hidden;"
},
{
"code": null,
"e": 27186,
"s": 27177,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> h1 { color:green; } .geeks { visibility: hidden; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>visibility:hidden;</h2> <p class=\"geeks\"> A computer science portal for geeks </p> </body></html> ",
"e": 27712,
"s": 27186,
"text": null
},
{
"code": null,
"e": 27720,
"s": 27712,
"text": "Output:"
},
{
"code": null,
"e": 28841,
"s": 27720,
"text": "collapse: This property only used for the table elements. It is used to remove the rows and column from the table but it does not affect the layout of the Table. But their space is available for other content.Note:This property is not used for other elements except table elements.Syntax:visibility:collapse;Example:<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> table.geeks { visibility: collapse } table, th, td { border:1px solid red; p { color:green; font-size:25px; } </style> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h2>visibility:collapse;</h2> <p>geeksforgeeks</p> <table style=\"border:1px solid red;\" class=\"geeks\"> <tr> <th>geeks</th> <th>for</th> <th>geeks</th> </tr> </table> <p>A computer science portal for geeks</p> </center> </body></html> Output:"
},
{
"code": null,
"e": 28849,
"s": 28841,
"text": "Syntax:"
},
{
"code": null,
"e": 28870,
"s": 28849,
"text": "visibility:collapse;"
},
{
"code": null,
"e": 28879,
"s": 28870,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS | visibility Property </title> <style> table.geeks { visibility: collapse } table, th, td { border:1px solid red; p { color:green; font-size:25px; } </style> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h2>visibility:collapse;</h2> <p>geeksforgeeks</p> <table style=\"border:1px solid red;\" class=\"geeks\"> <tr> <th>geeks</th> <th>for</th> <th>geeks</th> </tr> </table> <p>A computer science portal for geeks</p> </center> </body></html> ",
"e": 29677,
"s": 28879,
"text": null
},
{
"code": null,
"e": 29685,
"s": 29677,
"text": "Output:"
},
{
"code": null,
"e": 29769,
"s": 29685,
"text": "Supported browsers: The browsers supported by visibility Property are listed below:"
},
{
"code": null,
"e": 29783,
"s": 29769,
"text": "Google Chrome"
},
{
"code": null,
"e": 29801,
"s": 29783,
"text": "Internet Explorer"
},
{
"code": null,
"e": 29809,
"s": 29801,
"text": "Firefox"
},
{
"code": null,
"e": 29815,
"s": 29809,
"text": "Opera"
},
{
"code": null,
"e": 29822,
"s": 29815,
"text": "Safari"
},
{
"code": null,
"e": 29959,
"s": 29822,
"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": 29973,
"s": 29959,
"text": "shubham_singh"
},
{
"code": null,
"e": 29988,
"s": 29973,
"text": "CSS-Properties"
},
{
"code": null,
"e": 30012,
"s": 29988,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30016,
"s": 30012,
"text": "CSS"
},
{
"code": null,
"e": 30021,
"s": 30016,
"text": "HTML"
},
{
"code": null,
"e": 30038,
"s": 30021,
"text": "Web Technologies"
},
{
"code": null,
"e": 30043,
"s": 30038,
"text": "HTML"
},
{
"code": null,
"e": 30141,
"s": 30043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30191,
"s": 30141,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30253,
"s": 30191,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30301,
"s": 30253,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30359,
"s": 30301,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30414,
"s": 30359,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30464,
"s": 30414,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30526,
"s": 30464,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30574,
"s": 30526,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30634,
"s": 30574,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Java.io.StreamTokenizer Class in Java | Set 1 - GeeksforGeeks | 09 Jan, 2017
Java.io.StreamTokenizer class parses input stream into “tokens”.It allows to read one token at a time. Stream Tokenizer can recognize numbers, quoted strings, and various comment styles.Declaration :
public class StreamTokenizer
extends Object
Constructor :StreamTokenizer(Reader arg) : Creates a tokenizer that parses the given character stream.
Methods :
commentChar : java.io.StreamTokenizer.commentChar(int arg) ignores all characters from the single-line comment character to the end of the line by this StreamTokenizer.Syntax :public void commentChar(int arg)
Parameters :
arg : the character after which all characters are ignored in the line.
Return :
No value is returned.Implementation :// Java Program illustrating use of commentChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of commentChar() method token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Programmers123GeeksHelloa Program is explained here my friends.Output:Word : Progr
Number : 1.0
Number : 2.0
Number : 3.0
Word : Geeks
Word : Hello
public void commentChar(int arg)
Parameters :
arg : the character after which all characters are ignored in the line.
Return :
No value is returned.
Implementation :
// Java Program illustrating use of commentChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of commentChar() method token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}
Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :
Programmers123GeeksHelloa Program is explained here my friends.
Output:
Word : Progr
Number : 1.0
Number : 2.0
Number : 3.0
Word : Geeks
Word : Hello
lineno() : java.io.StreamTokenizer.lineno() returns the current line number of this StreamTokenizer.Syntax :public int lineno()
Parameters :
arg : the character after which all characters are ignored in the line.
Return :
returns the current line number of this StreamTokenizer.Implementation :// Java Program illustrating use of lineno() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); token.eolIsSignificant(true); // Use of lineno() method // to get current line no. System.out.println("Line Number:" + token.lineno()); token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println(""); System.out.println("Line No. : " + token.lineno()); break; case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}Output:Line Number:1
Word : Progr
Line No. : 2
Number : 1.0
Line No. : 3
Number : 2.0
Line No. : 4
Number : 3.0
Line No. : 5
Word : Geeks
Line No. : 6
Word : Hello
Line No. : 7
Word : This
Word : is
public int lineno()
Parameters :
arg : the character after which all characters are ignored in the line.
Return :
returns the current line number of this StreamTokenizer.
Implementation :
// Java Program illustrating use of lineno() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); token.eolIsSignificant(true); // Use of lineno() method // to get current line no. System.out.println("Line Number:" + token.lineno()); token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println(""); System.out.println("Line No. : " + token.lineno()); break; case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}
Output:
Line Number:1
Word : Progr
Line No. : 2
Number : 1.0
Line No. : 3
Number : 2.0
Line No. : 4
Number : 3.0
Line No. : 5
Word : Geeks
Line No. : 6
Word : Hello
Line No. : 7
Word : This
Word : is
toString() : java.io.StreamTokenizer.toString() represents current Stream token as a string along with it’s line no.Syntax :public String toString()
Return :
represents current Stream token as a string along with it's line no.Implementation :// Java Program illustrating use of toString() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: // Value of ttype field returned by nextToken() System.out.println("Number : " + token.nval); break; // Value of ttype field returned by nextToken() case StreamTokenizer.TT_WORD: // Use of toStringn() method System.out.println("Word : " + token.toString()); break; } } }}Output:Word : Token[Programmers], line 1
Number : 1.0
Number : 2.0
Number : 3.0
Word : Token[Geeks], line 5
Word : Token[Hello], line 6
Word : Token[a], line 7
Word : Token[Program], line 7
Word : Token[is], line 7
Word : Token[explained], line 7
Word : Token[here], line 7
Word : Token[my], line 7
Word : Token[friends.], line 7
public String toString()
Return :
represents current Stream token as a string along with it's line no.
Implementation :
// Java Program illustrating use of toString() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: // Value of ttype field returned by nextToken() System.out.println("Number : " + token.nval); break; // Value of ttype field returned by nextToken() case StreamTokenizer.TT_WORD: // Use of toStringn() method System.out.println("Word : " + token.toString()); break; } } }}
Output:
Word : Token[Programmers], line 1
Number : 1.0
Number : 2.0
Number : 3.0
Word : Token[Geeks], line 5
Word : Token[Hello], line 6
Word : Token[a], line 7
Word : Token[Program], line 7
Word : Token[is], line 7
Word : Token[explained], line 7
Word : Token[here], line 7
Word : Token[my], line 7
Word : Token[friends.], line 7
eolIsSignificant() : java.io.StreamTokenizer.eolIsSignificant(boolean arg) tells whether to treat end of line as a token or not. If ‘arg’ is true, then it End Of Line is treated as a token. If true, then the method returns TT_EOL and set the ttype field when End Of Line is reached.If ‘arg’ is false then the End Of Line is treated simply as a white space.Syntax :public void eolIsSignificant(boolean arg)
Parameters :
arg : boolean which tells whether to take EOL as a token or white space
Return :
No value is returned.Implementation :// Java Program illustrating use of eolIsSignificant() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); boolean arg = true; // Use of eolIsSignificant() method token.eolIsSignificant(arg); // Here the 'arg' is set true, so EOL is treated as a token int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println("End of Line encountered."); break; case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :1Geeks2For3GeeksOutput :Number : 1.0
End of Line encountered.
Word : Geeks
End of Line encountered.
Number : 2.0
End of Line encountered.
Word : For
End of Line encountered.
Number : 3.0
End of Line encountered.
Word : Geeks
public void eolIsSignificant(boolean arg)
Parameters :
arg : boolean which tells whether to take EOL as a token or white space
Return :
No value is returned.
Implementation :
// Java Program illustrating use of eolIsSignificant() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); boolean arg = true; // Use of eolIsSignificant() method token.eolIsSignificant(arg); // Here the 'arg' is set true, so EOL is treated as a token int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println("End of Line encountered."); break; case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}
Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :
1Geeks2For3Geeks
Output :
Number : 1.0
End of Line encountered.
Word : Geeks
End of Line encountered.
Number : 2.0
End of Line encountered.
Word : For
End of Line encountered.
Number : 3.0
End of Line encountered.
Word : Geeks
nextToken() : java.io.StreamTokenizer.nextToken() parses the next token from the Input Stream and returns it’s value to the ttype field along with the additional fields like ‘sval’, ‘nval’.Syntax :public int nextToken()
Parameters :
------
Return :
value to the ttype fieldImplementation :// Java Program illustrating use of nextToken() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of nextToken() method to parse Next Token from the Input Stream int t = token.nextToken(); while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :1This program tells2about use of3next token() methodOutput :Word : This
Word : program
Word : tells
Number : 2.0
Word : about
Word : use
Word : of
Number : 3.0
Word : next
Word : token
Word : method
public int nextToken()
Parameters :
------
Return :
value to the ttype field
Implementation :
// Java Program illustrating use of nextToken() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of nextToken() method to parse Next Token from the Input Stream int t = token.nextToken(); while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}
Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :
1This program tells2about use of3next token() method
Output :
Word : This
Word : program
Word : tells
Number : 2.0
Word : about
Word : use
Word : of
Number : 3.0
Word : next
Word : token
Word : method
lowerCaseMode() : java.io.StreamTokenizer.lowerCaseMode(boolean arg) tells whether to lowercase the word tokens automatically or not. If the flag – ‘arg’ is set true, then the value of ‘sval’ field is lowered.Syntax :public void lowerCaseMode(boolean arg)
Parameters :
arg : indicates whether to lowercase the word tokens automatically or not
Return :
voidImplementation :// Java Program illustrating use of lowerCaseMode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); /* Use of lowerCaseMode() method to Here, the we have set the Lower Case Mode ON */ boolean arg = true; token.lowerCaseMode(arg); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Hello GeeksThis Is AboutLowerCaseMode()Output :Word : hello
Word : geeks
Word : this
Word : is
Word : about
Word : lowercasemode
public void lowerCaseMode(boolean arg)
Parameters :
arg : indicates whether to lowercase the word tokens automatically or not
Return :
void
Implementation :
// Java Program illustrating use of lowerCaseMode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); /* Use of lowerCaseMode() method to Here, the we have set the Lower Case Mode ON */ boolean arg = true; token.lowerCaseMode(arg); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}
Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :
Hello GeeksThis Is AboutLowerCaseMode()
Output :
Word : hello
Word : geeks
Word : this
Word : is
Word : about
Word : lowercasemode
ordinaryChar() : java.io.StreamTokenizer.ordinaryChar(int arg) sets ‘arg’ character as an ordinary character. It will remove the arg character, if it has any significance as word, number, white space or comment Character.Syntax :public void ordinaryChar(int arg)
Parameters :
arg : the character which is to be set as an Ordinary Character
Return :
voidImplementation :// Java Program illustrating use of ordinaryChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChar() method // Here we have taken 's' as an ordinary character token.ordinaryChar('s'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Hello GeeksThissss Issszz AboutordinaryChar()This method has remove ‘s’ from the entire StreamOutput :Word : Hello
Word : Geek
Word : Thi
Word : I
Word : zz
Word : About
Word : ordinaryChar
public void ordinaryChar(int arg)
Parameters :
arg : the character which is to be set as an Ordinary Character
Return :
void
Implementation :
// Java Program illustrating use of ordinaryChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChar() method // Here we have taken 's' as an ordinary character token.ordinaryChar('s'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}
Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :
Hello GeeksThissss Issszz AboutordinaryChar()
This method has remove ‘s’ from the entire Stream
Output :
Word : Hello
Word : Geek
Word : Thi
Word : I
Word : zz
Word : About
Word : ordinaryChar
ordinaryChars() : java.io.StreamTokenizer.ordinaryChars(int low, int high) sets character in the range – ‘a to b’ to Ordinary character in the StreamTokenizerSyntax :public void ordinaryChars(int low, int high)
Parameters :
low : lower limit of range
high : higher limit of range
Return :
voidImplementation :// Java Program illustrating use of ordinaryChars() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChars() method // Here we have taken low = 'a' and high = 'c' token.ordinaryChars('a','c'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Hello GeeksThisisaboutordinaryChars()Output :Word : Hello
Word : Geeks
Word : This
Word : is
Word : out
Word : ordin
Word : ryCh
Word : rsNext Article – Java.io.StreamTokenizer Class in Java | Set 2 This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
public void ordinaryChars(int low, int high)
Parameters :
low : lower limit of range
high : higher limit of range
Return :
void
Implementation :
// Java Program illustrating use of ordinaryChars() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader("ABC.txt"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChars() method // Here we have taken low = 'a' and high = 'c' token.ordinaryChars('a','c'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println("Number : " + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word : " + token.sval); break; } } }}
Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :
Hello GeeksThisisaboutordinaryChars()
Output :
Word : Hello
Word : Geeks
Word : This
Word : is
Word : out
Word : ordin
Word : ryCh
Word : rs
Next Article – Java.io.StreamTokenizer Class in Java | Set 2 This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25801,
"s": 25773,
"text": "\n09 Jan, 2017"
},
{
"code": null,
"e": 26001,
"s": 25801,
"text": "Java.io.StreamTokenizer class parses input stream into “tokens”.It allows to read one token at a time. Stream Tokenizer can recognize numbers, quoted strings, and various comment styles.Declaration :"
},
{
"code": null,
"e": 26047,
"s": 26001,
"text": "public class StreamTokenizer\n extends Object"
},
{
"code": null,
"e": 26150,
"s": 26047,
"text": "Constructor :StreamTokenizer(Reader arg) : Creates a tokenizer that parses the given character stream."
},
{
"code": null,
"e": 26160,
"s": 26150,
"text": "Methods :"
},
{
"code": null,
"e": 27747,
"s": 26160,
"text": "commentChar : java.io.StreamTokenizer.commentChar(int arg) ignores all characters from the single-line comment character to the end of the line by this StreamTokenizer.Syntax :public void commentChar(int arg) \nParameters : \narg : the character after which all characters are ignored in the line.\nReturn :\nNo value is returned.Implementation :// Java Program illustrating use of commentChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of commentChar() method token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Programmers123GeeksHelloa Program is explained here my friends.Output:Word : Progr\nNumber : 1.0\nNumber : 2.0\nNumber : 3.0\nWord : Geeks\nWord : Hello\n"
},
{
"code": null,
"e": 27898,
"s": 27747,
"text": "public void commentChar(int arg) \nParameters : \narg : the character after which all characters are ignored in the line.\nReturn :\nNo value is returned."
},
{
"code": null,
"e": 27915,
"s": 27898,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of commentChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of commentChar() method token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}",
"e": 28821,
"s": 27915,
"text": null
},
{
"code": null,
"e": 29013,
"s": 28821,
"text": "Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :"
},
{
"code": null,
"e": 29077,
"s": 29013,
"text": "Programmers123GeeksHelloa Program is explained here my friends."
},
{
"code": null,
"e": 29085,
"s": 29077,
"text": "Output:"
},
{
"code": null,
"e": 29164,
"s": 29085,
"text": "Word : Progr\nNumber : 1.0\nNumber : 2.0\nNumber : 3.0\nWord : Geeks\nWord : Hello\n"
},
{
"code": null,
"e": 30879,
"s": 29164,
"text": "lineno() : java.io.StreamTokenizer.lineno() returns the current line number of this StreamTokenizer.Syntax :public int lineno()\nParameters : \narg : the character after which all characters are ignored in the line.\nReturn :\nreturns the current line number of this StreamTokenizer.Implementation :// Java Program illustrating use of lineno() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); token.eolIsSignificant(true); // Use of lineno() method // to get current line no. System.out.println(\"Line Number:\" + token.lineno()); token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println(\"\"); System.out.println(\"Line No. : \" + token.lineno()); break; case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}Output:Line Number:1\nWord : Progr\n\nLine No. : 2\nNumber : 1.0\n\nLine No. : 3\nNumber : 2.0\n\nLine No. : 4\nNumber : 3.0\n\nLine No. : 5\nWord : Geeks\n\nLine No. : 6\nWord : Hello\n\nLine No. : 7\nWord : This\nWord : is\n"
},
{
"code": null,
"e": 31051,
"s": 30879,
"text": "public int lineno()\nParameters : \narg : the character after which all characters are ignored in the line.\nReturn :\nreturns the current line number of this StreamTokenizer."
},
{
"code": null,
"e": 31068,
"s": 31051,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of lineno() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); token.eolIsSignificant(true); // Use of lineno() method // to get current line no. System.out.println(\"Line Number:\" + token.lineno()); token.commentChar('a'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println(\"\"); System.out.println(\"Line No. : \" + token.lineno()); break; case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}",
"e": 32283,
"s": 31068,
"text": null
},
{
"code": null,
"e": 32291,
"s": 32283,
"text": "Output:"
},
{
"code": null,
"e": 32490,
"s": 32291,
"text": "Line Number:1\nWord : Progr\n\nLine No. : 2\nNumber : 1.0\n\nLine No. : 3\nNumber : 2.0\n\nLine No. : 4\nNumber : 3.0\n\nLine No. : 5\nWord : Geeks\n\nLine No. : 6\nWord : Hello\n\nLine No. : 7\nWord : This\nWord : is\n"
},
{
"code": null,
"e": 34102,
"s": 32490,
"text": "toString() : java.io.StreamTokenizer.toString() represents current Stream token as a string along with it’s line no.Syntax :public String toString()\nReturn :\nrepresents current Stream token as a string along with it's line no.Implementation :// Java Program illustrating use of toString() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: // Value of ttype field returned by nextToken() System.out.println(\"Number : \" + token.nval); break; // Value of ttype field returned by nextToken() case StreamTokenizer.TT_WORD: // Use of toStringn() method System.out.println(\"Word : \" + token.toString()); break; } } }}Output:Word : Token[Programmers], line 1\nNumber : 1.0\nNumber : 2.0\nNumber : 3.0\nWord : Token[Geeks], line 5\nWord : Token[Hello], line 6\nWord : Token[a], line 7\nWord : Token[Program], line 7\nWord : Token[is], line 7\nWord : Token[explained], line 7\nWord : Token[here], line 7\nWord : Token[my], line 7\nWord : Token[friends.], line 7\n"
},
{
"code": null,
"e": 34205,
"s": 34102,
"text": "public String toString()\nReturn :\nrepresents current Stream token as a string along with it's line no."
},
{
"code": null,
"e": 34222,
"s": 34205,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of toString() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: // Value of ttype field returned by nextToken() System.out.println(\"Number : \" + token.nval); break; // Value of ttype field returned by nextToken() case StreamTokenizer.TT_WORD: // Use of toStringn() method System.out.println(\"Word : \" + token.toString()); break; } } }}",
"e": 35262,
"s": 34222,
"text": null
},
{
"code": null,
"e": 35270,
"s": 35262,
"text": "Output:"
},
{
"code": null,
"e": 35594,
"s": 35270,
"text": "Word : Token[Programmers], line 1\nNumber : 1.0\nNumber : 2.0\nNumber : 3.0\nWord : Token[Geeks], line 5\nWord : Token[Hello], line 6\nWord : Token[a], line 7\nWord : Token[Program], line 7\nWord : Token[is], line 7\nWord : Token[explained], line 7\nWord : Token[here], line 7\nWord : Token[my], line 7\nWord : Token[friends.], line 7\n"
},
{
"code": null,
"e": 37648,
"s": 35594,
"text": "eolIsSignificant() : java.io.StreamTokenizer.eolIsSignificant(boolean arg) tells whether to treat end of line as a token or not. If ‘arg’ is true, then it End Of Line is treated as a token. If true, then the method returns TT_EOL and set the ttype field when End Of Line is reached.If ‘arg’ is false then the End Of Line is treated simply as a white space.Syntax :public void eolIsSignificant(boolean arg)\nParameters :\narg : boolean which tells whether to take EOL as a token or white space\nReturn :\nNo value is returned.Implementation :// Java Program illustrating use of eolIsSignificant() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); boolean arg = true; // Use of eolIsSignificant() method token.eolIsSignificant(arg); // Here the 'arg' is set true, so EOL is treated as a token int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println(\"End of Line encountered.\"); break; case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :1Geeks2For3GeeksOutput :Number : 1.0\nEnd of Line encountered.\nWord : Geeks\nEnd of Line encountered.\nNumber : 2.0\nEnd of Line encountered.\nWord : For\nEnd of Line encountered.\nNumber : 3.0\nEnd of Line encountered.\nWord : Geeks"
},
{
"code": null,
"e": 37806,
"s": 37648,
"text": "public void eolIsSignificant(boolean arg)\nParameters :\narg : boolean which tells whether to take EOL as a token or white space\nReturn :\nNo value is returned."
},
{
"code": null,
"e": 37823,
"s": 37806,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of eolIsSignificant() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); boolean arg = true; // Use of eolIsSignificant() method token.eolIsSignificant(arg); // Here the 'arg' is set true, so EOL is treated as a token int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_EOL: System.out.println(\"End of Line encountered.\"); break; case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}",
"e": 38925,
"s": 37823,
"text": null
},
{
"code": null,
"e": 39117,
"s": 38925,
"text": "Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :"
},
{
"code": null,
"e": 39134,
"s": 39117,
"text": "1Geeks2For3Geeks"
},
{
"code": null,
"e": 39143,
"s": 39134,
"text": "Output :"
},
{
"code": null,
"e": 39344,
"s": 39143,
"text": "Number : 1.0\nEnd of Line encountered.\nWord : Geeks\nEnd of Line encountered.\nNumber : 2.0\nEnd of Line encountered.\nWord : For\nEnd of Line encountered.\nNumber : 3.0\nEnd of Line encountered.\nWord : Geeks"
},
{
"code": null,
"e": 40915,
"s": 39344,
"text": "nextToken() : java.io.StreamTokenizer.nextToken() parses the next token from the Input Stream and returns it’s value to the ttype field along with the additional fields like ‘sval’, ‘nval’.Syntax :public int nextToken()\nParameters :\n------\nReturn :\nvalue to the ttype fieldImplementation :// Java Program illustrating use of nextToken() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of nextToken() method to parse Next Token from the Input Stream int t = token.nextToken(); while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :1This program tells2about use of3next token() methodOutput :Word : This\nWord : program\nWord : tells\nNumber : 2.0\nWord : about\nWord : use\nWord : of\nNumber : 3.0\nWord : next\nWord : token\nWord : method"
},
{
"code": null,
"e": 40992,
"s": 40915,
"text": "public int nextToken()\nParameters :\n------\nReturn :\nvalue to the ttype field"
},
{
"code": null,
"e": 41009,
"s": 40992,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of nextToken() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of nextToken() method to parse Next Token from the Input Stream int t = token.nextToken(); while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}",
"e": 41902,
"s": 41009,
"text": null
},
{
"code": null,
"e": 42094,
"s": 41902,
"text": "Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :"
},
{
"code": null,
"e": 42147,
"s": 42094,
"text": "1This program tells2about use of3next token() method"
},
{
"code": null,
"e": 42156,
"s": 42147,
"text": "Output :"
},
{
"code": null,
"e": 42295,
"s": 42156,
"text": "Word : This\nWord : program\nWord : tells\nNumber : 2.0\nWord : about\nWord : use\nWord : of\nNumber : 3.0\nWord : next\nWord : token\nWord : method"
},
{
"code": null,
"e": 43955,
"s": 42295,
"text": "lowerCaseMode() : java.io.StreamTokenizer.lowerCaseMode(boolean arg) tells whether to lowercase the word tokens automatically or not. If the flag – ‘arg’ is set true, then the value of ‘sval’ field is lowered.Syntax :public void lowerCaseMode(boolean arg)\nParameters :\narg : indicates whether to lowercase the word tokens automatically or not\nReturn :\nvoidImplementation :// Java Program illustrating use of lowerCaseMode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); /* Use of lowerCaseMode() method to Here, the we have set the Lower Case Mode ON */ boolean arg = true; token.lowerCaseMode(arg); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Hello GeeksThis Is AboutLowerCaseMode()Output :Word : hello\nWord : geeks\nWord : this\nWord : is\nWord : about\nWord : lowercasemode"
},
{
"code": null,
"e": 44095,
"s": 43955,
"text": "public void lowerCaseMode(boolean arg)\nParameters :\narg : indicates whether to lowercase the word tokens automatically or not\nReturn :\nvoid"
},
{
"code": null,
"e": 44112,
"s": 44095,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of lowerCaseMode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); /* Use of lowerCaseMode() method to Here, the we have set the Lower Case Mode ON */ boolean arg = true; token.lowerCaseMode(arg); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}",
"e": 45081,
"s": 44112,
"text": null
},
{
"code": null,
"e": 45273,
"s": 45081,
"text": "Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :"
},
{
"code": null,
"e": 45313,
"s": 45273,
"text": "Hello GeeksThis Is AboutLowerCaseMode()"
},
{
"code": null,
"e": 45322,
"s": 45313,
"text": "Output :"
},
{
"code": null,
"e": 45404,
"s": 45322,
"text": "Word : hello\nWord : geeks\nWord : this\nWord : is\nWord : about\nWord : lowercasemode"
},
{
"code": null,
"e": 47084,
"s": 45404,
"text": "ordinaryChar() : java.io.StreamTokenizer.ordinaryChar(int arg) sets ‘arg’ character as an ordinary character. It will remove the arg character, if it has any significance as word, number, white space or comment Character.Syntax :public void ordinaryChar(int arg)\nParameters :\narg : the character which is to be set as an Ordinary Character\nReturn :\nvoidImplementation :// Java Program illustrating use of ordinaryChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChar() method // Here we have taken 's' as an ordinary character token.ordinaryChar('s'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Hello GeeksThissss Issszz AboutordinaryChar()This method has remove ‘s’ from the entire StreamOutput :Word : Hello\nWord : Geek\nWord : Thi\nWord : I\nWord : zz\nWord : About\nWord : ordinaryChar"
},
{
"code": null,
"e": 47209,
"s": 47084,
"text": "public void ordinaryChar(int arg)\nParameters :\narg : the character which is to be set as an Ordinary Character\nReturn :\nvoid"
},
{
"code": null,
"e": 47226,
"s": 47209,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of ordinaryChar() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChar() method // Here we have taken 's' as an ordinary character token.ordinaryChar('s'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}",
"e": 48157,
"s": 47226,
"text": null
},
{
"code": null,
"e": 48349,
"s": 48157,
"text": "Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :"
},
{
"code": null,
"e": 48395,
"s": 48349,
"text": "Hello GeeksThissss Issszz AboutordinaryChar()"
},
{
"code": null,
"e": 48445,
"s": 48395,
"text": "This method has remove ‘s’ from the entire Stream"
},
{
"code": null,
"e": 48454,
"s": 48445,
"text": "Output :"
},
{
"code": null,
"e": 48542,
"s": 48454,
"text": "Word : Hello\nWord : Geek\nWord : Thi\nWord : I\nWord : zz\nWord : About\nWord : ordinaryChar"
},
{
"code": null,
"e": 50634,
"s": 48542,
"text": "ordinaryChars() : java.io.StreamTokenizer.ordinaryChars(int low, int high) sets character in the range – ‘a to b’ to Ordinary character in the StreamTokenizerSyntax :public void ordinaryChars(int low, int high)\nParameters :\nlow : lower limit of range\nhigh : higher limit of range\nReturn :\nvoidImplementation :// Java Program illustrating use of ordinaryChars() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChars() method // Here we have taken low = 'a' and high = 'c' token.ordinaryChars('a','c'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :Hello GeeksThisisaboutordinaryChars()Output :Word : Hello\nWord : Geeks\nWord : This\nWord : is\nWord : out\nWord : ordin\nWord : ryCh\nWord : rsNext Article – Java.io.StreamTokenizer Class in Java | Set 2 This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 50762,
"s": 50634,
"text": "public void ordinaryChars(int low, int high)\nParameters :\nlow : lower limit of range\nhigh : higher limit of range\nReturn :\nvoid"
},
{
"code": null,
"e": 50779,
"s": 50762,
"text": "Implementation :"
},
{
"code": "// Java Program illustrating use of ordinaryChars() method import java.io.*;public class NewClass{ public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException { FileReader reader = new FileReader(\"ABC.txt\"); BufferedReader bufferread = new BufferedReader(reader); StreamTokenizer token = new StreamTokenizer(bufferread); // Use of ordinaryChars() method // Here we have taken low = 'a' and high = 'c' token.ordinaryChars('a','c'); int t; while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) { switch (t) { case StreamTokenizer.TT_NUMBER: System.out.println(\"Number : \" + token.nval); break; case StreamTokenizer.TT_WORD: System.out.println(\"Word : \" + token.sval); break; } } }}",
"e": 51714,
"s": 50779,
"text": null
},
{
"code": null,
"e": 51906,
"s": 51714,
"text": "Note :This program won’t run here as no ‘ABC’ file exists. You can check this code on Java compiler on your system.To check this code, create a file ‘ABC’ on your system.‘ABC’ file contains :"
},
{
"code": null,
"e": 51944,
"s": 51906,
"text": "Hello GeeksThisisaboutordinaryChars()"
},
{
"code": null,
"e": 51953,
"s": 51944,
"text": "Output :"
},
{
"code": null,
"e": 52047,
"s": 51953,
"text": "Word : Hello\nWord : Geeks\nWord : This\nWord : is\nWord : out\nWord : ordin\nWord : ryCh\nWord : rs"
},
{
"code": null,
"e": 52408,
"s": 52047,
"text": "Next Article – Java.io.StreamTokenizer Class in Java | Set 2 This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 52533,
"s": 52408,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 52542,
"s": 52533,
"text": "Java-I/O"
},
{
"code": null,
"e": 52547,
"s": 52542,
"text": "Java"
},
{
"code": null,
"e": 52552,
"s": 52547,
"text": "Java"
},
{
"code": null,
"e": 52650,
"s": 52552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52701,
"s": 52650,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 52731,
"s": 52701,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 52750,
"s": 52731,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 52765,
"s": 52750,
"text": "Stream In Java"
},
{
"code": null,
"e": 52796,
"s": 52765,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 52814,
"s": 52796,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 52846,
"s": 52814,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 52866,
"s": 52846,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 52898,
"s": 52866,
"text": "Multidimensional Arrays in Java"
}
] |
RAND() Function in SQL Server - GeeksforGeeks | 30 Dec, 2020
RAND() function :This function in SQL Server is used to return a random decimal value and this value lies in the range greater than and equal to zero (>=0) and less than 1. If we want to obtain a random integer R in the range i <= R < j, we have to use the expression “FLOOR(i + RAND() * (j − i))”.
Features :
This function is used to give a random decimal value.
The returned value lies in between 0 (inclusive) and 1 (exclusive).
If this function does not accept any parameter, it will returns a completely random number.
If this function takes a parameter, it will returns a repeatable sequence of random numbers.
This function accepts optional parameter.
This function uses a formula“FLOOR(i + RAND() * (j − i))” to get a random integer R,where R lies in the range of “i <= R < j”.
Syntax :
RAND(N)
Parameter :This method accepts a parameter as given below :
N : If N is specified, it returns a repeatable sequence of random numbers. If no N is specified, it returns a completely random number. It is optional and it works as a seed value.
Returns :It returns a random number between 0 (inclusive) and 1 (exclusive).
Example-1 :Getting a random value between 0 and 1.
SELECT RAND();
Output :
0.37892290119984562
Example-2 :Getting a random decimal number with seed value of 5.
SELECT RAND(5);
Output :
0.71366652509795636
Example-3 :Using RAND() function with variables and getting a random number between in the range of [ 2, 8 ) using RAND Function. Here, we will use the expression : FLOOR(i + RAND() * (j − i)) for generating the random number. Here, i is 2 and j is 8.
DECLARE @i INT;
DECLARE @j INT;
SET @i = 2;
SET @j = 8;
SELECT FLOOR(@i + RAND()*(@j-@i));
Output :
7.0
Example-4 :Getting a random value between in the range [ 3, 9 ] using RAND Function. Here, we will use the expression : FLOOR(i + RAND() * (j − i + 1)) for generating the random number. Here i is 3 and j is 9.
SELECT FLOOR(3 + RAND()*(9 - 3 + 1));
Output :
9.0
Application :This function is used to return a random number between 0 (inclusive) and 1 (exclusive).
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 25812,
"s": 25513,
"text": "RAND() function :This function in SQL Server is used to return a random decimal value and this value lies in the range greater than and equal to zero (>=0) and less than 1. If we want to obtain a random integer R in the range i <= R < j, we have to use the expression “FLOOR(i + RAND() * (j − i))”."
},
{
"code": null,
"e": 25823,
"s": 25812,
"text": "Features :"
},
{
"code": null,
"e": 25877,
"s": 25823,
"text": "This function is used to give a random decimal value."
},
{
"code": null,
"e": 25945,
"s": 25877,
"text": "The returned value lies in between 0 (inclusive) and 1 (exclusive)."
},
{
"code": null,
"e": 26037,
"s": 25945,
"text": "If this function does not accept any parameter, it will returns a completely random number."
},
{
"code": null,
"e": 26130,
"s": 26037,
"text": "If this function takes a parameter, it will returns a repeatable sequence of random numbers."
},
{
"code": null,
"e": 26172,
"s": 26130,
"text": "This function accepts optional parameter."
},
{
"code": null,
"e": 26299,
"s": 26172,
"text": "This function uses a formula“FLOOR(i + RAND() * (j − i))” to get a random integer R,where R lies in the range of “i <= R < j”."
},
{
"code": null,
"e": 26308,
"s": 26299,
"text": "Syntax :"
},
{
"code": null,
"e": 26316,
"s": 26308,
"text": "RAND(N)"
},
{
"code": null,
"e": 26376,
"s": 26316,
"text": "Parameter :This method accepts a parameter as given below :"
},
{
"code": null,
"e": 26557,
"s": 26376,
"text": "N : If N is specified, it returns a repeatable sequence of random numbers. If no N is specified, it returns a completely random number. It is optional and it works as a seed value."
},
{
"code": null,
"e": 26634,
"s": 26557,
"text": "Returns :It returns a random number between 0 (inclusive) and 1 (exclusive)."
},
{
"code": null,
"e": 26685,
"s": 26634,
"text": "Example-1 :Getting a random value between 0 and 1."
},
{
"code": null,
"e": 26700,
"s": 26685,
"text": "SELECT RAND();"
},
{
"code": null,
"e": 26709,
"s": 26700,
"text": "Output :"
},
{
"code": null,
"e": 26729,
"s": 26709,
"text": "0.37892290119984562"
},
{
"code": null,
"e": 26794,
"s": 26729,
"text": "Example-2 :Getting a random decimal number with seed value of 5."
},
{
"code": null,
"e": 26810,
"s": 26794,
"text": "SELECT RAND(5);"
},
{
"code": null,
"e": 26819,
"s": 26810,
"text": "Output :"
},
{
"code": null,
"e": 26839,
"s": 26819,
"text": "0.71366652509795636"
},
{
"code": null,
"e": 27091,
"s": 26839,
"text": "Example-3 :Using RAND() function with variables and getting a random number between in the range of [ 2, 8 ) using RAND Function. Here, we will use the expression : FLOOR(i + RAND() * (j − i)) for generating the random number. Here, i is 2 and j is 8."
},
{
"code": null,
"e": 27183,
"s": 27091,
"text": "DECLARE @i INT;\nDECLARE @j INT;\nSET @i = 2;\nSET @j = 8;\nSELECT FLOOR(@i + RAND()*(@j-@i));\n"
},
{
"code": null,
"e": 27192,
"s": 27183,
"text": "Output :"
},
{
"code": null,
"e": 27196,
"s": 27192,
"text": "7.0"
},
{
"code": null,
"e": 27406,
"s": 27196,
"text": "Example-4 :Getting a random value between in the range [ 3, 9 ] using RAND Function. Here, we will use the expression : FLOOR(i + RAND() * (j − i + 1)) for generating the random number. Here i is 3 and j is 9."
},
{
"code": null,
"e": 27445,
"s": 27406,
"text": "SELECT FLOOR(3 + RAND()*(9 - 3 + 1));\n"
},
{
"code": null,
"e": 27454,
"s": 27445,
"text": "Output :"
},
{
"code": null,
"e": 27458,
"s": 27454,
"text": "9.0"
},
{
"code": null,
"e": 27560,
"s": 27458,
"text": "Application :This function is used to return a random number between 0 (inclusive) and 1 (exclusive)."
},
{
"code": null,
"e": 27569,
"s": 27560,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27580,
"s": 27569,
"text": "SQL-Server"
},
{
"code": null,
"e": 27584,
"s": 27580,
"text": "SQL"
},
{
"code": null,
"e": 27588,
"s": 27584,
"text": "SQL"
},
{
"code": null,
"e": 27686,
"s": 27588,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27752,
"s": 27686,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27809,
"s": 27752,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27841,
"s": 27809,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27856,
"s": 27841,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27934,
"s": 27856,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27970,
"s": 27934,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27987,
"s": 27970,
"text": "SQL using Python"
},
{
"code": null,
"e": 28053,
"s": 27987,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28115,
"s": 28053,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Node.js response.setHeader() Method - GeeksforGeeks | 15 Sep, 2020
The response.setHeader(name, value) (Added in v0.4.0) method is an inbuilt application programming interface of the ‘http‘ module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, response.getHeader() may return non-string values. However, the non-string values will be converted to strings for network transmission.
When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.
In order to get a response and a proper result, we need to import ‘http’ module.
Syntax:
const http = require('http');
Syntax:
response.setHeader(name, value)
Parameters: This property accepts a single parameter as mentioned above and described below:
name <String>: It accepts the name of the header and it is case-insensitive.
value <any>: It can accept any values like objects, string, integer, Array, etc.
Return Value: It does not return any value, instead sets a header as described below.
The below example illustrates the use of response.setHeader() property in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // response.setHeaders() Method // Importing http modulevar http = require('http');// Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(request, response) { // Setting up Headers response.setHeader('Content-Type', 'text/html'); response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); // Checking and printing the headers console.log("When Header is set a string:", response.getHeader('Content-Type')); console.log("When Header is set an Array:", response.getHeader('Set-Cookie')); // Getting the set Headers const headers = response.getHeaders(); // Printing those headers console.log(headers); // Prints Output on the browser in response response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log("Server is running at port 3000...");});
Now run http://localhost:3000/ in the browser.
Output:
In Console
>> Server is running at port 3000...
>> When Header is set a string: text/html
>> When Header is set an Array: [‘type=ninja’, ‘language=javascript’]
>> [Object: null prototype] { ‘content-type’ : ‘text/html’, ‘set-cookie’ : [‘type=ninja’, ‘language=javascript’]}
Example 2: Filename: index.js
// Node.js program to demonstrate the // response.setHeaders() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(req, response) { // Setting up Headers response.setHeader('Alfa', 'Beta'); response.setHeader('Alfa1', ''); response.setHeader('Alfa2', 5); response.setHeader('Cookie-Setup', ['Alfa=Beta', 'Beta=Romeo']); // response.setHeader('', 'Beta'); // Throws Error // response.setHeader(); // Throws Error // Checking and printing the headers console.log("When Header is set an Array:", response.getHeader('Cookie-Setup')); console.log("When Header is set an 'Beta':", response.getHeader('Alfa')); console.log("When Header is set '':", response.getHeader('Alfa1')); console.log("When Header is set number 5:", response.getHeader('alfa2')); console.log("When Header is not set:", response.getHeader('Content-Type')); // Getting the set Headers const headers = response.getHeaders(); // Printing those headers console.log(headers); var Output = "Hello Geeksforgeeks..., " + "Available headers are:" + JSON.stringify(headers); // Prints Output on the browser in response response.write(Output); response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log("Server is running at port 3000...");});
Run index.js file using the following command:
node index.js
Output:
Output: In Console
Server is running at port 3000...
When Header is set an Array: [ ‘Alfa=Beta’, ‘Beta=Romeo’ ]
When Header is set an ‘Beta’: Beta
When Header is set ”:
When Header is set number 5: 5
When Header is not set: undefined
[Object: null prototype] {
alfa: ‘Beta’,
alfa1: ”,
alfa2: 5,
‘cookie-setup’: [ ‘Alfa=Beta’, ‘Beta=Romeo’ ]}
Now run http://localhost:3000/ in the browser.
Output: In Browser
Hello Geeksforgeeks..., Available headers are:{“alfa”:”Beta”, “alfa1′′:””, “alfa2”:5, “cookie-setup”:[“Alfa=Beta”, “Beta=Romeo”]}ok
If response.writeHead() method is called and this method has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead of response.writeHead().
Reference: https://nodejs.org/api/http.html#http_response_setheader_name_value
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Mongoose | findByIdAndUpdate() Function
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": 25767,
"s": 25739,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 26314,
"s": 25767,
"text": "The response.setHeader(name, value) (Added in v0.4.0) method is an inbuilt application programming interface of the ‘http‘ module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, response.getHeader() may return non-string values. However, the non-string values will be converted to strings for network transmission."
},
{
"code": null,
"e": 26503,
"s": 26314,
"text": "When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence."
},
{
"code": null,
"e": 26584,
"s": 26503,
"text": "In order to get a response and a proper result, we need to import ‘http’ module."
},
{
"code": null,
"e": 26592,
"s": 26584,
"text": "Syntax:"
},
{
"code": null,
"e": 26623,
"s": 26592,
"text": "const http = require('http');\n"
},
{
"code": null,
"e": 26631,
"s": 26623,
"text": "Syntax:"
},
{
"code": null,
"e": 26664,
"s": 26631,
"text": "response.setHeader(name, value)\n"
},
{
"code": null,
"e": 26757,
"s": 26664,
"text": "Parameters: This property accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 26834,
"s": 26757,
"text": "name <String>: It accepts the name of the header and it is case-insensitive."
},
{
"code": null,
"e": 26916,
"s": 26834,
"text": "value <any>: It can accept any values like objects, string, integer, Array, etc. "
},
{
"code": null,
"e": 27002,
"s": 26916,
"text": "Return Value: It does not return any value, instead sets a header as described below."
},
{
"code": null,
"e": 27085,
"s": 27002,
"text": "The below example illustrates the use of response.setHeader() property in Node.js."
},
{
"code": null,
"e": 27115,
"s": 27085,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // response.setHeaders() Method // Importing http modulevar http = require('http');// Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(request, response) { // Setting up Headers response.setHeader('Content-Type', 'text/html'); response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); // Checking and printing the headers console.log(\"When Header is set a string:\", response.getHeader('Content-Type')); console.log(\"When Header is set an Array:\", response.getHeader('Set-Cookie')); // Getting the set Headers const headers = response.getHeaders(); // Printing those headers console.log(headers); // Prints Output on the browser in response response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\");});",
"e": 28125,
"s": 27115,
"text": null
},
{
"code": null,
"e": 28172,
"s": 28125,
"text": "Now run http://localhost:3000/ in the browser."
},
{
"code": null,
"e": 28180,
"s": 28172,
"text": "Output:"
},
{
"code": null,
"e": 28191,
"s": 28180,
"text": "In Console"
},
{
"code": null,
"e": 28228,
"s": 28191,
"text": ">> Server is running at port 3000..."
},
{
"code": null,
"e": 28270,
"s": 28228,
"text": ">> When Header is set a string: text/html"
},
{
"code": null,
"e": 28340,
"s": 28270,
"text": ">> When Header is set an Array: [‘type=ninja’, ‘language=javascript’]"
},
{
"code": null,
"e": 28454,
"s": 28340,
"text": ">> [Object: null prototype] { ‘content-type’ : ‘text/html’, ‘set-cookie’ : [‘type=ninja’, ‘language=javascript’]}"
},
{
"code": null,
"e": 28484,
"s": 28454,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // response.setHeaders() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(req, response) { // Setting up Headers response.setHeader('Alfa', 'Beta'); response.setHeader('Alfa1', ''); response.setHeader('Alfa2', 5); response.setHeader('Cookie-Setup', ['Alfa=Beta', 'Beta=Romeo']); // response.setHeader('', 'Beta'); // Throws Error // response.setHeader(); // Throws Error // Checking and printing the headers console.log(\"When Header is set an Array:\", response.getHeader('Cookie-Setup')); console.log(\"When Header is set an 'Beta':\", response.getHeader('Alfa')); console.log(\"When Header is set '':\", response.getHeader('Alfa1')); console.log(\"When Header is set number 5:\", response.getHeader('alfa2')); console.log(\"When Header is not set:\", response.getHeader('Content-Type')); // Getting the set Headers const headers = response.getHeaders(); // Printing those headers console.log(headers); var Output = \"Hello Geeksforgeeks..., \" + \"Available headers are:\" + JSON.stringify(headers); // Prints Output on the browser in response response.write(Output); response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\");});",
"e": 29930,
"s": 28484,
"text": null
},
{
"code": null,
"e": 29977,
"s": 29930,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 29992,
"s": 29977,
"text": "node index.js\n"
},
{
"code": null,
"e": 30000,
"s": 29992,
"text": "Output:"
},
{
"code": null,
"e": 30019,
"s": 30000,
"text": "Output: In Console"
},
{
"code": null,
"e": 30053,
"s": 30019,
"text": "Server is running at port 3000..."
},
{
"code": null,
"e": 30112,
"s": 30053,
"text": "When Header is set an Array: [ ‘Alfa=Beta’, ‘Beta=Romeo’ ]"
},
{
"code": null,
"e": 30147,
"s": 30112,
"text": "When Header is set an ‘Beta’: Beta"
},
{
"code": null,
"e": 30169,
"s": 30147,
"text": "When Header is set ”:"
},
{
"code": null,
"e": 30200,
"s": 30169,
"text": "When Header is set number 5: 5"
},
{
"code": null,
"e": 30234,
"s": 30200,
"text": "When Header is not set: undefined"
},
{
"code": null,
"e": 30261,
"s": 30234,
"text": "[Object: null prototype] {"
},
{
"code": null,
"e": 30276,
"s": 30261,
"text": " alfa: ‘Beta’,"
},
{
"code": null,
"e": 30287,
"s": 30276,
"text": " alfa1: ”,"
},
{
"code": null,
"e": 30298,
"s": 30287,
"text": " alfa2: 5,"
},
{
"code": null,
"e": 30346,
"s": 30298,
"text": " ‘cookie-setup’: [ ‘Alfa=Beta’, ‘Beta=Romeo’ ]}"
},
{
"code": null,
"e": 30393,
"s": 30346,
"text": "Now run http://localhost:3000/ in the browser."
},
{
"code": null,
"e": 30412,
"s": 30393,
"text": "Output: In Browser"
},
{
"code": null,
"e": 30544,
"s": 30412,
"text": "Hello Geeksforgeeks..., Available headers are:{“alfa”:”Beta”, “alfa1′′:””, “alfa2”:5, “cookie-setup”:[“Alfa=Beta”, “Beta=Romeo”]}ok"
},
{
"code": null,
"e": 30960,
"s": 30544,
"text": "If response.writeHead() method is called and this method has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead of response.writeHead()."
},
{
"code": null,
"e": 31039,
"s": 30960,
"text": "Reference: https://nodejs.org/api/http.html#http_response_setheader_name_value"
},
{
"code": null,
"e": 31055,
"s": 31039,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 31063,
"s": 31055,
"text": "Node.js"
},
{
"code": null,
"e": 31080,
"s": 31063,
"text": "Web Technologies"
},
{
"code": null,
"e": 31178,
"s": 31080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31235,
"s": 31178,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 31289,
"s": 31235,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 31326,
"s": 31289,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 31359,
"s": 31326,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 31399,
"s": 31359,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 31439,
"s": 31399,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31484,
"s": 31439,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31527,
"s": 31484,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31577,
"s": 31527,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | set() method - GeeksforGeeks | 19 Feb, 2022
Set, a term in mathematics for a sequence consisting of distinct language is also extended in its language by Python and can easily be made using set().
set() method is used to convert any of the iterable to sequence of iterable elements with distinct elements, commonly called Set.
Syntax : set(iterable)Parameters : Any iterable sequence like list, tuple or dictionary.Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument.
Don’t worry if you get an unordered list from the set. Sets are unordered. Use sorted(set(sampleList)) to get it sorted
Code #1 : Demonstrating set() with list and tuple
Python3
# Python3 code to demonstrate the# working of set() on list and tuple # initializing listlis1 = [ 3, 4, 1, 4, 5 ] # initializing tupletup1 = (3, 4, 1, 4, 5) # Printing iterables before conversionprint("The list before conversion is : " + str(lis1))print("The tuple before conversion is : " + str(tup1)) # Iterables after conversion are# notice distinct and elementsprint("The list after conversion is : " + str(set(lis1)))print("The tuple after conversion is : " + str(set(tup1)))
Output:
The list before conversion is : [3, 4, 1, 4, 5]
The tuple before conversion is : (3, 4, 1, 4, 5)
The list after conversion is : {1, 3, 4, 5}
The tuple after conversion is : {1, 3, 4, 5}
No parameters are passed to create the empty set
Dictionary can also be created using set, but only keys remain after conversion, values are lost.
Code #2: Demonstration of working of set on dictionary
Python3
# Python3 code to demonstrate the# working of set() on dictionary # initializing listdic1 = { 4 : 'geeks', 1 : 'for', 3 : 'geeks' } # Printing dictionary before conversion# internally sortedprint("Dictionary before conversion is : " + str(dic1)) # Dictionary after conversion are# notice lost keysprint("Dictionary after conversion is : " + str(set(dic1)))
Dictionary before conversion is : {4: 'geeks', 1: 'for', 3: 'geeks'}
Dictionary after conversion is : {1, 3, 4}
Time Complexity: Set method is implemented as a hash table, so the time complexity is O(1).
yashthakkar1173
praveendhakad798
ruhelaa48
rajeev0719singh
anantmulchandani
Python-Built-in-functions
python-set
Python-set-functions
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25335,
"s": 25307,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 25488,
"s": 25335,
"text": "Set, a term in mathematics for a sequence consisting of distinct language is also extended in its language by Python and can easily be made using set()."
},
{
"code": null,
"e": 25619,
"s": 25488,
"text": "set() method is used to convert any of the iterable to sequence of iterable elements with distinct elements, commonly called Set. "
},
{
"code": null,
"e": 25820,
"s": 25619,
"text": "Syntax : set(iterable)Parameters : Any iterable sequence like list, tuple or dictionary.Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument. "
},
{
"code": null,
"e": 25940,
"s": 25820,
"text": "Don’t worry if you get an unordered list from the set. Sets are unordered. Use sorted(set(sampleList)) to get it sorted"
},
{
"code": null,
"e": 25991,
"s": 25940,
"text": "Code #1 : Demonstrating set() with list and tuple "
},
{
"code": null,
"e": 25999,
"s": 25991,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate the# working of set() on list and tuple # initializing listlis1 = [ 3, 4, 1, 4, 5 ] # initializing tupletup1 = (3, 4, 1, 4, 5) # Printing iterables before conversionprint(\"The list before conversion is : \" + str(lis1))print(\"The tuple before conversion is : \" + str(tup1)) # Iterables after conversion are# notice distinct and elementsprint(\"The list after conversion is : \" + str(set(lis1)))print(\"The tuple after conversion is : \" + str(set(tup1)))",
"e": 26480,
"s": 25999,
"text": null
},
{
"code": null,
"e": 26490,
"s": 26480,
"text": "Output: "
},
{
"code": null,
"e": 26676,
"s": 26490,
"text": "The list before conversion is : [3, 4, 1, 4, 5]\nThe tuple before conversion is : (3, 4, 1, 4, 5)\nThe list after conversion is : {1, 3, 4, 5}\nThe tuple after conversion is : {1, 3, 4, 5}"
},
{
"code": null,
"e": 26725,
"s": 26676,
"text": "No parameters are passed to create the empty set"
},
{
"code": null,
"e": 26823,
"s": 26725,
"text": "Dictionary can also be created using set, but only keys remain after conversion, values are lost."
},
{
"code": null,
"e": 26880,
"s": 26823,
"text": "Code #2: Demonstration of working of set on dictionary "
},
{
"code": null,
"e": 26888,
"s": 26880,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate the# working of set() on dictionary # initializing listdic1 = { 4 : 'geeks', 1 : 'for', 3 : 'geeks' } # Printing dictionary before conversion# internally sortedprint(\"Dictionary before conversion is : \" + str(dic1)) # Dictionary after conversion are# notice lost keysprint(\"Dictionary after conversion is : \" + str(set(dic1)))",
"e": 27245,
"s": 26888,
"text": null
},
{
"code": null,
"e": 27357,
"s": 27245,
"text": "Dictionary before conversion is : {4: 'geeks', 1: 'for', 3: 'geeks'}\nDictionary after conversion is : {1, 3, 4}"
},
{
"code": null,
"e": 27450,
"s": 27357,
"text": "Time Complexity: Set method is implemented as a hash table, so the time complexity is O(1). "
},
{
"code": null,
"e": 27466,
"s": 27450,
"text": "yashthakkar1173"
},
{
"code": null,
"e": 27483,
"s": 27466,
"text": "praveendhakad798"
},
{
"code": null,
"e": 27493,
"s": 27483,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27509,
"s": 27493,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27526,
"s": 27509,
"text": "anantmulchandani"
},
{
"code": null,
"e": 27552,
"s": 27526,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 27563,
"s": 27552,
"text": "python-set"
},
{
"code": null,
"e": 27584,
"s": 27563,
"text": "Python-set-functions"
},
{
"code": null,
"e": 27591,
"s": 27584,
"text": "Python"
},
{
"code": null,
"e": 27602,
"s": 27591,
"text": "python-set"
},
{
"code": null,
"e": 27700,
"s": 27602,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27732,
"s": 27700,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27754,
"s": 27732,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27796,
"s": 27754,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27822,
"s": 27796,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27851,
"s": 27822,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27895,
"s": 27851,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27932,
"s": 27895,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27968,
"s": 27932,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28010,
"s": 27968,
"text": "Check if element exists in list in Python"
}
] |
How to create a Struct Instance Using a Struct Literal in Golang? - GeeksforGeeks | 21 Feb, 2022
A structure or struct in Golang is a user-defined data type which is a composition of various data fields. Each data field has its own data type, which can be a built-in or another user-defined type. Struct represents any real-world entity which has some set of properties/fields. For Example, a student has a name, roll number, city, department. It makes sense to group these four properties into a single structure address as shown below.
type Student struct {
name string
roll_no int
city string
department string
}
Syntax for declaring a structure:
var x Student
The above code creates a variable of type Student in which fields by default are set to their respective zero values. Since struct is a composite data type, it is initialized using composite literals. Composite literals construct values for structs, arrays, slices, and maps where a single syntax is used for those types. Struct literals are used to create struct instances in Golang. You can create a struct instance using a struct literal as follows:
var d = Student{"Akshay", 1, "Lucknow", "Computer Science"}
We can also use a short declaration operator.
d := Student{"Akshay", 1, "Lucknow", "Computer Science"}
You must keep the following rules in mind while creating a struct literal:
A key must be a field name declared in the struct type.An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.A literal may omit the element list; such a literal evaluates to the zero value for its type.It is an error to specify an element for a non-exported field of a struct belonging to a different package.
A key must be a field name declared in the struct type.
An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.
An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
A literal may omit the element list; such a literal evaluates to the zero value for its type.
It is an error to specify an element for a non-exported field of a struct belonging to a different package.
Example 1:
C
// Golang program to show how to// declare and define the struct// using struct literalpackage main // importing required modulesimport "fmt" // Defining a struct typetype Student struct { name string roll_no int city string department string} func main() { // Declaring a variable of a `struct` type // All the struct fields are initialized // with their zero value var x Student fmt.Println("Student0:", x) // Declaring and initializing a // struct using a struct literal // Fields should be initialised in // the same order as they are declared // in struct's definition x1 := Student{"Akshay", 1, "Lucknow", "Computer Science"} fmt.Println("Student1: ", x1) // You can specify keys for // their respective values x2 := Student{name: "Anita", roll_no: 2, city: "Ballia", department: "Mechanical"} fmt.Println("Student2: ", x2)}
Output:
Student0: { 0 }
Student1: {Akshay 1 Lucknow Computer Science}
Student2: {Anita 2 Ballia Mechanical}
Uninitialized fields are set to their corresponding zero-values.Example 2:
C
// Golang program illustrating// the use of string literalspackage main // importing required modulesimport "fmt" // Defining a struct typetype Address struct { name, city string Pincode int} func main() { add1 := Address{name: "Ram"} fmt.Println("Address is:", add1)}
Output:
Address is: {Ram 0}
It must be noted that uninitialized values are set to zero values when field:value initializer is used during instantiation. The following code will output an error.Example:
C
// Golang program illustrating// the use of string literalspackage main // importing required modulesimport "fmt" // Defining a struct typetype Address struct { name, city string Pincode int} func main() { add1 := Address{"Ram"} fmt.Println("Address is: ", add1)}
Output:
Compilation Error: too few values in Address literal
If you specify least one key for an element, then you must specify all the other keys as well.Example:
C
package main // importing required modulesimport "fmt" // Defining a struct typetype Address struct { name, city string Pincode int} func main() { // Only 1 key is specified here add1 := Address{name: "Ram", "Mumbai", 221007} fmt.Println("Address is: ", add1)}
Output:
Compilation Error: mixture of field:value and value initializers
The above program throws an error as we have specified key for only one element and that creates a mixture of the field:value and value initializers. We should either go with the field:value or value initializers.
chhabradhanvi
Golang-Program
Picked
Go Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
strings.Replace() Function in Golang With Examples
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 25417,
"s": 25389,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 25859,
"s": 25417,
"text": "A structure or struct in Golang is a user-defined data type which is a composition of various data fields. Each data field has its own data type, which can be a built-in or another user-defined type. Struct represents any real-world entity which has some set of properties/fields. For Example, a student has a name, roll number, city, department. It makes sense to group these four properties into a single structure address as shown below. "
},
{
"code": null,
"e": 25962,
"s": 25859,
"text": "type Student struct {\n name string \n roll_no int\n city string\n department string\n}"
},
{
"code": null,
"e": 25998,
"s": 25962,
"text": "Syntax for declaring a structure: "
},
{
"code": null,
"e": 26012,
"s": 25998,
"text": "var x Student"
},
{
"code": null,
"e": 26466,
"s": 26012,
"text": "The above code creates a variable of type Student in which fields by default are set to their respective zero values. Since struct is a composite data type, it is initialized using composite literals. Composite literals construct values for structs, arrays, slices, and maps where a single syntax is used for those types. Struct literals are used to create struct instances in Golang. You can create a struct instance using a struct literal as follows: "
},
{
"code": null,
"e": 26526,
"s": 26466,
"text": "var d = Student{\"Akshay\", 1, \"Lucknow\", \"Computer Science\"}"
},
{
"code": null,
"e": 26573,
"s": 26526,
"text": "We can also use a short declaration operator. "
},
{
"code": null,
"e": 26631,
"s": 26573,
"text": "d := Student{\"Akshay\", 1, \"Lucknow\", \"Computer Science\"} "
},
{
"code": null,
"e": 26708,
"s": 26631,
"text": "You must keep the following rules in mind while creating a struct literal: "
},
{
"code": null,
"e": 27240,
"s": 26708,
"text": "A key must be a field name declared in the struct type.An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.A literal may omit the element list; such a literal evaluates to the zero value for its type.It is an error to specify an element for a non-exported field of a struct belonging to a different package."
},
{
"code": null,
"e": 27296,
"s": 27240,
"text": "A key must be a field name declared in the struct type."
},
{
"code": null,
"e": 27433,
"s": 27296,
"text": "An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared."
},
{
"code": null,
"e": 27574,
"s": 27433,
"text": "An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field."
},
{
"code": null,
"e": 27668,
"s": 27574,
"text": "A literal may omit the element list; such a literal evaluates to the zero value for its type."
},
{
"code": null,
"e": 27776,
"s": 27668,
"text": "It is an error to specify an element for a non-exported field of a struct belonging to a different package."
},
{
"code": null,
"e": 27788,
"s": 27776,
"text": "Example 1: "
},
{
"code": null,
"e": 27790,
"s": 27788,
"text": "C"
},
{
"code": "// Golang program to show how to// declare and define the struct// using struct literalpackage main // importing required modulesimport \"fmt\" // Defining a struct typetype Student struct { name string roll_no int city string department string} func main() { // Declaring a variable of a `struct` type // All the struct fields are initialized // with their zero value var x Student fmt.Println(\"Student0:\", x) // Declaring and initializing a // struct using a struct literal // Fields should be initialised in // the same order as they are declared // in struct's definition x1 := Student{\"Akshay\", 1, \"Lucknow\", \"Computer Science\"} fmt.Println(\"Student1: \", x1) // You can specify keys for // their respective values x2 := Student{name: \"Anita\", roll_no: 2, city: \"Ballia\", department: \"Mechanical\"} fmt.Println(\"Student2: \", x2)}",
"e": 28713,
"s": 27790,
"text": null
},
{
"code": null,
"e": 28722,
"s": 28713,
"text": "Output: "
},
{
"code": null,
"e": 28825,
"s": 28722,
"text": "Student0: { 0 }\nStudent1: {Akshay 1 Lucknow Computer Science}\nStudent2: {Anita 2 Ballia Mechanical}"
},
{
"code": null,
"e": 28901,
"s": 28825,
"text": "Uninitialized fields are set to their corresponding zero-values.Example 2: "
},
{
"code": null,
"e": 28903,
"s": 28901,
"text": "C"
},
{
"code": "// Golang program illustrating// the use of string literalspackage main // importing required modulesimport \"fmt\" // Defining a struct typetype Address struct { name, city string Pincode int} func main() { add1 := Address{name: \"Ram\"} fmt.Println(\"Address is:\", add1)}",
"e": 29187,
"s": 28903,
"text": null
},
{
"code": null,
"e": 29197,
"s": 29187,
"text": "Output: "
},
{
"code": null,
"e": 29218,
"s": 29197,
"text": "Address is: {Ram 0}"
},
{
"code": null,
"e": 29393,
"s": 29218,
"text": "It must be noted that uninitialized values are set to zero values when field:value initializer is used during instantiation. The following code will output an error.Example: "
},
{
"code": null,
"e": 29395,
"s": 29393,
"text": "C"
},
{
"code": "// Golang program illustrating// the use of string literalspackage main // importing required modulesimport \"fmt\" // Defining a struct typetype Address struct { name, city string Pincode int} func main() { add1 := Address{\"Ram\"} fmt.Println(\"Address is: \", add1)}",
"e": 29674,
"s": 29395,
"text": null
},
{
"code": null,
"e": 29684,
"s": 29674,
"text": "Output: "
},
{
"code": null,
"e": 29737,
"s": 29684,
"text": "Compilation Error: too few values in Address literal"
},
{
"code": null,
"e": 29841,
"s": 29737,
"text": "If you specify least one key for an element, then you must specify all the other keys as well.Example: "
},
{
"code": null,
"e": 29843,
"s": 29841,
"text": "C"
},
{
"code": "package main // importing required modulesimport \"fmt\" // Defining a struct typetype Address struct { name, city string Pincode int} func main() { // Only 1 key is specified here add1 := Address{name: \"Ram\", \"Mumbai\", 221007} fmt.Println(\"Address is: \", add1)}",
"e": 30122,
"s": 29843,
"text": null
},
{
"code": null,
"e": 30132,
"s": 30122,
"text": "Output: "
},
{
"code": null,
"e": 30197,
"s": 30132,
"text": "Compilation Error: mixture of field:value and value initializers"
},
{
"code": null,
"e": 30412,
"s": 30197,
"text": "The above program throws an error as we have specified key for only one element and that creates a mixture of the field:value and value initializers. We should either go with the field:value or value initializers. "
},
{
"code": null,
"e": 30426,
"s": 30412,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 30441,
"s": 30426,
"text": "Golang-Program"
},
{
"code": null,
"e": 30448,
"s": 30441,
"text": "Picked"
},
{
"code": null,
"e": 30460,
"s": 30448,
"text": "Go Language"
},
{
"code": null,
"e": 30476,
"s": 30460,
"text": "Write From Home"
},
{
"code": null,
"e": 30574,
"s": 30476,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30620,
"s": 30574,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 30671,
"s": 30620,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 30684,
"s": 30671,
"text": "Arrays in Go"
},
{
"code": null,
"e": 30731,
"s": 30684,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 30764,
"s": 30731,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 30800,
"s": 30764,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 30836,
"s": 30800,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 30897,
"s": 30836,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30913,
"s": 30897,
"text": "Python infinity"
}
] |
Poisson Regression in R Programming - GeeksforGeeks | 10 May, 2020
A Poisson Regression model is used to model count data and model response variables (Y-values) that are counts. It shows which X-values work on the Y-value and more categorically, it counts data: discrete data with non-negative integer values that count something.
In other words, it shows which explanatory variables have a notable effect on the response variable. Poisson Regression involves regression models in which the response variable is in the form of counts and not fractional numbers.
Mathematical Equation:
log(y) = a + b1x1 + b2x2 + bnxn.....
Parameters:
y: This parameter sets as a response variable.
a and b: The parameter a and b are the numeric coefficients.
x: This parameter is the predictor variable.
The function used to create the Poisson regression model is the glm() function.
Syntax: glm(formula, data, family)
Parameters:
formula: This parameter is the symbol presenting the relationship between the variables.
data: The parameter is the data set giving the values of these variables.
family: This parameter R object to specify the details of the model. It’s value is ‘Poisson’ for Logistic Regression.
Example:
We use the data set “warpbreaks”.
Considering “breaks” as the response variable.
The wool “type” and “tension” are taken as predictor variables.
Code:
input <- warpbreaksprint(head(input))
Output:
Approach: Creating the poisson regression model:
Take the parameters which are required to make model.
let’s use summary() function to find the summary of the model for data analysis.
Example:
output <-glm(formula = breaks ~ wool + tension, data = warpbreaks, family = poisson)print(summary(output))
Output:
Approach: Creating the regression model with the help of the glm() function as:
With the help of this function, easy to make model.
Now we draw a graph for the relation between “formula”, “data” and “family”.
Example:
output_result <-glm(formula = breaks ~ wool + tension, data = warpbreaks, family = poisson) output_result
Output:
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
How to filter R dataframe by multiple conditions? | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26752,
"s": 26487,
"text": "A Poisson Regression model is used to model count data and model response variables (Y-values) that are counts. It shows which X-values work on the Y-value and more categorically, it counts data: discrete data with non-negative integer values that count something."
},
{
"code": null,
"e": 26983,
"s": 26752,
"text": "In other words, it shows which explanatory variables have a notable effect on the response variable. Poisson Regression involves regression models in which the response variable is in the form of counts and not fractional numbers."
},
{
"code": null,
"e": 27006,
"s": 26983,
"text": "Mathematical Equation:"
},
{
"code": null,
"e": 27043,
"s": 27006,
"text": "log(y) = a + b1x1 + b2x2 + bnxn....."
},
{
"code": null,
"e": 27055,
"s": 27043,
"text": "Parameters:"
},
{
"code": null,
"e": 27102,
"s": 27055,
"text": "y: This parameter sets as a response variable."
},
{
"code": null,
"e": 27163,
"s": 27102,
"text": "a and b: The parameter a and b are the numeric coefficients."
},
{
"code": null,
"e": 27208,
"s": 27163,
"text": "x: This parameter is the predictor variable."
},
{
"code": null,
"e": 27288,
"s": 27208,
"text": "The function used to create the Poisson regression model is the glm() function."
},
{
"code": null,
"e": 27323,
"s": 27288,
"text": "Syntax: glm(formula, data, family)"
},
{
"code": null,
"e": 27335,
"s": 27323,
"text": "Parameters:"
},
{
"code": null,
"e": 27424,
"s": 27335,
"text": "formula: This parameter is the symbol presenting the relationship between the variables."
},
{
"code": null,
"e": 27498,
"s": 27424,
"text": "data: The parameter is the data set giving the values of these variables."
},
{
"code": null,
"e": 27616,
"s": 27498,
"text": "family: This parameter R object to specify the details of the model. It’s value is ‘Poisson’ for Logistic Regression."
},
{
"code": null,
"e": 27625,
"s": 27616,
"text": "Example:"
},
{
"code": null,
"e": 27659,
"s": 27625,
"text": "We use the data set “warpbreaks”."
},
{
"code": null,
"e": 27706,
"s": 27659,
"text": "Considering “breaks” as the response variable."
},
{
"code": null,
"e": 27770,
"s": 27706,
"text": "The wool “type” and “tension” are taken as predictor variables."
},
{
"code": null,
"e": 27776,
"s": 27770,
"text": "Code:"
},
{
"code": "input <- warpbreaksprint(head(input))",
"e": 27814,
"s": 27776,
"text": null
},
{
"code": null,
"e": 27822,
"s": 27814,
"text": "Output:"
},
{
"code": null,
"e": 27871,
"s": 27822,
"text": "Approach: Creating the poisson regression model:"
},
{
"code": null,
"e": 27925,
"s": 27871,
"text": "Take the parameters which are required to make model."
},
{
"code": null,
"e": 28006,
"s": 27925,
"text": "let’s use summary() function to find the summary of the model for data analysis."
},
{
"code": null,
"e": 28015,
"s": 28006,
"text": "Example:"
},
{
"code": "output <-glm(formula = breaks ~ wool + tension, data = warpbreaks, family = poisson)print(summary(output)) ",
"e": 28139,
"s": 28015,
"text": null
},
{
"code": null,
"e": 28147,
"s": 28139,
"text": "Output:"
},
{
"code": null,
"e": 28227,
"s": 28147,
"text": "Approach: Creating the regression model with the help of the glm() function as:"
},
{
"code": null,
"e": 28279,
"s": 28227,
"text": "With the help of this function, easy to make model."
},
{
"code": null,
"e": 28356,
"s": 28279,
"text": "Now we draw a graph for the relation between “formula”, “data” and “family”."
},
{
"code": null,
"e": 28365,
"s": 28356,
"text": "Example:"
},
{
"code": "output_result <-glm(formula = breaks ~ wool + tension, data = warpbreaks, family = poisson) output_result ",
"e": 28492,
"s": 28365,
"text": null
},
{
"code": null,
"e": 28500,
"s": 28492,
"text": "Output:"
},
{
"code": null,
"e": 28511,
"s": 28500,
"text": "R Language"
},
{
"code": null,
"e": 28609,
"s": 28511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28661,
"s": 28609,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28696,
"s": 28661,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28734,
"s": 28696,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28792,
"s": 28734,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28835,
"s": 28792,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28884,
"s": 28835,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28921,
"s": 28884,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 28938,
"s": 28921,
"text": "R - if statement"
},
{
"code": null,
"e": 28964,
"s": 28938,
"text": "Time Series Analysis in R"
}
] |
Lazy Composables in Android Jetpack Compose - Columns, Rows, Grids - GeeksforGeeks | 28 Jul, 2021
In Jetpack compose we have Composables like Column and Row but when the app needs to display a large number of items in a row or columns then it’s not efficient if done by Row or Column Composable. Therefore we have Lazy Composables in Jetpack Compose. Mainly we have three kinds of Lazy Composables Row, Column, and Grid. In this article, we are going to look at all three Lazy Composables. We will build a simple app that demonstrates all three composables in action.
Prerequisites:
Knowledge of Kotlin.
Knowledge of Jetpack Compose.
Step 1: Create a New Project (Or use it in the existing Compose project)
To create a new project in the Android Studio Canary version, refer to the article How to Create a new Project in the Android Studio Canary Version with Jetpack Compose.
Step 2 : Add Color (optional)
Open ui > theme > Colors.kt and add
val GreenGfg = Color(0xFF0F9D58)
Step 3: Create Row and Column Items that are going to be displayed
Open MainActivity.kt and create two Composables, one for Row Item and One for Column Item
Kotlin
// Row Item with item Number @Composablefun RowItem(number: Int) { // Simple Row Composable Row( modifier = Modifier .size(100.dp) // Size 100 dp .background(Color.White) // Background White .border(1.dp, GreenGfg), // Border color green // Align Items in Center verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { // Text Composable which displays some // kind of message , text color is green Text(text = "This Is Item Number $number", color = GreenGfg) }} // Similar to row composable created above@Composablefun ColumnItem(number: Int) { Column( modifier = Modifier .fillMaxWidth() .height(30.dp) .background(Color.White) .border(1.dp, GreenGfg), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "This Is Item Number $number", color = GreenGfg) }}
Step 4: Working with Lazy Composables
Unline Column or Row Composable we cannot place composable inside directly inside Lazy Composables. Lazy Composables provides functions to place items in the LazyScope. There is mainly five overloaded functions.
Function
Parameter
Functionality
Places number of items present same as the size of Array,
and provides item(in list) and index of current Item.
Step 4.1: Lazy Row
Create a Composable in MainActivity.kt, here we will place Lazy row to demonstrate Lazy Row
Kotlin
@Composablefun LazyRowExample(numbers: Array<Int>) { // Place A lazy Row LazyRow( contentPadding = PaddingValues(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { RowItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> RowItem(number = currentCount) } // items(list/array) places number of items same as // the size of list/array and gives current list/array // item in the lazyItemScope items(numbers) {arrayItem-> // Here numbers is Array<Int> so we // get Int in the scope. RowItem(number = arrayItem) } // items(list/array) places number of items same // as the size of list/array and gives current list/array // item and currentIndex in the lazyItemScope itemsIndexed(numbers) { index: Int, item: Int -> RowItem(number = index) } }}
Step 4.2: Lazy Column
Create a Composable in MainActivity.kt, here we will place Lazy Column to demonstrate Lazy Column
Kotlin
@Composablefun ColumnExample(numbers: Array<Int>) { LazyColumn( contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { ColumnItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> ColumnItem(number = currentCount) } // items(list/array) places number of items same // as the size of list/array and gives current // list/array item in the lazyItemScope items(numbers) {arrayItem-> ColumnItem(number = arrayItem) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item and currentIndex // in the lazyItemScope itemsIndexed(numbers) { index, item -> ColumnItem(number = index) } }}
Step 4.3: Lazy Grid
Create a Composable in MainActivity.kt, here we will place LazyVerticalGrid. It’s almost the same as other lazy composable but it takes an extra parameter cells which is the number of grid items in one row / minimum width of one item. cells can be either GridCells.Fixed(count), It fixes the items displayed in one grid row. Another value it accepts is GridCells.Adaptive(minWidth), it sets the minWidth of each grid item.
Kotlin
// add the annotation, // since [LazyVerticalGrid] is Experimental Api@ExperimentalFoundationApi@Composablefun GridExample(numbers: Array<Int>) { // Lazy Vertical grid LazyVerticalGrid( // fix the item in one row to be 2. cells = GridCells.Fixed(2), contentPadding = PaddingValues(8.dp), ) { item { RowItem(number = 0) } items(10) { RowItem(number = it) } items(numbers) { RowItem(number = it) } itemsIndexed(numbers) { index, item -> RowItem(number = index) } }}
Step 5: Placing the Composables on Screen
Now place all three examples in setContentView in MainActivity Class.
Kotlin
class MainActivity : ComponentActivity() { // Creates array as [0,1,2,3,4,5,.....99] private val numbers: Array<Int> = Array(100) { it + 1 } @ExperimentalFoundationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LazyComponentsTheme { Column( modifier = Modifier .fillMaxSize() .background(Color.White) ) { // Place the row and column // to take 50% height of screen Column(Modifier.fillMaxHeight(0.5f)) { // Heading Text( text = "Row", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Row, pass the numbers array LazyRowExample(numbers = numbers) // Heading Text( text = "Column", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Column, Pass the numbers array LazyColumnExample(numbers = numbers) } Column(Modifier.fillMaxHeight()) { // Heading Text( text = "Grid", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Grid GridExample(numbers = numbers) } } } } }}
Complete Code:
Note: Before running this whole code, make sure to do Step 2, or replace GreenGfg with your own color.
Kotlin
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.*import androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.unit.dpimport com.gfg.lazycomponents.ui.theme.GreenGfgimport com.gfg.lazycomponents.ui.theme.LazyComponentsTheme class MainActivity : ComponentActivity() { // Creates array as [0,1,2,3,4,5,.....99] private val numbers: Array<Int> = Array(100) { it + 1 } @ExperimentalFoundationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LazyComponentsTheme { Column( modifier = Modifier .fillMaxSize() .background(Color.White) ) { // Place the row and column // to take 50% height of screen Column(Modifier.fillMaxHeight(0.5f)) { // Heading Text( text = "Row", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Row,pass the numbers array LazyRowExample(numbers = numbers) // Heading Text( text = "Column", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Column, Pass the numbers array LazyColumnExample(numbers = numbers) } Column(Modifier.fillMaxHeight()) { // Heading Text( text = "Grid", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Grid GridExample(numbers = numbers) } } } } }} @Composablefun LazyRowExample(numbers: Array<Int>) { // Place A lazy Row LazyRow( contentPadding = PaddingValues(8.dp), // Each Item in LazyRow have a 8.dp margin horizontalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { RowItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> RowItem(number = currentCount) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item in the lazyItemScope items(numbers) {arrayItem-> // Here numbers is Array<Int> so we // get Int in the scope. RowItem(number = arrayItem) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item and currentIndex // in the lazyItemScope itemsIndexed(numbers) { index: Int, item: Int -> RowItem(number = index) } }} @Composablefun RowItem(number: Int) { // Simple Row Composable Row( modifier = Modifier .size(100.dp) // Size 100 dp .background(Color.White) // Background White .border(1.dp, GreenGfg), // Border color green // Align Items in Center verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { // Text Composable which displays some // kind of message , text color is green Text(text = "This Is Item Number $number", color = GreenGfg) }} @Composablefun ColumnItem(number: Int) { Column( modifier = Modifier .fillMaxWidth() .height(30.dp) .background(Color.White) .border(1.dp, GreenGfg), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "This Is Item Number $number", color = GreenGfg) }} @Composablefun LazyColumnExample(numbers: Array<Int>) { LazyColumn( contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { ColumnItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> ColumnItem(number = currentCount) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item in the lazyItemScope items(numbers) {arrayItem-> ColumnItem(number = arrayItem) } // items(list/array) places number of // items same as the size of list/array // and gives current list/array item and // currentIndex in the lazyItemScope itemsIndexed(numbers) { index, item -> ColumnItem(number = index) } }} // add the annotation, // since [LazyVerticalGrid] is Experimental Api@ExperimentalFoundationApi@Composablefun GridExample(numbers: Array<Int>) { // Lazy Vertical grid LazyVerticalGrid( // fix the item in one row to be 2. cells = GridCells.Fixed(2), contentPadding = PaddingValues(8.dp), ) { item { RowItem(number = 0) } items(10) { RowItem(number = it) } items(numbers) { RowItem(number = it) } itemsIndexed(numbers) { index, item -> RowItem(number = index) } }}
Now run the app on an emulator or phone.
Output:
Get the complete code from GitHub.
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 26851,
"s": 26381,
"text": "In Jetpack compose we have Composables like Column and Row but when the app needs to display a large number of items in a row or columns then it’s not efficient if done by Row or Column Composable. Therefore we have Lazy Composables in Jetpack Compose. Mainly we have three kinds of Lazy Composables Row, Column, and Grid. In this article, we are going to look at all three Lazy Composables. We will build a simple app that demonstrates all three composables in action."
},
{
"code": null,
"e": 26866,
"s": 26851,
"text": "Prerequisites:"
},
{
"code": null,
"e": 26887,
"s": 26866,
"text": "Knowledge of Kotlin."
},
{
"code": null,
"e": 26917,
"s": 26887,
"text": "Knowledge of Jetpack Compose."
},
{
"code": null,
"e": 26990,
"s": 26917,
"text": "Step 1: Create a New Project (Or use it in the existing Compose project)"
},
{
"code": null,
"e": 27160,
"s": 26990,
"text": "To create a new project in the Android Studio Canary version, refer to the article How to Create a new Project in the Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 27190,
"s": 27160,
"text": "Step 2 : Add Color (optional)"
},
{
"code": null,
"e": 27227,
"s": 27190,
"text": "Open ui > theme > Colors.kt and add "
},
{
"code": null,
"e": 27260,
"s": 27227,
"text": "val GreenGfg = Color(0xFF0F9D58)"
},
{
"code": null,
"e": 27327,
"s": 27260,
"text": "Step 3: Create Row and Column Items that are going to be displayed"
},
{
"code": null,
"e": 27417,
"s": 27327,
"text": "Open MainActivity.kt and create two Composables, one for Row Item and One for Column Item"
},
{
"code": null,
"e": 27424,
"s": 27417,
"text": "Kotlin"
},
{
"code": "// Row Item with item Number @Composablefun RowItem(number: Int) { // Simple Row Composable Row( modifier = Modifier .size(100.dp) // Size 100 dp .background(Color.White) // Background White .border(1.dp, GreenGfg), // Border color green // Align Items in Center verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { // Text Composable which displays some // kind of message , text color is green Text(text = \"This Is Item Number $number\", color = GreenGfg) }} // Similar to row composable created above@Composablefun ColumnItem(number: Int) { Column( modifier = Modifier .fillMaxWidth() .height(30.dp) .background(Color.White) .border(1.dp, GreenGfg), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = \"This Is Item Number $number\", color = GreenGfg) }}",
"e": 28466,
"s": 27424,
"text": null
},
{
"code": null,
"e": 28504,
"s": 28466,
"text": "Step 4: Working with Lazy Composables"
},
{
"code": null,
"e": 28717,
"s": 28504,
"text": "Unline Column or Row Composable we cannot place composable inside directly inside Lazy Composables. Lazy Composables provides functions to place items in the LazyScope. There is mainly five overloaded functions. "
},
{
"code": null,
"e": 28726,
"s": 28717,
"text": "Function"
},
{
"code": null,
"e": 28736,
"s": 28726,
"text": "Parameter"
},
{
"code": null,
"e": 28750,
"s": 28736,
"text": "Functionality"
},
{
"code": null,
"e": 28808,
"s": 28750,
"text": "Places number of items present same as the size of Array,"
},
{
"code": null,
"e": 28862,
"s": 28808,
"text": "and provides item(in list) and index of current Item."
},
{
"code": null,
"e": 28881,
"s": 28862,
"text": "Step 4.1: Lazy Row"
},
{
"code": null,
"e": 28973,
"s": 28881,
"text": "Create a Composable in MainActivity.kt, here we will place Lazy row to demonstrate Lazy Row"
},
{
"code": null,
"e": 28980,
"s": 28973,
"text": "Kotlin"
},
{
"code": "@Composablefun LazyRowExample(numbers: Array<Int>) { // Place A lazy Row LazyRow( contentPadding = PaddingValues(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { RowItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> RowItem(number = currentCount) } // items(list/array) places number of items same as // the size of list/array and gives current list/array // item in the lazyItemScope items(numbers) {arrayItem-> // Here numbers is Array<Int> so we // get Int in the scope. RowItem(number = arrayItem) } // items(list/array) places number of items same // as the size of list/array and gives current list/array // item and currentIndex in the lazyItemScope itemsIndexed(numbers) { index: Int, item: Int -> RowItem(number = index) } }}",
"e": 30114,
"s": 28980,
"text": null
},
{
"code": null,
"e": 30137,
"s": 30114,
"text": " Step 4.2: Lazy Column"
},
{
"code": null,
"e": 30235,
"s": 30137,
"text": "Create a Composable in MainActivity.kt, here we will place Lazy Column to demonstrate Lazy Column"
},
{
"code": null,
"e": 30242,
"s": 30235,
"text": "Kotlin"
},
{
"code": "@Composablefun ColumnExample(numbers: Array<Int>) { LazyColumn( contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { ColumnItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> ColumnItem(number = currentCount) } // items(list/array) places number of items same // as the size of list/array and gives current // list/array item in the lazyItemScope items(numbers) {arrayItem-> ColumnItem(number = arrayItem) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item and currentIndex // in the lazyItemScope itemsIndexed(numbers) { index, item -> ColumnItem(number = index) } }}",
"e": 31266,
"s": 30242,
"text": null
},
{
"code": null,
"e": 31286,
"s": 31266,
"text": "Step 4.3: Lazy Grid"
},
{
"code": null,
"e": 31709,
"s": 31286,
"text": "Create a Composable in MainActivity.kt, here we will place LazyVerticalGrid. It’s almost the same as other lazy composable but it takes an extra parameter cells which is the number of grid items in one row / minimum width of one item. cells can be either GridCells.Fixed(count), It fixes the items displayed in one grid row. Another value it accepts is GridCells.Adaptive(minWidth), it sets the minWidth of each grid item."
},
{
"code": null,
"e": 31716,
"s": 31709,
"text": "Kotlin"
},
{
"code": "// add the annotation, // since [LazyVerticalGrid] is Experimental Api@ExperimentalFoundationApi@Composablefun GridExample(numbers: Array<Int>) { // Lazy Vertical grid LazyVerticalGrid( // fix the item in one row to be 2. cells = GridCells.Fixed(2), contentPadding = PaddingValues(8.dp), ) { item { RowItem(number = 0) } items(10) { RowItem(number = it) } items(numbers) { RowItem(number = it) } itemsIndexed(numbers) { index, item -> RowItem(number = index) } }}",
"e": 32321,
"s": 31716,
"text": null
},
{
"code": null,
"e": 32363,
"s": 32321,
"text": "Step 5: Placing the Composables on Screen"
},
{
"code": null,
"e": 32433,
"s": 32363,
"text": "Now place all three examples in setContentView in MainActivity Class."
},
{
"code": null,
"e": 32440,
"s": 32433,
"text": "Kotlin"
},
{
"code": "class MainActivity : ComponentActivity() { // Creates array as [0,1,2,3,4,5,.....99] private val numbers: Array<Int> = Array(100) { it + 1 } @ExperimentalFoundationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LazyComponentsTheme { Column( modifier = Modifier .fillMaxSize() .background(Color.White) ) { // Place the row and column // to take 50% height of screen Column(Modifier.fillMaxHeight(0.5f)) { // Heading Text( text = \"Row\", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Row, pass the numbers array LazyRowExample(numbers = numbers) // Heading Text( text = \"Column\", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Column, Pass the numbers array LazyColumnExample(numbers = numbers) } Column(Modifier.fillMaxHeight()) { // Heading Text( text = \"Grid\", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Grid GridExample(numbers = numbers) } } } } }}",
"e": 34461,
"s": 32440,
"text": null
},
{
"code": null,
"e": 34477,
"s": 34461,
"text": "Complete Code: "
},
{
"code": null,
"e": 34580,
"s": 34477,
"text": "Note: Before running this whole code, make sure to do Step 2, or replace GreenGfg with your own color."
},
{
"code": null,
"e": 34587,
"s": 34580,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.*import androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.unit.dpimport com.gfg.lazycomponents.ui.theme.GreenGfgimport com.gfg.lazycomponents.ui.theme.LazyComponentsTheme class MainActivity : ComponentActivity() { // Creates array as [0,1,2,3,4,5,.....99] private val numbers: Array<Int> = Array(100) { it + 1 } @ExperimentalFoundationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LazyComponentsTheme { Column( modifier = Modifier .fillMaxSize() .background(Color.White) ) { // Place the row and column // to take 50% height of screen Column(Modifier.fillMaxHeight(0.5f)) { // Heading Text( text = \"Row\", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Row,pass the numbers array LazyRowExample(numbers = numbers) // Heading Text( text = \"Column\", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Column, Pass the numbers array LazyColumnExample(numbers = numbers) } Column(Modifier.fillMaxHeight()) { // Heading Text( text = \"Grid\", color = Color.Black, modifier = Modifier.padding(start = 8.dp) ) // Lazy Grid GridExample(numbers = numbers) } } } } }} @Composablefun LazyRowExample(numbers: Array<Int>) { // Place A lazy Row LazyRow( contentPadding = PaddingValues(8.dp), // Each Item in LazyRow have a 8.dp margin horizontalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { RowItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> RowItem(number = currentCount) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item in the lazyItemScope items(numbers) {arrayItem-> // Here numbers is Array<Int> so we // get Int in the scope. RowItem(number = arrayItem) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item and currentIndex // in the lazyItemScope itemsIndexed(numbers) { index: Int, item: Int -> RowItem(number = index) } }} @Composablefun RowItem(number: Int) { // Simple Row Composable Row( modifier = Modifier .size(100.dp) // Size 100 dp .background(Color.White) // Background White .border(1.dp, GreenGfg), // Border color green // Align Items in Center verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { // Text Composable which displays some // kind of message , text color is green Text(text = \"This Is Item Number $number\", color = GreenGfg) }} @Composablefun ColumnItem(number: Int) { Column( modifier = Modifier .fillMaxWidth() .height(30.dp) .background(Color.White) .border(1.dp, GreenGfg), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = \"This Is Item Number $number\", color = GreenGfg) }} @Composablefun LazyColumnExample(numbers: Array<Int>) { LazyColumn( contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { // item places one item on the LazyScope item { ColumnItem(number = 0) } // items(count) places number of items supplied // as count and gives current count in the lazyItemScope items(10) {currentCount-> ColumnItem(number = currentCount) } // items(list/array) places number of items // same as the size of list/array and gives // current list/array item in the lazyItemScope items(numbers) {arrayItem-> ColumnItem(number = arrayItem) } // items(list/array) places number of // items same as the size of list/array // and gives current list/array item and // currentIndex in the lazyItemScope itemsIndexed(numbers) { index, item -> ColumnItem(number = index) } }} // add the annotation, // since [LazyVerticalGrid] is Experimental Api@ExperimentalFoundationApi@Composablefun GridExample(numbers: Array<Int>) { // Lazy Vertical grid LazyVerticalGrid( // fix the item in one row to be 2. cells = GridCells.Fixed(2), contentPadding = PaddingValues(8.dp), ) { item { RowItem(number = 0) } items(10) { RowItem(number = it) } items(numbers) { RowItem(number = it) } itemsIndexed(numbers) { index, item -> RowItem(number = index) } }}",
"e": 40957,
"s": 34587,
"text": null
},
{
"code": null,
"e": 40998,
"s": 40957,
"text": "Now run the app on an emulator or phone."
},
{
"code": null,
"e": 41006,
"s": 40998,
"text": "Output:"
},
{
"code": null,
"e": 41041,
"s": 41006,
"text": "Get the complete code from GitHub."
},
{
"code": null,
"e": 41057,
"s": 41041,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 41065,
"s": 41057,
"text": "Android"
},
{
"code": null,
"e": 41072,
"s": 41065,
"text": "Kotlin"
},
{
"code": null,
"e": 41080,
"s": 41072,
"text": "Android"
},
{
"code": null,
"e": 41178,
"s": 41080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41216,
"s": 41178,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 41255,
"s": 41216,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 41305,
"s": 41255,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 41356,
"s": 41305,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 41398,
"s": 41356,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 41417,
"s": 41398,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 41430,
"s": 41417,
"text": "Kotlin Array"
},
{
"code": null,
"e": 41472,
"s": 41430,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 41512,
"s": 41472,
"text": "How to Get Current Location in Android?"
}
] |
Print reverse of a Linked List without extra space and modifications - GeeksforGeeks | CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
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)
Doubly Linked List | Set 1 (Introduction and Insertion)
LinkedList in Java
Detect loop in a linked list
Linked List vs Array
Find the middle of a given linked list
Merge two sorted linked lists
Implement a stack using singly linked list
Queue - Linked List Implementation
Delete a Linked List node at a given position
Merge Sort for Linked Lists
Implementing a Linked List in Java using Class
Function to check if a singly linked list is palindrome
Find Length of a Linked List (Iterative and Recursive)
Detect and Remove Loop in a Linked List
Circular Linked List | Set 1 (Introduction and Applications)
Reverse a Linked List in groups of given size | Set 1
Search an element in a Linked List (Iterative and Recursive)
Program for n'th node from the end of a Linked List
Write a function to delete a Linked List
Write a function to get the intersection point of two Linked Lists
Remove duplicates from a sorted linked list
Top 20 Linked List Interview Question
Add two numbers represented by linked lists | Set 1
Remove duplicates from an unsorted linked list
Write a function to get Nth node in a Linked List
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)
Doubly Linked List | Set 1 (Introduction and Insertion)
LinkedList in Java
Detect loop in a linked list
Linked List vs Array
Find the middle of a given linked list
Merge two sorted linked lists
Implement a stack using singly linked list
Queue - Linked List Implementation
Delete a Linked List node at a given position
Merge Sort for Linked Lists
Implementing a Linked List in Java using Class
Function to check if a singly linked list is palindrome
Find Length of a Linked List (Iterative and Recursive)
Detect and Remove Loop in a Linked List
Circular Linked List | Set 1 (Introduction and Applications)
Reverse a Linked List in groups of given size | Set 1
Search an element in a Linked List (Iterative and Recursive)
Program for n'th node from the end of a Linked List
Write a function to delete a Linked List
Write a function to get the intersection point of two Linked Lists
Remove duplicates from a sorted linked list
Top 20 Linked List Interview Question
Add two numbers represented by linked lists | Set 1
Remove duplicates from an unsorted linked list
Write a function to get Nth node in a Linked List
Difficulty Level :
Easy
Given a Linked List, display the linked list in reverse without using recursion, stack or modifications to given list.Examples:
Input : 1->2->3->4->5->NULL
Output :5->4->3->2->1->NULL
Input :10->5->15->20->24->NULL
Output :24->20->15->5->10->NULL
Below are different solutions that are now allowed here as we cannot use extra space and modify list.1) Recursive solution to print reverse a linked list. Requires extra space.2) Reverse linked list and then print. This requires modifications to original list. 3) Stack based solution to print linked list reverse. Push all nodes one by one to a stack. Then one by one pop elements from stack and print. This also requires extra space.Algorithms:
1) Find n = count nodes in linked list.
2) For i = n to 1, do following.
Print i-th node using get n-th node function
C++
Java
Python3
C#
Javascript
// C/C++ program to print reverse of linked list// without extra space and without modifications.#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Counts no. of nodes in linked list */int getCount(struct Node* head){ int count = 0; // Initialize count struct Node* current = head; // Initialize current while (current != NULL) { count++; current = current->next; } return count;} /* Takes head pointer of the linked list and index as arguments and return data at index*/int getNth(struct Node* head, int n){ struct Node* curr = head; for (int i=0; i<n-1 && curr != NULL; i++) curr = curr->next; return curr->data;} void printReverse(Node *head){ // Count nodes int n = getCount(head); for (int i=n; i>=1; i--) printf("%d ", getNth(head, i));} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printReverse(head); return 0;}
// Java program to print reverse of linked list// without extra space and without modifications.class GFG{ /* Link list node */static class Node{ int data; Node next;};static Node head; /* Given a reference (pointer to pointer) tothe head of a list and an int, push a new nodeon the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; head = head_ref;} /* Counts no. of nodes in linked list */static int getCount(Node head){ int count = 0; // Initialize count Node current = head; // Initialize current while (current != null) { count++; current = current.next; } return count;} /* Takes head pointer of the linked list andindex as arguments and return data at index*/static int getNth(Node head, int n){ Node curr = head; for (int i = 0; i < n - 1 && curr != null; i++) curr = curr.next; return curr.data;} static void printReverse(){ // Count nodes int n = getCount(head); for (int i = n; i >= 1; i--) System.out.printf("%d ", getNth(head, i));} // Driver Codepublic static void main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct below list 1->2->3->4->5 */ push(head, 5); push(head, 4); push(head, 3); push(head, 2); push(head, 1); printReverse();}} // This code is contributed by PrinciRaj1992
# Python3 program to print reverse of linked list# without extra space and without modifications. ''' Link list node '''class Node: def __init__(self, data): self.data = data self.next = None ''' Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. '''def push( head_ref, new_data): new_node = Node(new_data) new_node.next = head_ref; head_ref = new_node; return head_ref ''' Counts no. of nodes in linked list '''def getCount(head): count = 0; # Initialize count current = head; # Initialize current while (current != None): count += 1 current = current.next; return count; ''' Takes head pointer of the linked list and index as arguments and return data at index'''def getNth(head, n): curr = head; i = 0 while i < n - 1 and curr != None: curr = curr.next; i += 1 return curr.data; def printReverse(head): # Count nodes n = getCount(head); for i in range(n, 0, -1): print(getNth(head, i), end = ' '); # Driver codeif __name__=='__main__': ''' Start with the empty list ''' head = None; ''' Use push() to construct below list 1.2.3.4.5 ''' head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printReverse(head); # This code is contributed by rutvik_56
// C# program to print reverse of// linked list without extra space// and without modifications.using System; class GFG{ /* Link list node */public class Node{ public int data; public Node next;};static Node head; /* Given a reference (pointer to pointer)to the head of a list and an int, push anew node on the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; head = head_ref;} /* Counts no. of nodes in linked list */static int getCount(Node head){ int count = 0; // Initialize count Node current = head; // Initialize current while (current != null) { count++; current = current.next; } return count;} /* Takes head pointer of the linked list andindex as arguments and return data at index*/static int getNth(Node head, int n){ Node curr = head; for (int i = 0; i < n - 1 && curr != null; i++) curr = curr.next; return curr.data;} static void printReverse(){ // Count nodes int n = getCount(head); for (int i = n; i >= 1; i--) Console.Write("{0} ", getNth(head, i));} // Driver Codepublic static void Main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct below list 1->2->3->4->5 */ push(head, 5); push(head, 4); push(head, 3); push(head, 2); push(head, 1); printReverse();}} // This code is contributed by Princi Singh
<script> // JavaScript program to implement above approach // Link list nodeclass Node{ constructor(data){ this.data = data this.next = null }} // Given a reference (pointer to pointer) to the head// of a list and an int, push a new node on the front// of the list. function push( head_ref, new_data){ let new_node = new Node(new_data) new_node.next = head_ref; head_ref = new_node; return head_ref} // Counts no. of nodes in linked list function getCount(head){ let count = 0; // Initialize count let current = head; // Initialize current while (current != null){ count += 1 current = current.next; } return count;} // Takes head pointer of the linked list and index// as arguments and return data at index function getNth(head, n){ let curr = head; let i = 0 while(i < n - 1 && curr != null){ curr = curr.next; i += 1 } return curr.data;} function printReverse(head){ // Count nodes let n = getCount(head); for(let i=n;i>0;i--) document.write(getNth(head, i),' ');} // Driver code // Start with the empty listlet head = null; // Use push() to construct below list// 1.2.3.4.5head = push(head, 5);head = push(head, 4);head = push(head, 3);head = push(head, 2);head = push(head, 1); printReverse(head); // This code is contributed by shinjanpatra </script>
Output:
5 4 3 2 1
princiraj1992
princi singh
nidhi_biet
rutvik_56
simmytarika5
shinjanpatra
programming-puzzle
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Delete a node in a Doubly Linked List
Real-time application of Data Structures
Linked List Implementation in C#
Insert a node at a specific position in a linked list
Move last element to front of a given Linked List | [
{
"code": null,
"e": 419,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses"
},
{
"code": null,
"e": 600,
"s": 419,
"text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 685,
"s": 600,
"text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More"
},
{
"code": null,
"e": 702,
"s": 685,
"text": "DSA Live Classes"
},
{
"code": null,
"e": 716,
"s": 702,
"text": "System Design"
},
{
"code": null,
"e": 741,
"s": 716,
"text": "Java Backend Development"
},
{
"code": null,
"e": 757,
"s": 741,
"text": "Full Stack LIVE"
},
{
"code": null,
"e": 770,
"s": 757,
"text": "Explore More"
},
{
"code": null,
"e": 842,
"s": 770,
"text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 858,
"s": 842,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 869,
"s": 858,
"text": "SDE Theory"
},
{
"code": null,
"e": 894,
"s": 869,
"text": "Must-Do Coding Questions"
},
{
"code": null,
"e": 907,
"s": 894,
"text": "Explore More"
},
{
"code": null,
"e": 1054,
"s": 907,
"text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1130,
"s": 1054,
"text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More"
},
{
"code": null,
"e": 1154,
"s": 1130,
"text": "Competitive Programming"
},
{
"code": null,
"e": 1179,
"s": 1154,
"text": "Data Structures with C++"
},
{
"code": null,
"e": 1192,
"s": 1179,
"text": "Data Science"
},
{
"code": null,
"e": 1205,
"s": 1192,
"text": "Explore More"
},
{
"code": null,
"e": 1265,
"s": 1205,
"text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1281,
"s": 1265,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 1285,
"s": 1281,
"text": "CIP"
},
{
"code": null,
"e": 1305,
"s": 1285,
"text": "JAVA / Python / C++"
},
{
"code": null,
"e": 1318,
"s": 1305,
"text": "Explore More"
},
{
"code": null,
"e": 1393,
"s": 1318,
"text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more"
},
{
"code": null,
"e": 1406,
"s": 1393,
"text": "School Guide"
},
{
"code": null,
"e": 1425,
"s": 1406,
"text": "Python Programming"
},
{
"code": null,
"e": 1444,
"s": 1425,
"text": "Learn To Make Apps"
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "Explore more"
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "All Courses"
},
{
"code": null,
"e": 3985,
"s": 1469,
"text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 4566,
"s": 3985,
"text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms"
},
{
"code": null,
"e": 4899,
"s": 4566,
"text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question"
},
{
"code": null,
"e": 4919,
"s": 4899,
"text": "Asymptotic Analysis"
},
{
"code": null,
"e": 4949,
"s": 4919,
"text": "Worst, Average and Best Cases"
},
{
"code": null,
"e": 4970,
"s": 4949,
"text": "Asymptotic Notations"
},
{
"code": null,
"e": 5006,
"s": 4970,
"text": "Little o and little omega notations"
},
{
"code": null,
"e": 5035,
"s": 5006,
"text": "Lower and Upper Bound Theory"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "Analysis of Loops"
},
{
"code": null,
"e": 5073,
"s": 5053,
"text": "Solving Recurrences"
},
{
"code": null,
"e": 5092,
"s": 5073,
"text": "Amortized Analysis"
},
{
"code": null,
"e": 5128,
"s": 5092,
"text": "What does 'Space Complexity' mean ?"
},
{
"code": null,
"e": 5157,
"s": 5128,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 5194,
"s": 5157,
"text": "Polynomial Time Approximation Scheme"
},
{
"code": null,
"e": 5221,
"s": 5194,
"text": "A Time Complexity Question"
},
{
"code": null,
"e": 5242,
"s": 5221,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 5261,
"s": 5242,
"text": "Sorting Algorithms"
},
{
"code": null,
"e": 5278,
"s": 5261,
"text": "Graph Algorithms"
},
{
"code": null,
"e": 5296,
"s": 5278,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5317,
"s": 5296,
"text": "Geometric Algorithms"
},
{
"code": null,
"e": 5330,
"s": 5317,
"text": "Mathematical"
},
{
"code": null,
"e": 5349,
"s": 5330,
"text": "Bitwise Algorithms"
},
{
"code": null,
"e": 5371,
"s": 5349,
"text": "Randomized Algorithms"
},
{
"code": null,
"e": 5389,
"s": 5371,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 5409,
"s": 5389,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5428,
"s": 5409,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5441,
"s": 5428,
"text": "Backtracking"
},
{
"code": null,
"e": 5458,
"s": 5441,
"text": "Branch and Bound"
},
{
"code": null,
"e": 5473,
"s": 5458,
"text": "All Algorithms"
},
{
"code": null,
"e": 5616,
"s": 5473,
"text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures"
},
{
"code": null,
"e": 5623,
"s": 5616,
"text": "Arrays"
},
{
"code": null,
"e": 5635,
"s": 5623,
"text": "Linked List"
},
{
"code": null,
"e": 5641,
"s": 5635,
"text": "Stack"
},
{
"code": null,
"e": 5647,
"s": 5641,
"text": "Queue"
},
{
"code": null,
"e": 5659,
"s": 5647,
"text": "Binary Tree"
},
{
"code": null,
"e": 5678,
"s": 5659,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5683,
"s": 5678,
"text": "Heap"
},
{
"code": null,
"e": 5691,
"s": 5683,
"text": "Hashing"
},
{
"code": null,
"e": 5697,
"s": 5691,
"text": "Graph"
},
{
"code": null,
"e": 5721,
"s": 5697,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5728,
"s": 5721,
"text": "Matrix"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Strings"
},
{
"code": null,
"e": 5756,
"s": 5736,
"text": "All Data Structures"
},
{
"code": null,
"e": 5976,
"s": 5756,
"text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes"
},
{
"code": null,
"e": 5996,
"s": 5976,
"text": "Company Preparation"
},
{
"code": null,
"e": 6007,
"s": 5996,
"text": "Top Topics"
},
{
"code": null,
"e": 6034,
"s": 6007,
"text": "Practice Company Questions"
},
{
"code": null,
"e": 6056,
"s": 6034,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6079,
"s": 6056,
"text": "Experienced Interviews"
},
{
"code": null,
"e": 6101,
"s": 6079,
"text": "Internship Interviews"
},
{
"code": null,
"e": 6126,
"s": 6101,
"text": "Competititve Programming"
},
{
"code": null,
"e": 6142,
"s": 6126,
"text": "Design Patterns"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6189,
"s": 6165,
"text": "Multiple Choice Quizzes"
},
{
"code": null,
"e": 6270,
"s": 6189,
"text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin"
},
{
"code": null,
"e": 6272,
"s": 6270,
"text": "C"
},
{
"code": null,
"e": 6276,
"s": 6272,
"text": "C++"
},
{
"code": null,
"e": 6281,
"s": 6276,
"text": "Java"
},
{
"code": null,
"e": 6288,
"s": 6281,
"text": "Python"
},
{
"code": null,
"e": 6291,
"s": 6288,
"text": "C#"
},
{
"code": null,
"e": 6302,
"s": 6291,
"text": "JavaScript"
},
{
"code": null,
"e": 6309,
"s": 6302,
"text": "jQuery"
},
{
"code": null,
"e": 6313,
"s": 6309,
"text": "SQL"
},
{
"code": null,
"e": 6317,
"s": 6313,
"text": "PHP"
},
{
"code": null,
"e": 6323,
"s": 6317,
"text": "Scala"
},
{
"code": null,
"e": 6328,
"s": 6323,
"text": "Perl"
},
{
"code": null,
"e": 6340,
"s": 6328,
"text": "Go Language"
},
{
"code": null,
"e": 6345,
"s": 6340,
"text": "HTML"
},
{
"code": null,
"e": 6349,
"s": 6345,
"text": "CSS"
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": "Kotlin"
},
{
"code": null,
"e": 6402,
"s": 6356,
"text": "ML & Data ScienceMachine LearningData Science"
},
{
"code": null,
"e": 6419,
"s": 6402,
"text": "Machine Learning"
},
{
"code": null,
"e": 6432,
"s": 6419,
"text": "Data Science"
},
{
"code": null,
"e": 6599,
"s": 6432,
"text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering"
},
{
"code": null,
"e": 6611,
"s": 6599,
"text": "Mathematics"
},
{
"code": null,
"e": 6628,
"s": 6611,
"text": "Operating System"
},
{
"code": null,
"e": 6633,
"s": 6628,
"text": "DBMS"
},
{
"code": null,
"e": 6651,
"s": 6633,
"text": "Computer Networks"
},
{
"code": null,
"e": 6690,
"s": 6651,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 6712,
"s": 6690,
"text": "Theory of Computation"
},
{
"code": null,
"e": 6728,
"s": 6712,
"text": "Compiler Design"
},
{
"code": null,
"e": 6742,
"s": 6728,
"text": "Digital Logic"
},
{
"code": null,
"e": 6763,
"s": 6742,
"text": "Software Engineering"
},
{
"code": null,
"e": 6938,
"s": 6763,
"text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS"
},
{
"code": null,
"e": 6966,
"s": 6938,
"text": "GATE Computer Science Notes"
},
{
"code": null,
"e": 6984,
"s": 6966,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 7006,
"s": 6984,
"text": "GATE CS Solved Papers"
},
{
"code": null,
"e": 7048,
"s": 7006,
"text": "GATE CS Original Papers and Official Keys"
},
{
"code": null,
"e": 7064,
"s": 7048,
"text": "GATE 2021 Dates"
},
{
"code": null,
"e": 7086,
"s": 7064,
"text": "GATE CS 2021 Syllabus"
},
{
"code": null,
"e": 7115,
"s": 7086,
"text": "Important Topics for GATE CS"
},
{
"code": null,
"e": 7189,
"s": 7115,
"text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP"
},
{
"code": null,
"e": 7194,
"s": 7189,
"text": "HTML"
},
{
"code": null,
"e": 7198,
"s": 7194,
"text": "CSS"
},
{
"code": null,
"e": 7209,
"s": 7198,
"text": "JavaScript"
},
{
"code": null,
"e": 7219,
"s": 7209,
"text": "AngularJS"
},
{
"code": null,
"e": 7227,
"s": 7219,
"text": "ReactJS"
},
{
"code": null,
"e": 7234,
"s": 7227,
"text": "NodeJS"
},
{
"code": null,
"e": 7244,
"s": 7234,
"text": "Bootstrap"
},
{
"code": null,
"e": 7251,
"s": 7244,
"text": "jQuery"
},
{
"code": null,
"e": 7255,
"s": 7251,
"text": "PHP"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Software DesignsSoftware Design PatternsSystem Design Tutorial"
},
{
"code": null,
"e": 7343,
"s": 7318,
"text": "Software Design Patterns"
},
{
"code": null,
"e": 7366,
"s": 7343,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 7923,
"s": 7366,
"text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 7942,
"s": 7923,
"text": "School Programming"
},
{
"code": null,
"e": 8034,
"s": 7942,
"text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus"
},
{
"code": null,
"e": 8048,
"s": 8034,
"text": "Number System"
},
{
"code": null,
"e": 8056,
"s": 8048,
"text": "Algebra"
},
{
"code": null,
"e": 8069,
"s": 8056,
"text": "Trigonometry"
},
{
"code": null,
"e": 8080,
"s": 8069,
"text": "Statistics"
},
{
"code": null,
"e": 8092,
"s": 8080,
"text": "Probability"
},
{
"code": null,
"e": 8101,
"s": 8092,
"text": "Geometry"
},
{
"code": null,
"e": 8113,
"s": 8101,
"text": "Mensuration"
},
{
"code": null,
"e": 8122,
"s": 8113,
"text": "Calculus"
},
{
"code": null,
"e": 8215,
"s": 8122,
"text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes"
},
{
"code": null,
"e": 8229,
"s": 8215,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8243,
"s": 8229,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8258,
"s": 8243,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8273,
"s": 8258,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 8288,
"s": 8273,
"text": "Class 12 Notes"
},
{
"code": null,
"e": 8417,
"s": 8288,
"text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8440,
"s": 8417,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8463,
"s": 8440,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8487,
"s": 8463,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8511,
"s": 8487,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8535,
"s": 8511,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8668,
"s": 8535,
"text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8691,
"s": 8668,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8714,
"s": 8691,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8738,
"s": 8714,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8762,
"s": 8738,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8786,
"s": 8762,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8867,
"s": 8786,
"text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 8881,
"s": 8867,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8895,
"s": 8881,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8910,
"s": 8895,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8925,
"s": 8910,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 9131,
"s": 8925,
"text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9242,
"s": 9131,
"text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9284,
"s": 9242,
"text": "ISRO CS Original Papers and Official Keys"
},
{
"code": null,
"e": 9306,
"s": 9284,
"text": "ISRO CS Solved Papers"
},
{
"code": null,
"e": 9351,
"s": 9306,
"text": "ISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9434,
"s": 9351,
"text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9460,
"s": 9434,
"text": "UGC NET CS Notes Paper II"
},
{
"code": null,
"e": 9487,
"s": 9460,
"text": "UGC NET CS Notes Paper III"
},
{
"code": null,
"e": 9512,
"s": 9487,
"text": "UGC NET CS Solved Papers"
},
{
"code": null,
"e": 9717,
"s": 9512,
"text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 9743,
"s": 9717,
"text": "Campus Ambassador Program"
},
{
"code": null,
"e": 9769,
"s": 9743,
"text": "School Ambassador Program"
},
{
"code": null,
"e": 9777,
"s": 9769,
"text": "Project"
},
{
"code": null,
"e": 9795,
"s": 9777,
"text": "Geek of the Month"
},
{
"code": null,
"e": 9820,
"s": 9795,
"text": "Campus Geek of the Month"
},
{
"code": null,
"e": 9837,
"s": 9820,
"text": "Placement Course"
},
{
"code": null,
"e": 9862,
"s": 9837,
"text": "Competititve Programming"
},
{
"code": null,
"e": 9875,
"s": 9862,
"text": "Testimonials"
},
{
"code": null,
"e": 9891,
"s": 9875,
"text": "Student Chapter"
},
{
"code": null,
"e": 9907,
"s": 9891,
"text": "Geek on the Top"
},
{
"code": null,
"e": 9918,
"s": 9907,
"text": "Internship"
},
{
"code": null,
"e": 9926,
"s": 9918,
"text": "Careers"
},
{
"code": null,
"e": 9965,
"s": 9926,
"text": "JobsApply for JobsPost a JobJOB-A-THON"
},
{
"code": null,
"e": 9980,
"s": 9965,
"text": "Apply for Jobs"
},
{
"code": null,
"e": 9991,
"s": 9980,
"text": "Post a Job"
},
{
"code": null,
"e": 10002,
"s": 9991,
"text": "JOB-A-THON"
},
{
"code": null,
"e": 10267,
"s": 10002,
"text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10284,
"s": 10267,
"text": "All DSA Problems"
},
{
"code": null,
"e": 10303,
"s": 10284,
"text": "Problem of the Day"
},
{
"code": null,
"e": 10337,
"s": 10303,
"text": "Interview Series: Weekly Contests"
},
{
"code": null,
"e": 10371,
"s": 10337,
"text": "Bi-Wizard Coding: School Contests"
},
{
"code": null,
"e": 10391,
"s": 10371,
"text": "Contests and Events"
},
{
"code": null,
"e": 10410,
"s": 10391,
"text": "Practice SDE Sheet"
},
{
"code": null,
"e": 10530,
"s": 10410,
"text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10552,
"s": 10530,
"text": "Top 50 Array Problems"
},
{
"code": null,
"e": 10575,
"s": 10552,
"text": "Top 50 String Problems"
},
{
"code": null,
"e": 10596,
"s": 10575,
"text": "Top 50 Tree Problems"
},
{
"code": null,
"e": 10618,
"s": 10596,
"text": "Top 50 Graph Problems"
},
{
"code": null,
"e": 10637,
"s": 10618,
"text": "Top 50 DP Problems"
},
{
"code": null,
"e": 10908,
"s": 10641,
"text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri"
},
{
"code": null,
"e": 10921,
"s": 10908,
"text": "Geeks Digest"
},
{
"code": null,
"e": 10929,
"s": 10921,
"text": "Quizzes"
},
{
"code": null,
"e": 10942,
"s": 10929,
"text": "Geeks Campus"
},
{
"code": null,
"e": 10957,
"s": 10942,
"text": "Gblog Articles"
},
{
"code": null,
"e": 10961,
"s": 10957,
"text": "IDE"
},
{
"code": null,
"e": 10975,
"s": 10961,
"text": "Campus Mantri"
},
{
"code": null,
"e": 10983,
"s": 10975,
"text": "Sign In"
},
{
"code": null,
"e": 10991,
"s": 10983,
"text": "Sign In"
},
{
"code": null,
"e": 10996,
"s": 10991,
"text": "Home"
},
{
"code": null,
"e": 11009,
"s": 10996,
"text": "Saved Videos"
},
{
"code": null,
"e": 11017,
"s": 11009,
"text": "Courses"
},
{
"code": null,
"e": 15482,
"s": 11017,
"text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 15536,
"s": 15482,
"text": "\nFor Working Professionals\n \n\n"
},
{
"code": null,
"e": 15659,
"s": 15536,
"text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n"
},
{
"code": null,
"e": 15678,
"s": 15659,
"text": "\nDSA Live Classes\n"
},
{
"code": null,
"e": 15694,
"s": 15678,
"text": "\nSystem Design\n"
},
{
"code": null,
"e": 15721,
"s": 15694,
"text": "\nJava Backend Development\n"
},
{
"code": null,
"e": 15739,
"s": 15721,
"text": "\nFull Stack LIVE\n"
},
{
"code": null,
"e": 15754,
"s": 15739,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15862,
"s": 15754,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n"
},
{
"code": null,
"e": 15880,
"s": 15862,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 15893,
"s": 15880,
"text": "\nSDE Theory\n"
},
{
"code": null,
"e": 15920,
"s": 15893,
"text": "\nMust-Do Coding Questions\n"
},
{
"code": null,
"e": 15935,
"s": 15920,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15976,
"s": 15935,
"text": "\nFor Students\n \n\n"
},
{
"code": null,
"e": 16088,
"s": 15976,
"text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n"
},
{
"code": null,
"e": 16114,
"s": 16088,
"text": "\nCompetitive Programming\n"
},
{
"code": null,
"e": 16141,
"s": 16114,
"text": "\nData Structures with C++\n"
},
{
"code": null,
"e": 16156,
"s": 16141,
"text": "\nData Science\n"
},
{
"code": null,
"e": 16171,
"s": 16156,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16267,
"s": 16171,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n"
},
{
"code": null,
"e": 16285,
"s": 16267,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 16291,
"s": 16285,
"text": "\nCIP\n"
},
{
"code": null,
"e": 16313,
"s": 16291,
"text": "\nJAVA / Python / C++\n"
},
{
"code": null,
"e": 16328,
"s": 16313,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16439,
"s": 16328,
"text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n"
},
{
"code": null,
"e": 16454,
"s": 16439,
"text": "\nSchool Guide\n"
},
{
"code": null,
"e": 16475,
"s": 16454,
"text": "\nPython Programming\n"
},
{
"code": null,
"e": 16496,
"s": 16475,
"text": "\nLearn To Make Apps\n"
},
{
"code": null,
"e": 16511,
"s": 16496,
"text": "\nExplore more\n"
},
{
"code": null,
"e": 16816,
"s": 16511,
"text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n"
},
{
"code": null,
"e": 16839,
"s": 16816,
"text": "\nSearching Algorithms\n"
},
{
"code": null,
"e": 16860,
"s": 16839,
"text": "\nSorting Algorithms\n"
},
{
"code": null,
"e": 16879,
"s": 16860,
"text": "\nGraph Algorithms\n"
},
{
"code": null,
"e": 16899,
"s": 16879,
"text": "\nPattern Searching\n"
},
{
"code": null,
"e": 16922,
"s": 16899,
"text": "\nGeometric Algorithms\n"
},
{
"code": null,
"e": 16937,
"s": 16922,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 16958,
"s": 16937,
"text": "\nBitwise Algorithms\n"
},
{
"code": null,
"e": 16982,
"s": 16958,
"text": "\nRandomized Algorithms\n"
},
{
"code": null,
"e": 17002,
"s": 16982,
"text": "\nGreedy Algorithms\n"
},
{
"code": null,
"e": 17024,
"s": 17002,
"text": "\nDynamic Programming\n"
},
{
"code": null,
"e": 17045,
"s": 17024,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 17060,
"s": 17045,
"text": "\nBacktracking\n"
},
{
"code": null,
"e": 17079,
"s": 17060,
"text": "\nBranch and Bound\n"
},
{
"code": null,
"e": 17096,
"s": 17079,
"text": "\nAll Algorithms\n"
},
{
"code": null,
"e": 17481,
"s": 17096,
"text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n"
},
{
"code": null,
"e": 17503,
"s": 17481,
"text": "\nAsymptotic Analysis\n"
},
{
"code": null,
"e": 17535,
"s": 17503,
"text": "\nWorst, Average and Best Cases\n"
},
{
"code": null,
"e": 17558,
"s": 17535,
"text": "\nAsymptotic Notations\n"
},
{
"code": null,
"e": 17596,
"s": 17558,
"text": "\nLittle o and little omega notations\n"
},
{
"code": null,
"e": 17627,
"s": 17596,
"text": "\nLower and Upper Bound Theory\n"
},
{
"code": null,
"e": 17647,
"s": 17627,
"text": "\nAnalysis of Loops\n"
},
{
"code": null,
"e": 17669,
"s": 17647,
"text": "\nSolving Recurrences\n"
},
{
"code": null,
"e": 17690,
"s": 17669,
"text": "\nAmortized Analysis\n"
},
{
"code": null,
"e": 17728,
"s": 17690,
"text": "\nWhat does 'Space Complexity' mean ?\n"
},
{
"code": null,
"e": 17759,
"s": 17728,
"text": "\nPseudo-polynomial Algorithms\n"
},
{
"code": null,
"e": 17798,
"s": 17759,
"text": "\nPolynomial Time Approximation Scheme\n"
},
{
"code": null,
"e": 17827,
"s": 17798,
"text": "\nA Time Complexity Question\n"
},
{
"code": null,
"e": 18024,
"s": 17827,
"text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n"
},
{
"code": null,
"e": 18033,
"s": 18024,
"text": "\nArrays\n"
},
{
"code": null,
"e": 18047,
"s": 18033,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 18055,
"s": 18047,
"text": "\nStack\n"
},
{
"code": null,
"e": 18063,
"s": 18055,
"text": "\nQueue\n"
},
{
"code": null,
"e": 18077,
"s": 18063,
"text": "\nBinary Tree\n"
},
{
"code": null,
"e": 18098,
"s": 18077,
"text": "\nBinary Search Tree\n"
},
{
"code": null,
"e": 18105,
"s": 18098,
"text": "\nHeap\n"
},
{
"code": null,
"e": 18115,
"s": 18105,
"text": "\nHashing\n"
},
{
"code": null,
"e": 18123,
"s": 18115,
"text": "\nGraph\n"
},
{
"code": null,
"e": 18149,
"s": 18123,
"text": "\nAdvanced Data Structure\n"
},
{
"code": null,
"e": 18158,
"s": 18149,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 18168,
"s": 18158,
"text": "\nStrings\n"
},
{
"code": null,
"e": 18190,
"s": 18168,
"text": "\nAll Data Structures\n"
},
{
"code": null,
"e": 18458,
"s": 18190,
"text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18480,
"s": 18458,
"text": "\nCompany Preparation\n"
},
{
"code": null,
"e": 18493,
"s": 18480,
"text": "\nTop Topics\n"
},
{
"code": null,
"e": 18522,
"s": 18493,
"text": "\nPractice Company Questions\n"
},
{
"code": null,
"e": 18546,
"s": 18522,
"text": "\nInterview Experiences\n"
},
{
"code": null,
"e": 18571,
"s": 18546,
"text": "\nExperienced Interviews\n"
},
{
"code": null,
"e": 18595,
"s": 18571,
"text": "\nInternship Interviews\n"
},
{
"code": null,
"e": 18622,
"s": 18595,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 18640,
"s": 18622,
"text": "\nDesign Patterns\n"
},
{
"code": null,
"e": 18665,
"s": 18640,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 18691,
"s": 18665,
"text": "\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18830,
"s": 18691,
"text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n"
},
{
"code": null,
"e": 18834,
"s": 18830,
"text": "\nC\n"
},
{
"code": null,
"e": 18840,
"s": 18834,
"text": "\nC++\n"
},
{
"code": null,
"e": 18847,
"s": 18840,
"text": "\nJava\n"
},
{
"code": null,
"e": 18856,
"s": 18847,
"text": "\nPython\n"
},
{
"code": null,
"e": 18861,
"s": 18856,
"text": "\nC#\n"
},
{
"code": null,
"e": 18874,
"s": 18861,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 18883,
"s": 18874,
"text": "\njQuery\n"
},
{
"code": null,
"e": 18889,
"s": 18883,
"text": "\nSQL\n"
},
{
"code": null,
"e": 18895,
"s": 18889,
"text": "\nPHP\n"
},
{
"code": null,
"e": 18903,
"s": 18895,
"text": "\nScala\n"
},
{
"code": null,
"e": 18910,
"s": 18903,
"text": "\nPerl\n"
},
{
"code": null,
"e": 18924,
"s": 18910,
"text": "\nGo Language\n"
},
{
"code": null,
"e": 18931,
"s": 18924,
"text": "\nHTML\n"
},
{
"code": null,
"e": 18937,
"s": 18931,
"text": "\nCSS\n"
},
{
"code": null,
"e": 18946,
"s": 18937,
"text": "\nKotlin\n"
},
{
"code": null,
"e": 19024,
"s": 18946,
"text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n"
},
{
"code": null,
"e": 19043,
"s": 19024,
"text": "\nMachine Learning\n"
},
{
"code": null,
"e": 19058,
"s": 19043,
"text": "\nData Science\n"
},
{
"code": null,
"e": 19271,
"s": 19058,
"text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n"
},
{
"code": null,
"e": 19285,
"s": 19271,
"text": "\nMathematics\n"
},
{
"code": null,
"e": 19304,
"s": 19285,
"text": "\nOperating System\n"
},
{
"code": null,
"e": 19311,
"s": 19304,
"text": "\nDBMS\n"
},
{
"code": null,
"e": 19331,
"s": 19311,
"text": "\nComputer Networks\n"
},
{
"code": null,
"e": 19372,
"s": 19331,
"text": "\nComputer Organization and Architecture\n"
},
{
"code": null,
"e": 19396,
"s": 19372,
"text": "\nTheory of Computation\n"
},
{
"code": null,
"e": 19414,
"s": 19396,
"text": "\nCompiler Design\n"
},
{
"code": null,
"e": 19430,
"s": 19414,
"text": "\nDigital Logic\n"
},
{
"code": null,
"e": 19453,
"s": 19430,
"text": "\nSoftware Engineering\n"
},
{
"code": null,
"e": 19670,
"s": 19453,
"text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19700,
"s": 19670,
"text": "\nGATE Computer Science Notes\n"
},
{
"code": null,
"e": 19720,
"s": 19700,
"text": "\nLast Minute Notes\n"
},
{
"code": null,
"e": 19744,
"s": 19720,
"text": "\nGATE CS Solved Papers\n"
},
{
"code": null,
"e": 19788,
"s": 19744,
"text": "\nGATE CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 19806,
"s": 19788,
"text": "\nGATE 2021 Dates\n"
},
{
"code": null,
"e": 19830,
"s": 19806,
"text": "\nGATE CS 2021 Syllabus\n"
},
{
"code": null,
"e": 19861,
"s": 19830,
"text": "\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19981,
"s": 19861,
"text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n"
},
{
"code": null,
"e": 19988,
"s": 19981,
"text": "\nHTML\n"
},
{
"code": null,
"e": 19994,
"s": 19988,
"text": "\nCSS\n"
},
{
"code": null,
"e": 20007,
"s": 19994,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 20019,
"s": 20007,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 20029,
"s": 20019,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 20038,
"s": 20029,
"text": "\nNodeJS\n"
},
{
"code": null,
"e": 20050,
"s": 20038,
"text": "\nBootstrap\n"
},
{
"code": null,
"e": 20059,
"s": 20050,
"text": "\njQuery\n"
},
{
"code": null,
"e": 20065,
"s": 20059,
"text": "\nPHP\n"
},
{
"code": null,
"e": 20160,
"s": 20065,
"text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20187,
"s": 20160,
"text": "\nSoftware Design Patterns\n"
},
{
"code": null,
"e": 20212,
"s": 20187,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20276,
"s": 20212,
"text": "\nSchool Learning\n \n\n\nSchool Programming\n"
},
{
"code": null,
"e": 20297,
"s": 20276,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 20433,
"s": 20297,
"text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n"
},
{
"code": null,
"e": 20449,
"s": 20433,
"text": "\nNumber System\n"
},
{
"code": null,
"e": 20459,
"s": 20449,
"text": "\nAlgebra\n"
},
{
"code": null,
"e": 20474,
"s": 20459,
"text": "\nTrigonometry\n"
},
{
"code": null,
"e": 20487,
"s": 20474,
"text": "\nStatistics\n"
},
{
"code": null,
"e": 20501,
"s": 20487,
"text": "\nProbability\n"
},
{
"code": null,
"e": 20512,
"s": 20501,
"text": "\nGeometry\n"
},
{
"code": null,
"e": 20526,
"s": 20512,
"text": "\nMensuration\n"
},
{
"code": null,
"e": 20537,
"s": 20526,
"text": "\nCalculus\n"
},
{
"code": null,
"e": 20668,
"s": 20537,
"text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n"
},
{
"code": null,
"e": 20684,
"s": 20668,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 20700,
"s": 20684,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 20717,
"s": 20700,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 20734,
"s": 20717,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 20751,
"s": 20734,
"text": "\nClass 12 Notes\n"
},
{
"code": null,
"e": 20918,
"s": 20751,
"text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20943,
"s": 20918,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 20968,
"s": 20943,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20994,
"s": 20968,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21020,
"s": 20994,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21046,
"s": 21020,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21217,
"s": 21046,
"text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21242,
"s": 21217,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 21267,
"s": 21242,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 21293,
"s": 21267,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21319,
"s": 21293,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21345,
"s": 21319,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21462,
"s": 21345,
"text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n"
},
{
"code": null,
"e": 21478,
"s": 21462,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 21494,
"s": 21478,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 21511,
"s": 21494,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 21528,
"s": 21511,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 21570,
"s": 21528,
"text": "\nCS Exams/PSUs\n \n\n"
},
{
"code": null,
"e": 21715,
"s": 21570,
"text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21759,
"s": 21715,
"text": "\nISRO CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 21783,
"s": 21759,
"text": "\nISRO CS Solved Papers\n"
},
{
"code": null,
"e": 21830,
"s": 21783,
"text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21947,
"s": 21830,
"text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 21975,
"s": 21947,
"text": "\nUGC NET CS Notes Paper II\n"
},
{
"code": null,
"e": 22004,
"s": 21975,
"text": "\nUGC NET CS Notes Paper III\n"
},
{
"code": null,
"e": 22031,
"s": 22004,
"text": "\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 22288,
"s": 22031,
"text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n"
},
{
"code": null,
"e": 22316,
"s": 22288,
"text": "\nCampus Ambassador Program\n"
},
{
"code": null,
"e": 22344,
"s": 22316,
"text": "\nSchool Ambassador Program\n"
},
{
"code": null,
"e": 22354,
"s": 22344,
"text": "\nProject\n"
},
{
"code": null,
"e": 22374,
"s": 22354,
"text": "\nGeek of the Month\n"
},
{
"code": null,
"e": 22401,
"s": 22374,
"text": "\nCampus Geek of the Month\n"
},
{
"code": null,
"e": 22420,
"s": 22401,
"text": "\nPlacement Course\n"
},
{
"code": null,
"e": 22447,
"s": 22420,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 22462,
"s": 22447,
"text": "\nTestimonials\n"
},
{
"code": null,
"e": 22480,
"s": 22462,
"text": "\nStudent Chapter\n"
},
{
"code": null,
"e": 22498,
"s": 22480,
"text": "\nGeek on the Top\n"
},
{
"code": null,
"e": 22511,
"s": 22498,
"text": "\nInternship\n"
},
{
"code": null,
"e": 22521,
"s": 22511,
"text": "\nCareers\n"
},
{
"code": null,
"e": 22679,
"s": 22521,
"text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22703,
"s": 22679,
"text": "\nTop 50 Array Problems\n"
},
{
"code": null,
"e": 22728,
"s": 22703,
"text": "\nTop 50 String Problems\n"
},
{
"code": null,
"e": 22751,
"s": 22728,
"text": "\nTop 50 Tree Problems\n"
},
{
"code": null,
"e": 22775,
"s": 22751,
"text": "\nTop 50 Graph Problems\n"
},
{
"code": null,
"e": 22796,
"s": 22775,
"text": "\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22834,
"s": 22796,
"text": "\nTutorials\n \n\n"
},
{
"code": null,
"e": 22907,
"s": 22834,
"text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 22924,
"s": 22907,
"text": "\nApply for Jobs\n"
},
{
"code": null,
"e": 22937,
"s": 22924,
"text": "\nPost a Job\n"
},
{
"code": null,
"e": 22950,
"s": 22937,
"text": "\nJOB-A-THON\n"
},
{
"code": null,
"e": 23136,
"s": 22950,
"text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23155,
"s": 23136,
"text": "\nAll DSA Problems\n"
},
{
"code": null,
"e": 23176,
"s": 23155,
"text": "\nProblem of the Day\n"
},
{
"code": null,
"e": 23212,
"s": 23176,
"text": "\nInterview Series: Weekly Contests\n"
},
{
"code": null,
"e": 23248,
"s": 23212,
"text": "\nBi-Wizard Coding: School Contests\n"
},
{
"code": null,
"e": 23270,
"s": 23248,
"text": "\nContests and Events\n"
},
{
"code": null,
"e": 23291,
"s": 23270,
"text": "\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23297,
"s": 23291,
"text": "GBlog"
},
{
"code": null,
"e": 23305,
"s": 23297,
"text": "Puzzles"
},
{
"code": null,
"e": 23318,
"s": 23305,
"text": "What's New ?"
},
{
"code": null,
"e": 23324,
"s": 23318,
"text": "Array"
},
{
"code": null,
"e": 23331,
"s": 23324,
"text": "Matrix"
},
{
"code": null,
"e": 23339,
"s": 23331,
"text": "Strings"
},
{
"code": null,
"e": 23347,
"s": 23339,
"text": "Hashing"
},
{
"code": null,
"e": 23359,
"s": 23347,
"text": "Linked List"
},
{
"code": null,
"e": 23365,
"s": 23359,
"text": "Stack"
},
{
"code": null,
"e": 23371,
"s": 23365,
"text": "Queue"
},
{
"code": null,
"e": 23383,
"s": 23371,
"text": "Binary Tree"
},
{
"code": null,
"e": 23402,
"s": 23383,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 23407,
"s": 23402,
"text": "Heap"
},
{
"code": null,
"e": 23413,
"s": 23407,
"text": "Graph"
},
{
"code": null,
"e": 23423,
"s": 23413,
"text": "Searching"
},
{
"code": null,
"e": 23431,
"s": 23423,
"text": "Sorting"
},
{
"code": null,
"e": 23448,
"s": 23431,
"text": "Divide & Conquer"
},
{
"code": null,
"e": 23461,
"s": 23448,
"text": "Mathematical"
},
{
"code": null,
"e": 23471,
"s": 23461,
"text": "Geometric"
},
{
"code": null,
"e": 23479,
"s": 23471,
"text": "Bitwise"
},
{
"code": null,
"e": 23486,
"s": 23479,
"text": "Greedy"
},
{
"code": null,
"e": 23499,
"s": 23486,
"text": "Backtracking"
},
{
"code": null,
"e": 23516,
"s": 23499,
"text": "Branch and Bound"
},
{
"code": null,
"e": 23536,
"s": 23516,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23554,
"s": 23536,
"text": "Pattern Searching"
},
{
"code": null,
"e": 23565,
"s": 23554,
"text": "Randomized"
},
{
"code": null,
"e": 23600,
"s": 23565,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 23639,
"s": 23600,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 23661,
"s": 23639,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 23709,
"s": 23661,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 23747,
"s": 23709,
"text": "Linked List | Set 3 (Deleting a node)"
},
{
"code": null,
"e": 23803,
"s": 23747,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 23822,
"s": 23803,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 23851,
"s": 23822,
"text": "Detect loop in a linked list"
},
{
"code": null,
"e": 23872,
"s": 23851,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 23911,
"s": 23872,
"text": "Find the middle of a given linked list"
},
{
"code": null,
"e": 23941,
"s": 23911,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 23984,
"s": 23941,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 24019,
"s": 23984,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 24065,
"s": 24019,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 24093,
"s": 24065,
"text": "Merge Sort for Linked Lists"
},
{
"code": null,
"e": 24140,
"s": 24093,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 24196,
"s": 24140,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 24251,
"s": 24196,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 24291,
"s": 24251,
"text": "Detect and Remove Loop in a Linked List"
},
{
"code": null,
"e": 24352,
"s": 24291,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 24406,
"s": 24352,
"text": "Reverse a Linked List in groups of given size | Set 1"
},
{
"code": null,
"e": 24467,
"s": 24406,
"text": "Search an element in a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 24519,
"s": 24467,
"text": "Program for n'th node from the end of a Linked List"
},
{
"code": null,
"e": 24560,
"s": 24519,
"text": "Write a function to delete a Linked List"
},
{
"code": null,
"e": 24627,
"s": 24560,
"text": "Write a function to get the intersection point of two Linked Lists"
},
{
"code": null,
"e": 24671,
"s": 24627,
"text": "Remove duplicates from a sorted linked list"
},
{
"code": null,
"e": 24709,
"s": 24671,
"text": "Top 20 Linked List Interview Question"
},
{
"code": null,
"e": 24761,
"s": 24709,
"text": "Add two numbers represented by linked lists | Set 1"
},
{
"code": null,
"e": 24808,
"s": 24761,
"text": "Remove duplicates from an unsorted linked list"
},
{
"code": null,
"e": 24858,
"s": 24808,
"text": "Write a function to get Nth node in a Linked List"
},
{
"code": null,
"e": 24893,
"s": 24858,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 24932,
"s": 24893,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 24954,
"s": 24932,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 25002,
"s": 24954,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 25040,
"s": 25002,
"text": "Linked List | Set 3 (Deleting a node)"
},
{
"code": null,
"e": 25096,
"s": 25040,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 25115,
"s": 25096,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 25144,
"s": 25115,
"text": "Detect loop in a linked list"
},
{
"code": null,
"e": 25165,
"s": 25144,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 25204,
"s": 25165,
"text": "Find the middle of a given linked list"
},
{
"code": null,
"e": 25234,
"s": 25204,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 25277,
"s": 25234,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 25312,
"s": 25277,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 25358,
"s": 25312,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 25386,
"s": 25358,
"text": "Merge Sort for Linked Lists"
},
{
"code": null,
"e": 25433,
"s": 25386,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 25489,
"s": 25433,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 25544,
"s": 25489,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 25584,
"s": 25544,
"text": "Detect and Remove Loop in a Linked List"
},
{
"code": null,
"e": 25645,
"s": 25584,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 25699,
"s": 25645,
"text": "Reverse a Linked List in groups of given size | Set 1"
},
{
"code": null,
"e": 25760,
"s": 25699,
"text": "Search an element in a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 25812,
"s": 25760,
"text": "Program for n'th node from the end of a Linked List"
},
{
"code": null,
"e": 25853,
"s": 25812,
"text": "Write a function to delete a Linked List"
},
{
"code": null,
"e": 25920,
"s": 25853,
"text": "Write a function to get the intersection point of two Linked Lists"
},
{
"code": null,
"e": 25964,
"s": 25920,
"text": "Remove duplicates from a sorted linked list"
},
{
"code": null,
"e": 26002,
"s": 25964,
"text": "Top 20 Linked List Interview Question"
},
{
"code": null,
"e": 26054,
"s": 26002,
"text": "Add two numbers represented by linked lists | Set 1"
},
{
"code": null,
"e": 26101,
"s": 26054,
"text": "Remove duplicates from an unsorted linked list"
},
{
"code": null,
"e": 26151,
"s": 26101,
"text": "Write a function to get Nth node in a Linked List"
},
{
"code": null,
"e": 26175,
"s": 26151,
"text": "Difficulty Level :\nEasy"
},
{
"code": null,
"e": 26305,
"s": 26175,
"text": "Given a Linked List, display the linked list in reverse without using recursion, stack or modifications to given list.Examples: "
},
{
"code": null,
"e": 26425,
"s": 26305,
"text": "Input : 1->2->3->4->5->NULL\nOutput :5->4->3->2->1->NULL\n\nInput :10->5->15->20->24->NULL\nOutput :24->20->15->5->10->NULL"
},
{
"code": null,
"e": 26874,
"s": 26427,
"text": "Below are different solutions that are now allowed here as we cannot use extra space and modify list.1) Recursive solution to print reverse a linked list. Requires extra space.2) Reverse linked list and then print. This requires modifications to original list. 3) Stack based solution to print linked list reverse. Push all nodes one by one to a stack. Then one by one pop elements from stack and print. This also requires extra space.Algorithms:"
},
{
"code": null,
"e": 26996,
"s": 26874,
"text": "1) Find n = count nodes in linked list.\n2) For i = n to 1, do following.\n Print i-th node using get n-th node function"
},
{
"code": null,
"e": 27000,
"s": 26996,
"text": "C++"
},
{
"code": null,
"e": 27005,
"s": 27000,
"text": "Java"
},
{
"code": null,
"e": 27013,
"s": 27005,
"text": "Python3"
},
{
"code": null,
"e": 27016,
"s": 27013,
"text": "C#"
},
{
"code": null,
"e": 27027,
"s": 27016,
"text": "Javascript"
},
{
"code": "// C/C++ program to print reverse of linked list// without extra space and without modifications.#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Counts no. of nodes in linked list */int getCount(struct Node* head){ int count = 0; // Initialize count struct Node* current = head; // Initialize current while (current != NULL) { count++; current = current->next; } return count;} /* Takes head pointer of the linked list and index as arguments and return data at index*/int getNth(struct Node* head, int n){ struct Node* curr = head; for (int i=0; i<n-1 && curr != NULL; i++) curr = curr->next; return curr->data;} void printReverse(Node *head){ // Count nodes int n = getCount(head); for (int i=n; i>=1; i--) printf(\"%d \", getNth(head, i));} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printReverse(head); return 0;}",
"e": 28561,
"s": 27027,
"text": null
},
{
"code": "// Java program to print reverse of linked list// without extra space and without modifications.class GFG{ /* Link list node */static class Node{ int data; Node next;};static Node head; /* Given a reference (pointer to pointer) tothe head of a list and an int, push a new nodeon the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; head = head_ref;} /* Counts no. of nodes in linked list */static int getCount(Node head){ int count = 0; // Initialize count Node current = head; // Initialize current while (current != null) { count++; current = current.next; } return count;} /* Takes head pointer of the linked list andindex as arguments and return data at index*/static int getNth(Node head, int n){ Node curr = head; for (int i = 0; i < n - 1 && curr != null; i++) curr = curr.next; return curr.data;} static void printReverse(){ // Count nodes int n = getCount(head); for (int i = n; i >= 1; i--) System.out.printf(\"%d \", getNth(head, i));} // Driver Codepublic static void main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct below list 1->2->3->4->5 */ push(head, 5); push(head, 4); push(head, 3); push(head, 2); push(head, 1); printReverse();}} // This code is contributed by PrinciRaj1992",
"e": 30040,
"s": 28561,
"text": null
},
{
"code": "# Python3 program to print reverse of linked list# without extra space and without modifications. ''' Link list node '''class Node: def __init__(self, data): self.data = data self.next = None ''' Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. '''def push( head_ref, new_data): new_node = Node(new_data) new_node.next = head_ref; head_ref = new_node; return head_ref ''' Counts no. of nodes in linked list '''def getCount(head): count = 0; # Initialize count current = head; # Initialize current while (current != None): count += 1 current = current.next; return count; ''' Takes head pointer of the linked list and index as arguments and return data at index'''def getNth(head, n): curr = head; i = 0 while i < n - 1 and curr != None: curr = curr.next; i += 1 return curr.data; def printReverse(head): # Count nodes n = getCount(head); for i in range(n, 0, -1): print(getNth(head, i), end = ' '); # Driver codeif __name__=='__main__': ''' Start with the empty list ''' head = None; ''' Use push() to construct below list 1.2.3.4.5 ''' head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); printReverse(head); # This code is contributed by rutvik_56",
"e": 31506,
"s": 30040,
"text": null
},
{
"code": "// C# program to print reverse of// linked list without extra space// and without modifications.using System; class GFG{ /* Link list node */public class Node{ public int data; public Node next;};static Node head; /* Given a reference (pointer to pointer)to the head of a list and an int, push anew node on the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; head = head_ref;} /* Counts no. of nodes in linked list */static int getCount(Node head){ int count = 0; // Initialize count Node current = head; // Initialize current while (current != null) { count++; current = current.next; } return count;} /* Takes head pointer of the linked list andindex as arguments and return data at index*/static int getNth(Node head, int n){ Node curr = head; for (int i = 0; i < n - 1 && curr != null; i++) curr = curr.next; return curr.data;} static void printReverse(){ // Count nodes int n = getCount(head); for (int i = n; i >= 1; i--) Console.Write(\"{0} \", getNth(head, i));} // Driver Codepublic static void Main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct below list 1->2->3->4->5 */ push(head, 5); push(head, 4); push(head, 3); push(head, 2); push(head, 1); printReverse();}} // This code is contributed by Princi Singh",
"e": 33041,
"s": 31506,
"text": null
},
{
"code": "<script> // JavaScript program to implement above approach // Link list nodeclass Node{ constructor(data){ this.data = data this.next = null }} // Given a reference (pointer to pointer) to the head// of a list and an int, push a new node on the front// of the list. function push( head_ref, new_data){ let new_node = new Node(new_data) new_node.next = head_ref; head_ref = new_node; return head_ref} // Counts no. of nodes in linked list function getCount(head){ let count = 0; // Initialize count let current = head; // Initialize current while (current != null){ count += 1 current = current.next; } return count;} // Takes head pointer of the linked list and index// as arguments and return data at index function getNth(head, n){ let curr = head; let i = 0 while(i < n - 1 && curr != null){ curr = curr.next; i += 1 } return curr.data;} function printReverse(head){ // Count nodes let n = getCount(head); for(let i=n;i>0;i--) document.write(getNth(head, i),' ');} // Driver code // Start with the empty listlet head = null; // Use push() to construct below list// 1.2.3.4.5head = push(head, 5);head = push(head, 4);head = push(head, 3);head = push(head, 2);head = push(head, 1); printReverse(head); // This code is contributed by shinjanpatra </script>",
"e": 34435,
"s": 33041,
"text": null
},
{
"code": null,
"e": 34445,
"s": 34435,
"text": "Output: "
},
{
"code": null,
"e": 34455,
"s": 34445,
"text": "5 4 3 2 1"
},
{
"code": null,
"e": 34471,
"s": 34457,
"text": "princiraj1992"
},
{
"code": null,
"e": 34484,
"s": 34471,
"text": "princi singh"
},
{
"code": null,
"e": 34495,
"s": 34484,
"text": "nidhi_biet"
},
{
"code": null,
"e": 34505,
"s": 34495,
"text": "rutvik_56"
},
{
"code": null,
"e": 34518,
"s": 34505,
"text": "simmytarika5"
},
{
"code": null,
"e": 34531,
"s": 34518,
"text": "shinjanpatra"
},
{
"code": null,
"e": 34550,
"s": 34531,
"text": "programming-puzzle"
},
{
"code": null,
"e": 34562,
"s": 34550,
"text": "Linked List"
},
{
"code": null,
"e": 34574,
"s": 34562,
"text": "Linked List"
},
{
"code": null,
"e": 34672,
"s": 34574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34713,
"s": 34672,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 34763,
"s": 34713,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 34822,
"s": 34763,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 34862,
"s": 34822,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 34933,
"s": 34862,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 34971,
"s": 34933,
"text": "Delete a node in a Doubly Linked List"
},
{
"code": null,
"e": 35012,
"s": 34971,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 35045,
"s": 35012,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 35099,
"s": 35045,
"text": "Insert a node at a specific position in a linked list"
}
] |
C# Program to Print Employees Whose Salary is Greater than Average of all Employees Salaries Using LINQ - GeeksforGeeks | 16 Oct, 2021
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to display a list of those employees’ details whose salary is greater than the average of all employee salaries.
Example:
Input:
{{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199},
{emp_Name = "ramya", emp_Age = 22, emp_Salary = 19000},
{emp_Name = "harsha", emp_Age = 23, emp_Salary = 25000},
{emp_Name = "deepu", emp_Age = 23, emp_Salary = 23456},
{emp_Name = "jyothika", emp_Age = 21, emp_Salary = 21345}}
Output:
{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199}
{emp_Name = "harsha", emp_Age = 23, emp_Salary = 25000}
{emp_Name = "deepu", emp_Age = 23, emp_Salary = 23456}
Input:
{{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199},
{emp_Name = "ramya", emp_Age = 22, emp_Salary = 19000}}
Output:
{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199}
Approach:
Declare three variables- employee name, age, and salaryCreate a list of employees using list collection.Using Query compute the average salary of all the employees.Using where clause check each employee salary which is greater than average value.Select that employees.Display the result using ToString() method.
Declare three variables- employee name, age, and salary
Create a list of employees using list collection.
Using Query compute the average salary of all the employees.
Using where clause check each employee salary which is greater than average value.
Select that employees.
Display the result using ToString() method.
Example:
C#
// C# program to display the lits of employees // whose salary is greater than average salary // of all the employeesusing System;using System.Collections.Generic;using System.Linq; class Employee{ // Declare three variables// employee name, age, and Salarystring emp_Name;int emp_Age;int emp_Salary; // Get the datapublic override string ToString(){ return " " + emp_Name + " " + emp_Age + " " + emp_Salary;} // Driver codestatic void Main(string[] args){ // Create the list of 5 employees List<Employee> emp = new List<Employee>() { new Employee{ emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199 }, new Employee{ emp_Name = "ramya", emp_Age = 22, emp_Salary = 19000 }, new Employee{ emp_Name = "harsha", emp_Age = 23, emp_Salary = 25000 }, new Employee{ emp_Name = "deepu", emp_Age = 23, emp_Salary = 23456 }, new Employee{ emp_Name = "jyothika", emp_Age = 21, emp_Salary = 21345 } }; IEnumerable<Employee> result = // Getting the average of all the employees from e in emp // Total let total = emp.Sum(sal => sal.emp_Salary) let average = total / 5 // Condition to get salary greater than // average of all employees where e.emp_Salary > average // Select that employees select e; Console.WriteLine(" Employee-Name Employee-Age Employee-Salary"); foreach (Employee x in result) { Console.WriteLine(x.ToString()); }}}
Output:
Employee-Name Employee-Age Employee-Salary
sravan 21 26199
harsha 23 25000
deepu 23 23456
CSharp LINQ
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C# | [
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 26033,
"s": 25547,
"text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to display a list of those employees’ details whose salary is greater than the average of all employee salaries."
},
{
"code": null,
"e": 26042,
"s": 26033,
"text": "Example:"
},
{
"code": null,
"e": 26705,
"s": 26042,
"text": "Input:\n{{emp_Name = \"sravan\", emp_Age = 21, emp_Salary = 26199},\n {emp_Name = \"ramya\", emp_Age = 22, emp_Salary = 19000},\n {emp_Name = \"harsha\", emp_Age = 23, emp_Salary = 25000},\n {emp_Name = \"deepu\", emp_Age = 23, emp_Salary = 23456},\n {emp_Name = \"jyothika\", emp_Age = 21, emp_Salary = 21345}}\nOutput:\n {emp_Name = \"sravan\", emp_Age = 21, emp_Salary = 26199}\n {emp_Name = \"harsha\", emp_Age = 23, emp_Salary = 25000}\n {emp_Name = \"deepu\", emp_Age = 23, emp_Salary = 23456}\n \nInput:\n{{emp_Name = \"sravan\", emp_Age = 21, emp_Salary = 26199},\n {emp_Name = \"ramya\", emp_Age = 22, emp_Salary = 19000}}\nOutput:\n{emp_Name = \"sravan\", emp_Age = 21, emp_Salary = 26199}"
},
{
"code": null,
"e": 26715,
"s": 26705,
"text": "Approach:"
},
{
"code": null,
"e": 27027,
"s": 26715,
"text": "Declare three variables- employee name, age, and salaryCreate a list of employees using list collection.Using Query compute the average salary of all the employees.Using where clause check each employee salary which is greater than average value.Select that employees.Display the result using ToString() method."
},
{
"code": null,
"e": 27083,
"s": 27027,
"text": "Declare three variables- employee name, age, and salary"
},
{
"code": null,
"e": 27133,
"s": 27083,
"text": "Create a list of employees using list collection."
},
{
"code": null,
"e": 27194,
"s": 27133,
"text": "Using Query compute the average salary of all the employees."
},
{
"code": null,
"e": 27277,
"s": 27194,
"text": "Using where clause check each employee salary which is greater than average value."
},
{
"code": null,
"e": 27300,
"s": 27277,
"text": "Select that employees."
},
{
"code": null,
"e": 27344,
"s": 27300,
"text": "Display the result using ToString() method."
},
{
"code": null,
"e": 27353,
"s": 27344,
"text": "Example:"
},
{
"code": null,
"e": 27356,
"s": 27353,
"text": "C#"
},
{
"code": "// C# program to display the lits of employees // whose salary is greater than average salary // of all the employeesusing System;using System.Collections.Generic;using System.Linq; class Employee{ // Declare three variables// employee name, age, and Salarystring emp_Name;int emp_Age;int emp_Salary; // Get the datapublic override string ToString(){ return \" \" + emp_Name + \" \" + emp_Age + \" \" + emp_Salary;} // Driver codestatic void Main(string[] args){ // Create the list of 5 employees List<Employee> emp = new List<Employee>() { new Employee{ emp_Name = \"sravan\", emp_Age = 21, emp_Salary = 26199 }, new Employee{ emp_Name = \"ramya\", emp_Age = 22, emp_Salary = 19000 }, new Employee{ emp_Name = \"harsha\", emp_Age = 23, emp_Salary = 25000 }, new Employee{ emp_Name = \"deepu\", emp_Age = 23, emp_Salary = 23456 }, new Employee{ emp_Name = \"jyothika\", emp_Age = 21, emp_Salary = 21345 } }; IEnumerable<Employee> result = // Getting the average of all the employees from e in emp // Total let total = emp.Sum(sal => sal.emp_Salary) let average = total / 5 // Condition to get salary greater than // average of all employees where e.emp_Salary > average // Select that employees select e; Console.WriteLine(\" Employee-Name Employee-Age Employee-Salary\"); foreach (Employee x in result) { Console.WriteLine(x.ToString()); }}}",
"e": 28950,
"s": 27356,
"text": null
},
{
"code": null,
"e": 28958,
"s": 28950,
"text": "Output:"
},
{
"code": null,
"e": 29048,
"s": 28958,
"text": "Employee-Name Employee-Age Employee-Salary\nsravan 21 26199\nharsha 23 25000\ndeepu 23 23456"
},
{
"code": null,
"e": 29062,
"s": 29050,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 29078,
"s": 29062,
"text": "CSharp-programs"
},
{
"code": null,
"e": 29085,
"s": 29078,
"text": "Picked"
},
{
"code": null,
"e": 29088,
"s": 29085,
"text": "C#"
},
{
"code": null,
"e": 29186,
"s": 29088,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29209,
"s": 29186,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29237,
"s": 29209,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29254,
"s": 29237,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29276,
"s": 29254,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29305,
"s": 29276,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 29345,
"s": 29305,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29368,
"s": 29345,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 29408,
"s": 29368,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 29451,
"s": 29408,
"text": "C# | How to insert an element in an Array?"
}
] |
Pattern Searching using Suffix Tree - GeeksforGeeks | 22 Feb, 2019
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Preprocess Pattern or Preoprocess Text?We have discussed the following algorithms in the previous posts:
KMP AlgorithmRabin Karp AlgorithmFinite Automata based AlgorithmBoyer Moore Algorithm
All of the above algorithms preprocess the pattern to make the pattern searching faster. The best time complexity that we could get by preprocessing pattern is O(n) where n is length of the text. In this post, we will discuss an approach that preprocesses the text. A suffix tree is built of the text. After preprocessing text (building suffix tree of text), we can search any pattern in O(m) time where m is length of the pattern.Imagine you have stored complete work of William Shakespeare and preprocessed it. You can search any string in the complete work in time just proportional to length of the pattern. This is really a great improvement because length of pattern is generally much smaller than text.Preprocessing of text may become costly if the text changes frequently. It is good for fixed text or less frequently changing text though.
A Suffix Tree for a given text is a compressed trie for all suffixes of the given text. We have discussed Standard Trie. Let us understand Compressed Trie with the following array of words.
{bear, bell, bid, bull, buy, sell, stock, stop}
Following is standard trie for the above input set of words.
Following is the compressed trie. Compress Trie is obtained from standard trie by joining chains of single nodes. The nodes of a compressed trie can be stored by storing index ranges at the nodes.
How to build a Suffix Tree for a given text?As discussed above, Suffix Tree is compressed trie of all suffixes, so following are very abstract steps to build a suffix tree from given text.1) Generate all suffixes of given text.2) Consider all suffixes as individual words and build a compressed trie.
Let us consider an example text “banana\0” where ‘\0’ is string termination character. Following are all suffixes of “banana\0”
banana\0
anana\0
nana\0
ana\0
na\0
a\0
\0
If we consider all of the above suffixes as individual words and build a trie, we get following.
If we join chains of single nodes, we get the following compressed trie, which is the Suffix Tree for given text “banana\0”
Please note that above steps are just to manually create a Suffix Tree. We will be discussing actual algorithm and implementation in a separate post.
How to search a pattern in the built suffix tree?We have discussed above how to build a Suffix Tree which is needed as a preprocessing step in pattern searching. Following are abstract steps to search a pattern in the built Suffix Tree.1) Starting from the first character of the pattern and root of Suffix Tree, do following for every character......a) For the current character of pattern, if there is an edge from the current node of suffix tree, follow the edge......b) If there is no edge, print “pattern doesn’t exist in text” and return.2) If all characters of pattern have been processed, i.e., there is a path from root for characters of the given pattern, then print “Pattern found”.
Let us consider the example pattern as “nan” to see the searching process. Following diagram shows the path followed for searching “nan” or “nana”.
How does this work?Every pattern that is present in text (or we can say every substring of text) must be a prefix of one of all possible suffixes. The statement seems complicated, but it is a simple statement, we just need to take an example to check validity of it.
Applications of Suffix TreeSuffix tree can be used for a wide range of problems. Following are some famous problems where Suffix Trees provide optimal time complexity solution.1) Pattern Searching2) Finding the longest repeated substring3) Finding the longest common substring4) Finding the longest palindrome in a string
There are many more applications. See this for more details.
Ukkonen’s Suffix Tree Construction is discussed in following articles:Ukkonen’s Suffix Tree Construction – Part 1Ukkonen’s Suffix Tree Construction – Part 2Ukkonen’s Suffix Tree Construction – Part 3Ukkonen’s Suffix Tree Construction – Part 4Ukkonen’s Suffix Tree Construction – Part 5Ukkonen’s Suffix Tree Construction – Part 6
References:http://fbim.fh-regensburg.de/~saj39122/sal/skript/progr/pr45102/Tries.pdfhttp://www.cs.ucf.edu/~shzhang/Combio12/lec3.pdfhttp://www.allisons.org/ll/AlgDS/Tree/Suffix/
Suffix-Tree
Advanced Data Structure
Pattern Searching
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Disjoint Set Data Structures
Insert Operation in B-Tree
Difference between B tree and B+ tree
Red-Black Tree | Set 3 (Delete)
Binomial Heap
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching | [
{
"code": null,
"e": 24706,
"s": 24678,
"text": "\n22 Feb, 2019"
},
{
"code": null,
"e": 24880,
"s": 24706,
"text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m."
},
{
"code": null,
"e": 24985,
"s": 24880,
"text": "Preprocess Pattern or Preoprocess Text?We have discussed the following algorithms in the previous posts:"
},
{
"code": null,
"e": 25071,
"s": 24985,
"text": "KMP AlgorithmRabin Karp AlgorithmFinite Automata based AlgorithmBoyer Moore Algorithm"
},
{
"code": null,
"e": 25919,
"s": 25071,
"text": "All of the above algorithms preprocess the pattern to make the pattern searching faster. The best time complexity that we could get by preprocessing pattern is O(n) where n is length of the text. In this post, we will discuss an approach that preprocesses the text. A suffix tree is built of the text. After preprocessing text (building suffix tree of text), we can search any pattern in O(m) time where m is length of the pattern.Imagine you have stored complete work of William Shakespeare and preprocessed it. You can search any string in the complete work in time just proportional to length of the pattern. This is really a great improvement because length of pattern is generally much smaller than text.Preprocessing of text may become costly if the text changes frequently. It is good for fixed text or less frequently changing text though."
},
{
"code": null,
"e": 26109,
"s": 25919,
"text": "A Suffix Tree for a given text is a compressed trie for all suffixes of the given text. We have discussed Standard Trie. Let us understand Compressed Trie with the following array of words."
},
{
"code": null,
"e": 26157,
"s": 26109,
"text": "{bear, bell, bid, bull, buy, sell, stock, stop}"
},
{
"code": null,
"e": 26218,
"s": 26157,
"text": "Following is standard trie for the above input set of words."
},
{
"code": null,
"e": 26415,
"s": 26218,
"text": "Following is the compressed trie. Compress Trie is obtained from standard trie by joining chains of single nodes. The nodes of a compressed trie can be stored by storing index ranges at the nodes."
},
{
"code": null,
"e": 26716,
"s": 26415,
"text": "How to build a Suffix Tree for a given text?As discussed above, Suffix Tree is compressed trie of all suffixes, so following are very abstract steps to build a suffix tree from given text.1) Generate all suffixes of given text.2) Consider all suffixes as individual words and build a compressed trie."
},
{
"code": null,
"e": 26844,
"s": 26716,
"text": "Let us consider an example text “banana\\0” where ‘\\0’ is string termination character. Following are all suffixes of “banana\\0”"
},
{
"code": null,
"e": 26886,
"s": 26844,
"text": "banana\\0\nanana\\0\nnana\\0\nana\\0\nna\\0\na\\0\n\\0"
},
{
"code": null,
"e": 26983,
"s": 26886,
"text": "If we consider all of the above suffixes as individual words and build a trie, we get following."
},
{
"code": null,
"e": 27107,
"s": 26983,
"text": "If we join chains of single nodes, we get the following compressed trie, which is the Suffix Tree for given text “banana\\0”"
},
{
"code": null,
"e": 27257,
"s": 27107,
"text": "Please note that above steps are just to manually create a Suffix Tree. We will be discussing actual algorithm and implementation in a separate post."
},
{
"code": null,
"e": 27951,
"s": 27257,
"text": "How to search a pattern in the built suffix tree?We have discussed above how to build a Suffix Tree which is needed as a preprocessing step in pattern searching. Following are abstract steps to search a pattern in the built Suffix Tree.1) Starting from the first character of the pattern and root of Suffix Tree, do following for every character......a) For the current character of pattern, if there is an edge from the current node of suffix tree, follow the edge......b) If there is no edge, print “pattern doesn’t exist in text” and return.2) If all characters of pattern have been processed, i.e., there is a path from root for characters of the given pattern, then print “Pattern found”."
},
{
"code": null,
"e": 28099,
"s": 27951,
"text": "Let us consider the example pattern as “nan” to see the searching process. Following diagram shows the path followed for searching “nan” or “nana”."
},
{
"code": null,
"e": 28366,
"s": 28099,
"text": "How does this work?Every pattern that is present in text (or we can say every substring of text) must be a prefix of one of all possible suffixes. The statement seems complicated, but it is a simple statement, we just need to take an example to check validity of it."
},
{
"code": null,
"e": 28688,
"s": 28366,
"text": "Applications of Suffix TreeSuffix tree can be used for a wide range of problems. Following are some famous problems where Suffix Trees provide optimal time complexity solution.1) Pattern Searching2) Finding the longest repeated substring3) Finding the longest common substring4) Finding the longest palindrome in a string"
},
{
"code": null,
"e": 28749,
"s": 28688,
"text": "There are many more applications. See this for more details."
},
{
"code": null,
"e": 29078,
"s": 28749,
"text": "Ukkonen’s Suffix Tree Construction is discussed in following articles:Ukkonen’s Suffix Tree Construction – Part 1Ukkonen’s Suffix Tree Construction – Part 2Ukkonen’s Suffix Tree Construction – Part 3Ukkonen’s Suffix Tree Construction – Part 4Ukkonen’s Suffix Tree Construction – Part 5Ukkonen’s Suffix Tree Construction – Part 6"
},
{
"code": null,
"e": 29256,
"s": 29078,
"text": "References:http://fbim.fh-regensburg.de/~saj39122/sal/skript/progr/pr45102/Tries.pdfhttp://www.cs.ucf.edu/~shzhang/Combio12/lec3.pdfhttp://www.allisons.org/ll/AlgDS/Tree/Suffix/"
},
{
"code": null,
"e": 29268,
"s": 29256,
"text": "Suffix-Tree"
},
{
"code": null,
"e": 29292,
"s": 29268,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 29310,
"s": 29292,
"text": "Pattern Searching"
},
{
"code": null,
"e": 29328,
"s": 29310,
"text": "Pattern Searching"
},
{
"code": null,
"e": 29426,
"s": 29328,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29435,
"s": 29426,
"text": "Comments"
},
{
"code": null,
"e": 29448,
"s": 29435,
"text": "Old Comments"
},
{
"code": null,
"e": 29477,
"s": 29448,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 29504,
"s": 29477,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 29542,
"s": 29504,
"text": "Difference between B tree and B+ tree"
},
{
"code": null,
"e": 29574,
"s": 29542,
"text": "Red-Black Tree | Set 3 (Delete)"
},
{
"code": null,
"e": 29588,
"s": 29574,
"text": "Binomial Heap"
},
{
"code": null,
"e": 29624,
"s": 29588,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 29667,
"s": 29624,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 29705,
"s": 29667,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 29747,
"s": 29705,
"text": "Check if a string is substring of another"
}
] |
Count of pairs containing even or consecutive elements from given Array - GeeksforGeeks | 15 Dec, 2021
Given an array arr[] of even size, the task is to find the count of pairs after partitioning arr[] into pairs, such that:
each element of arr[] belongs to exactly one pair
both of them are even or
absolute difference between them is 1, i.e, |X – Y| = 1.
Examples:
Input: arr[] = {11, 12, 16, 14}Output: {11, 12}, {16, 14}Explanation: arr[] can be partitioned into pairs in the following way. Pair 1 – {11, 12}, as |11-12| = 1. Pair 2 – {16, 14}, both 16 and 14 are even. Therefore, {11, 12} and {16, 14} are the two pairs.
Input: A = {4, 7}Output: No
Approach: This problem is observation-based. Firstly, if even numbers count and odd numbers count does not have the same parity then the answer does not exist. That means if the count of even and odd both are either even or both are either odd. Now the left case when even numbers and odd numbers are equal in frequency, then 2 cases are there:
Occurrence of even and odd numbers are even, then answer exists always.Occurrence even and odd numbers are odd, then check if there are 2 numbers in the array such that their absolute difference is 1, and then even and odd numbers occurrence becomes, even so, answer exist.
Occurrence of even and odd numbers are even, then answer exists always.
Occurrence even and odd numbers are odd, then check if there are 2 numbers in the array such that their absolute difference is 1, and then even and odd numbers occurrence becomes, even so, answer exist.
Follow the steps below to solve the given problem.
Create a variable even_count = 0 as count of even numbers and odd_count = 0, as count of odd numbers.
Iterate the array from index = 0 to n-1, check if arr[index]%2 == 0, increment even_count else increment odd_count.
Check if even_count = odd_countif condition false output No as the array pairs cannot exist.Else check if there exist 2 elements in the array such that their absolute difference is 1. To check such a pair exists, create an array temp and store the count of each number of the array, then iterate the array and check if the consecutive element count is greater than 1 or not.If exists output Yes.
if condition false output No as the array pairs cannot exist.
Else check if there exist 2 elements in the array such that their absolute difference is 1. To check such a pair exists, create an array temp and store the count of each number of the array, then iterate the array and check if the consecutive element count is greater than 1 or not.
If exists output Yes.
For printing the required pairs, print even numbers in pairs, then odd numbers in pairs, and the left 2 elements as the last pair.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find similar pairs in arr[]void CheckSimilarPair(int arr[], int n){ // Variable to count // Odd and even numbers int odd_count = 0; int even_count = 0; // Count even and odd occurences for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { cout << "-1\n"; } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array vector<int> temp(1001, 0); // Maximum element upto which // temp should be checked int max_element = 0; // Iterate the array and store their counts for (int index = 0; index < n; index++) { temp[arr[index]]++; max_element = max(max_element, arr[index]); } int element1 = -1; int element2 = -1; bool pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for (int index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs vector<int> res; // Even pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.push_back(arr[index]); } } // Odd pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.push_back(arr[index]); } } // Printing all pairs for (int index = 0; index < res.size() - 1; index += 2) { cout << "{" << res[index] << ", " << res[index + 1] << "}" << " "; } cout << "{" << element1 << ", " << element2 << "}"; } else { cout << "\nNo"; } }} // Driver codeint main(){ int arr[4] = { 11, 12, 16, 14 }; int N = 4; CheckSimilarPair(arr, N); return 0;}
// Java program for above approachimport java.util.*; class GFG{ // Function to find similar pairs in arr[]static void CheckSimilarPair(int arr[], int n){ // Variable to count // Odd and even numbers int odd_count = 0; int even_count = 0; // Count even and odd occurences for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { System.out.print("-1\n"); } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array int []temp = new int[1001]; // Maximum element upto which // temp should be checked int max_element = 0; // Iterate the array and store their counts for (int index = 0; index < n; index++) { temp[arr[index]]++; max_element = Math.max(max_element, arr[index]); } int element1 = -1; int element2 = -1; boolean pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for (int index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs Vector<Integer> res = new Vector<Integer>(); // Even pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.add(arr[index]); } } // Odd pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.add(arr[index]); } } // Printing all pairs for (int index = 0; index < res.size() - 1; index += 2) { System.out.print("{" + res.get(index)+ ", " + res.get(index+1)+ "}" + " "); } System.out.print("{" + element1+ ", " + element2+ "}"); } else { System.out.print("\nNo"); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 11, 12, 16, 14 }; int N = 4; CheckSimilarPair(arr, N); }} // This code is contributed by 29AjayKumar
# Python program for above approach # Function to find similar pairs in arr[]def CheckSimilarPair(arr, n): # Variable to count # Odd and even numbers odd_count = 0 even_count = 0 # Count even and odd occurences for index in range(n): if (arr[index] % 2 == 0): even_count += 1 else: odd_count += 1 # Checking same parity of count of even # and odd numbers if ((even_count % 2 == 0 and odd_count % 2 == 1) or (even_count % 2 == 1 and odd_count % 2 == 0)): print("-1") else: # Check if there exist 2 numbers # with absolute difference is 1 # Vector to store frequency # of elements of the array temp = [0] * 1001 # Maximum element upto which # temp should be checked max_element = 0 # Iterate the array and store their counts for index in range(n): temp[arr[index]] += 1 max_element = max(max_element, arr[index]) element1 = -1 element2 = -1 pair_exist = False # Iterate the temp array # upto max_element and check # if 2 element exist # having 1 abs' difference for index in range(max_element + 1): if (temp[index - 1] >= 1 and temp[index] >= 1): element1 = index - 1 element2 = index pair_exist = True break # If pair exist if (pair_exist): # Vector storing pairs res = [] # Even pairs for index in range(n): if (arr[index] % 2 == 0 and arr[index] != element1 and arr[index] != element2): res.append(arr[index]) # Odd pairs for index in range(n): if (arr[index] % 2 == 1 and arr[index] != element1 and arr[index] != element2): res.append(arr[index]) # Printing all pairs for index in range(0, len(res) - 1, 2): print("{", end=" ") print(f"{res[index]} , {res[index + 1]}", end=" ") print("}", end=" ") print("{", end=" ") print(f"{element1} ,{element2}", end=" ") print("}") else: print('<br>' + "No") # Driver codearr = [11, 12, 16, 14]N = 4 CheckSimilarPair(arr, N) # This code is contributed by gfgking
// C# program for the above approachusing System;using System.Collections; class GFG{ // Function to find similar pairs in arr[]static void CheckSimilarPair(int []arr, int n){ // Variable to count // Odd and even numbers int odd_count = 0; int even_count = 0; // Count even and odd occurences for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { Console.Write("-1\n"); } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array int []temp = new int[1001]; // Maximum element upto which // temp should be checked int max_element = 0; // Iterate the array and store their counts for (int index = 0; index < n; index++) { temp[arr[index]]++; max_element = Math.Max(max_element, arr[index]); } int element1 = -1; int element2 = -1; bool pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for (int index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs ArrayList res = new ArrayList(); // Even pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.Add(arr[index]); } } // Odd pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.Add(arr[index]); } } // Printing all pairs for (int index = 0; index < res.Count - 1; index += 2) { Console.Write("{" + res[index]+ ", " + res[index+1]+ "}" + " "); } Console.Write("{" + element1+ ", " + element2+ "}"); } else { Console.Write("\nNo"); } }} // Driver Codepublic static void Main(){ int []arr = { 11, 12, 16, 14 }; int N = 4; CheckSimilarPair(arr, N);}}// This code is contributed by Samim Hossain Mondal.
<script> // JavaScript program for above approach // Function to find similar pairs in arr[]function CheckSimilarPair(arr, n){ // Variable to count // Odd and even numbers let odd_count = 0; let even_count = 0; // Count even and odd occurences for(let index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { cout << "-1\n"; } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array let temp = new Array(1001).fill(0) // Maximum element upto which // temp should be checked let max_element = 0; // Iterate the array and store their counts for(let index = 0; index < n; index++) { temp[arr[index]]++; max_element = Math.max(max_element, arr[index]); } let element1 = -1; let element2 = -1; let pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for(let index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs let res = []; // Even pairs for(let index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.push(arr[index]); } } // Odd pairs for(let index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.push(arr[index]); } } // Printing all pairs for(let index = 0; index < res.length - 1; index += 2) { document.write("{" + res[index] + ", " + res[index + 1] + "}" + " "); } document.write("{" + element1 + ", " + element2 + "}"); } else { document.write('<br>' + "No"); } }} // Driver codelet arr = [ 11, 12, 16, 14 ];let N = 4; CheckSimilarPair(arr, N); // This code is contributed by Potta Lokesh </script>
{16, 14} {11, 12}
Time Complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
29AjayKumar
gfgking
samim2000
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 24551,
"s": 24429,
"text": "Given an array arr[] of even size, the task is to find the count of pairs after partitioning arr[] into pairs, such that:"
},
{
"code": null,
"e": 24601,
"s": 24551,
"text": "each element of arr[] belongs to exactly one pair"
},
{
"code": null,
"e": 24626,
"s": 24601,
"text": "both of them are even or"
},
{
"code": null,
"e": 24683,
"s": 24626,
"text": "absolute difference between them is 1, i.e, |X – Y| = 1."
},
{
"code": null,
"e": 24694,
"s": 24683,
"text": "Examples: "
},
{
"code": null,
"e": 24954,
"s": 24694,
"text": "Input: arr[] = {11, 12, 16, 14}Output: {11, 12}, {16, 14}Explanation: arr[] can be partitioned into pairs in the following way. Pair 1 – {11, 12}, as |11-12| = 1. Pair 2 – {16, 14}, both 16 and 14 are even. Therefore, {11, 12} and {16, 14} are the two pairs. "
},
{
"code": null,
"e": 24982,
"s": 24954,
"text": "Input: A = {4, 7}Output: No"
},
{
"code": null,
"e": 25327,
"s": 24982,
"text": "Approach: This problem is observation-based. Firstly, if even numbers count and odd numbers count does not have the same parity then the answer does not exist. That means if the count of even and odd both are either even or both are either odd. Now the left case when even numbers and odd numbers are equal in frequency, then 2 cases are there:"
},
{
"code": null,
"e": 25601,
"s": 25327,
"text": "Occurrence of even and odd numbers are even, then answer exists always.Occurrence even and odd numbers are odd, then check if there are 2 numbers in the array such that their absolute difference is 1, and then even and odd numbers occurrence becomes, even so, answer exist."
},
{
"code": null,
"e": 25673,
"s": 25601,
"text": "Occurrence of even and odd numbers are even, then answer exists always."
},
{
"code": null,
"e": 25876,
"s": 25673,
"text": "Occurrence even and odd numbers are odd, then check if there are 2 numbers in the array such that their absolute difference is 1, and then even and odd numbers occurrence becomes, even so, answer exist."
},
{
"code": null,
"e": 25928,
"s": 25876,
"text": "Follow the steps below to solve the given problem. "
},
{
"code": null,
"e": 26030,
"s": 25928,
"text": "Create a variable even_count = 0 as count of even numbers and odd_count = 0, as count of odd numbers."
},
{
"code": null,
"e": 26146,
"s": 26030,
"text": "Iterate the array from index = 0 to n-1, check if arr[index]%2 == 0, increment even_count else increment odd_count."
},
{
"code": null,
"e": 26542,
"s": 26146,
"text": "Check if even_count = odd_countif condition false output No as the array pairs cannot exist.Else check if there exist 2 elements in the array such that their absolute difference is 1. To check such a pair exists, create an array temp and store the count of each number of the array, then iterate the array and check if the consecutive element count is greater than 1 or not.If exists output Yes."
},
{
"code": null,
"e": 26604,
"s": 26542,
"text": "if condition false output No as the array pairs cannot exist."
},
{
"code": null,
"e": 26887,
"s": 26604,
"text": "Else check if there exist 2 elements in the array such that their absolute difference is 1. To check such a pair exists, create an array temp and store the count of each number of the array, then iterate the array and check if the consecutive element count is greater than 1 or not."
},
{
"code": null,
"e": 26909,
"s": 26887,
"text": "If exists output Yes."
},
{
"code": null,
"e": 27040,
"s": 26909,
"text": "For printing the required pairs, print even numbers in pairs, then odd numbers in pairs, and the left 2 elements as the last pair."
},
{
"code": null,
"e": 27091,
"s": 27040,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27095,
"s": 27091,
"text": "C++"
},
{
"code": null,
"e": 27100,
"s": 27095,
"text": "Java"
},
{
"code": null,
"e": 27108,
"s": 27100,
"text": "Python3"
},
{
"code": null,
"e": 27111,
"s": 27108,
"text": "C#"
},
{
"code": null,
"e": 27122,
"s": 27111,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find similar pairs in arr[]void CheckSimilarPair(int arr[], int n){ // Variable to count // Odd and even numbers int odd_count = 0; int even_count = 0; // Count even and odd occurences for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { cout << \"-1\\n\"; } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array vector<int> temp(1001, 0); // Maximum element upto which // temp should be checked int max_element = 0; // Iterate the array and store their counts for (int index = 0; index < n; index++) { temp[arr[index]]++; max_element = max(max_element, arr[index]); } int element1 = -1; int element2 = -1; bool pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for (int index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs vector<int> res; // Even pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.push_back(arr[index]); } } // Odd pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.push_back(arr[index]); } } // Printing all pairs for (int index = 0; index < res.size() - 1; index += 2) { cout << \"{\" << res[index] << \", \" << res[index + 1] << \"}\" << \" \"; } cout << \"{\" << element1 << \", \" << element2 << \"}\"; } else { cout << \"\\nNo\"; } }} // Driver codeint main(){ int arr[4] = { 11, 12, 16, 14 }; int N = 4; CheckSimilarPair(arr, N); return 0;}",
"e": 29978,
"s": 27122,
"text": null
},
{
"code": "// Java program for above approachimport java.util.*; class GFG{ // Function to find similar pairs in arr[]static void CheckSimilarPair(int arr[], int n){ // Variable to count // Odd and even numbers int odd_count = 0; int even_count = 0; // Count even and odd occurences for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { System.out.print(\"-1\\n\"); } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array int []temp = new int[1001]; // Maximum element upto which // temp should be checked int max_element = 0; // Iterate the array and store their counts for (int index = 0; index < n; index++) { temp[arr[index]]++; max_element = Math.max(max_element, arr[index]); } int element1 = -1; int element2 = -1; boolean pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for (int index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs Vector<Integer> res = new Vector<Integer>(); // Even pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.add(arr[index]); } } // Odd pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.add(arr[index]); } } // Printing all pairs for (int index = 0; index < res.size() - 1; index += 2) { System.out.print(\"{\" + res.get(index)+ \", \" + res.get(index+1)+ \"}\" + \" \"); } System.out.print(\"{\" + element1+ \", \" + element2+ \"}\"); } else { System.out.print(\"\\nNo\"); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 11, 12, 16, 14 }; int N = 4; CheckSimilarPair(arr, N); }} // This code is contributed by 29AjayKumar",
"e": 32985,
"s": 29978,
"text": null
},
{
"code": "# Python program for above approach # Function to find similar pairs in arr[]def CheckSimilarPair(arr, n): # Variable to count # Odd and even numbers odd_count = 0 even_count = 0 # Count even and odd occurences for index in range(n): if (arr[index] % 2 == 0): even_count += 1 else: odd_count += 1 # Checking same parity of count of even # and odd numbers if ((even_count % 2 == 0 and odd_count % 2 == 1) or (even_count % 2 == 1 and odd_count % 2 == 0)): print(\"-1\") else: # Check if there exist 2 numbers # with absolute difference is 1 # Vector to store frequency # of elements of the array temp = [0] * 1001 # Maximum element upto which # temp should be checked max_element = 0 # Iterate the array and store their counts for index in range(n): temp[arr[index]] += 1 max_element = max(max_element, arr[index]) element1 = -1 element2 = -1 pair_exist = False # Iterate the temp array # upto max_element and check # if 2 element exist # having 1 abs' difference for index in range(max_element + 1): if (temp[index - 1] >= 1 and temp[index] >= 1): element1 = index - 1 element2 = index pair_exist = True break # If pair exist if (pair_exist): # Vector storing pairs res = [] # Even pairs for index in range(n): if (arr[index] % 2 == 0 and arr[index] != element1 and arr[index] != element2): res.append(arr[index]) # Odd pairs for index in range(n): if (arr[index] % 2 == 1 and arr[index] != element1 and arr[index] != element2): res.append(arr[index]) # Printing all pairs for index in range(0, len(res) - 1, 2): print(\"{\", end=\" \") print(f\"{res[index]} , {res[index + 1]}\", end=\" \") print(\"}\", end=\" \") print(\"{\", end=\" \") print(f\"{element1} ,{element2}\", end=\" \") print(\"}\") else: print('<br>' + \"No\") # Driver codearr = [11, 12, 16, 14]N = 4 CheckSimilarPair(arr, N) # This code is contributed by gfgking",
"e": 35362,
"s": 32985,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections; class GFG{ // Function to find similar pairs in arr[]static void CheckSimilarPair(int []arr, int n){ // Variable to count // Odd and even numbers int odd_count = 0; int even_count = 0; // Count even and odd occurences for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { Console.Write(\"-1\\n\"); } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array int []temp = new int[1001]; // Maximum element upto which // temp should be checked int max_element = 0; // Iterate the array and store their counts for (int index = 0; index < n; index++) { temp[arr[index]]++; max_element = Math.Max(max_element, arr[index]); } int element1 = -1; int element2 = -1; bool pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for (int index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs ArrayList res = new ArrayList(); // Even pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.Add(arr[index]); } } // Odd pairs for (int index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.Add(arr[index]); } } // Printing all pairs for (int index = 0; index < res.Count - 1; index += 2) { Console.Write(\"{\" + res[index]+ \", \" + res[index+1]+ \"}\" + \" \"); } Console.Write(\"{\" + element1+ \", \" + element2+ \"}\"); } else { Console.Write(\"\\nNo\"); } }} // Driver Codepublic static void Main(){ int []arr = { 11, 12, 16, 14 }; int N = 4; CheckSimilarPair(arr, N);}}// This code is contributed by Samim Hossain Mondal.",
"e": 38349,
"s": 35362,
"text": null
},
{
"code": "<script> // JavaScript program for above approach // Function to find similar pairs in arr[]function CheckSimilarPair(arr, n){ // Variable to count // Odd and even numbers let odd_count = 0; let even_count = 0; // Count even and odd occurences for(let index = 0; index < n; index++) { if (arr[index] % 2 == 0) even_count++; else odd_count++; } // Checking same parity of count of even // and odd numbers if ((even_count % 2 == 0 && odd_count % 2 == 1) || (even_count % 2 == 1 && odd_count % 2 == 0)) { cout << \"-1\\n\"; } else { // Check if there exist 2 numbers // with absolute difference is 1 // Vector to store frequency // of elements of the array let temp = new Array(1001).fill(0) // Maximum element upto which // temp should be checked let max_element = 0; // Iterate the array and store their counts for(let index = 0; index < n; index++) { temp[arr[index]]++; max_element = Math.max(max_element, arr[index]); } let element1 = -1; let element2 = -1; let pair_exist = false; // Iterate the temp array // upto max_element and check // if 2 element exist // having 1 abs' difference for(let index = 1; index <= max_element; index++) { if (temp[index - 1] >= 1 && temp[index] >= 1) { element1 = index - 1; element2 = index; pair_exist = true; break; } } // If pair exist if (pair_exist) { // Vector storing pairs let res = []; // Even pairs for(let index = 0; index < n; index++) { if (arr[index] % 2 == 0 && arr[index] != element1 && arr[index] != element2) { res.push(arr[index]); } } // Odd pairs for(let index = 0; index < n; index++) { if (arr[index] % 2 == 1 && arr[index] != element1 && arr[index] != element2) { res.push(arr[index]); } } // Printing all pairs for(let index = 0; index < res.length - 1; index += 2) { document.write(\"{\" + res[index] + \", \" + res[index + 1] + \"}\" + \" \"); } document.write(\"{\" + element1 + \", \" + element2 + \"}\"); } else { document.write('<br>' + \"No\"); } }} // Driver codelet arr = [ 11, 12, 16, 14 ];let N = 4; CheckSimilarPair(arr, N); // This code is contributed by Potta Lokesh </script>",
"e": 41433,
"s": 38349,
"text": null
},
{
"code": null,
"e": 41451,
"s": 41433,
"text": "{16, 14} {11, 12}"
},
{
"code": null,
"e": 41494,
"s": 41451,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 41510,
"s": 41496,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 41522,
"s": 41510,
"text": "29AjayKumar"
},
{
"code": null,
"e": 41530,
"s": 41522,
"text": "gfgking"
},
{
"code": null,
"e": 41540,
"s": 41530,
"text": "samim2000"
},
{
"code": null,
"e": 41547,
"s": 41540,
"text": "Arrays"
},
{
"code": null,
"e": 41554,
"s": 41547,
"text": "Greedy"
},
{
"code": null,
"e": 41561,
"s": 41554,
"text": "Arrays"
},
{
"code": null,
"e": 41568,
"s": 41561,
"text": "Greedy"
},
{
"code": null,
"e": 41666,
"s": 41568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41675,
"s": 41666,
"text": "Comments"
},
{
"code": null,
"e": 41688,
"s": 41675,
"text": "Old Comments"
},
{
"code": null,
"e": 41709,
"s": 41688,
"text": "Next Greater Element"
},
{
"code": null,
"e": 41734,
"s": 41709,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 41761,
"s": 41734,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 41810,
"s": 41761,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 41848,
"s": 41810,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 41899,
"s": 41848,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 41950,
"s": 41899,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 42008,
"s": 41950,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 42039,
"s": 42008,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
Image Processing using Streamlit. In this article, we will see how we can... | by Aniket Wattamwar | Towards Data Science | In this article, we will see how we can use Streamlit with Image Processing Techniques and Object Detection Algorithms. I am assuming that you have Streamlit installed and working on your system. If you do not know how to start with streamlit then you can refer to my previous article where I have explained it in brief.
I have also deployed this streamlit app on Streamlit Sharing. You can have a look at it before reading the article further.
Here is the link: Image Processing using Streamlit
Let’s dive into the code now.
First importing the necessary libraries
import streamlit as stfrom PIL import Imageimport cv2 import numpy as np
I have created the main function which is the starting point of the code. In this function, you will see a sidebar that I have created. Streamlit provides you sidebar selectbox function to easily create one. In the sidebar, I have added some values and with each of the values, a function is associated. When the user clicks on any one of them the corresponding function is triggered. By default, the first value which is the Welcome string is selected and the if statement calls the welcome() function.
def main():selected_box = st.sidebar.selectbox( 'Choose one of the following', ('Welcome','Image Processing', 'Video', 'Face Detection', 'Feature Detection', 'Object Detection') ) if selected_box == 'Welcome': welcome() if selected_box == 'Image Processing': photo() if selected_box == 'Video': video() if selected_box == 'Face Detection': face_detection() if selected_box == 'Feature Detection': feature_detection() if selected_box == 'Object Detection': object_detection()if __name__ == "__main__": main()
The below image shows the welcome page. Let's look at the welcome function as well.
def welcome(): st.title('Image Processing using Streamlit') st.subheader('A simple app that shows different image processing algorithms. You can choose the options' + ' from the left. I have implemented only a few to show how it works on Streamlit. ' + 'You are free to add stuff to this app.') st.image('hackershrine.jpg',use_column_width=True)
With st.title you can create a bold title and with st.subheader you can have a bold with lower font size. And with st.image you can display any image on your streamlit app. Make sure you set the column width to true so that it fits properly.
Next, we have the image processing part in the sidebar. Here, we will see thresholding, edge detection, and contours. I have used a slider to change the value of the threshold as per user convenience. To make an interactive slider you simply write st.slider in streamlit. With the help of OpenCV, we are doing the conversion of RGB to Gray and then using the threshold function in OpenCV. We pass the value of the slider in the threshold function. So when we move the slider the value changes and is stored in thresh1. Then we use st.image to display the thresh1 image. Make sure you set clamp to True.
Next, we have a bar chart displaying that image. You can do this using the bar chart function in streamlit. The value that is passed is calculated with the cv2.calchist function. You can use different histograms and plots for analysis of your images.
Then we have the Canny edge detection technique. I have made a button and when the user clicks on it, it runs the algorithm and displays the output. You can create a button simply by writing st.button along with if statement. Inside the if you write your edge detection code.
For Contours, again I have used a slider to change the image so that it the contours change. In OpenCV, you have the find contours function and draw contours function where you pass the image.
def photo():st.header("Thresholding, Edge Detection and Contours") if st.button('See Original Image of Tom'): original = Image.open('tom.jpg') st.image(original, use_column_width=True) image = cv2.imread('tom.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) x = st.slider('Change Threshold value',min_value = 50,max_value = 255)ret,thresh1 = cv2.threshold(image,x,255,cv2.THRESH_BINARY) thresh1 = thresh1.astype(np.float64) st.image(thresh1, use_column_width=True,clamp = True) st.text("Bar Chart of the image") histr = cv2.calcHist([image],[0],None,[256],[0,256]) st.bar_chart(histr) st.text("Press the button below to view Canny Edge Detection Technique") if st.button('Canny Edge Detector'): image = load_image("jerry.jpg") edges = cv2.Canny(image,50,300) cv2.imwrite('edges.jpg',edges) st.image(edges,use_column_width=True,clamp=True) y = st.slider('Change Value to increase or decrease contours',min_value = 50,max_value = 255) if st.button('Contours'): im = load_image("jerry1.jpg") imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,y,255,0) image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) img = cv2.drawContours(im, contours, -1, (0,255,0), 3) st.image(thresh, use_column_width=True, clamp = True) st.image(img, use_column_width=True, clamp = True)
The next part we will look at is Face detection. For face detection, I am using a haar cascade file. Using the cascadeClassifier we will load the XML file. We have the detectMultiScale function where we pass the image to find the faces in that image. If we find the image then draw a rectangle around the face. If you wish to save the image then you can use write function. Then we display the image using st.image using Streamlit.
def face_detection(): st.header("Face Detection using haarcascade") if st.button('See Original Image'): original = Image.open('friends.jpeg') st.image(original, use_column_width=True) image2 = cv2.imread("friends.jpeg")face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") faces = face_cascade.detectMultiScale(image2) print(f"{len(faces)} faces detected in the image.") for x, y, width, height in faces: cv2.rectangle(image2, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2) cv2.imwrite("faces.jpg", image2) st.image(image2, use_column_width=True,clamp = True)
The last part that I want to show is the Object Detection. I have used wallclock and eye haar cascade files to do object detection. Similar to face detection, we will load the XML files and use the detect multiscale function. If the respective objects are found we are going to draw a rectangle around that object. The below images show the output.
def object_detection(): st.header('Object Detection') st.subheader("Object Detection is done using different haarcascade files.") img = load_image("clock.jpg") img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) clock = cv2.CascadeClassifier('haarcascade_wallclock.xml') found = clock.detectMultiScale(img_gray, minSize =(20, 20)) amount_found = len(found) st.text("Detecting a clock from an image") if amount_found != 0: for (x, y, width, height) in found: cv2.rectangle(img_rgb, (x, y), (x + height, y + width), (0, 255, 0), 5) st.image(img_rgb, use_column_width=True,clamp = True) st.text("Detecting eyes from an image") image = load_image("eyes.jpg") img_gray_ = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) img_rgb_ = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) eye = cv2.CascadeClassifier('haarcascade_eye.xml') found = eye.detectMultiScale(img_gray_, minSize =(20, 20)) amount_found_ = len(found) if amount_found_ != 0: for (x, y, width, height) in found: cv2.rectangle(img_rgb_, (x, y), (x + height, y + width), (0, 255, 0), 5) st.image(img_rgb_, use_column_width=True,clamp = True)
You can find the code on my Github. I have also made a video on it.
For further reading on Image processing and Machine learning, you can refer to this informative article. | [
{
"code": null,
"e": 492,
"s": 171,
"text": "In this article, we will see how we can use Streamlit with Image Processing Techniques and Object Detection Algorithms. I am assuming that you have Streamlit installed and working on your system. If you do not know how to start with streamlit then you can refer to my previous article where I have explained it in brief."
},
{
"code": null,
"e": 616,
"s": 492,
"text": "I have also deployed this streamlit app on Streamlit Sharing. You can have a look at it before reading the article further."
},
{
"code": null,
"e": 667,
"s": 616,
"text": "Here is the link: Image Processing using Streamlit"
},
{
"code": null,
"e": 697,
"s": 667,
"text": "Let’s dive into the code now."
},
{
"code": null,
"e": 737,
"s": 697,
"text": "First importing the necessary libraries"
},
{
"code": null,
"e": 810,
"s": 737,
"text": "import streamlit as stfrom PIL import Imageimport cv2 import numpy as np"
},
{
"code": null,
"e": 1314,
"s": 810,
"text": "I have created the main function which is the starting point of the code. In this function, you will see a sidebar that I have created. Streamlit provides you sidebar selectbox function to easily create one. In the sidebar, I have added some values and with each of the values, a function is associated. When the user clicks on any one of them the corresponding function is triggered. By default, the first value which is the Welcome string is selected and the if statement calls the welcome() function."
},
{
"code": null,
"e": 1899,
"s": 1314,
"text": "def main():selected_box = st.sidebar.selectbox( 'Choose one of the following', ('Welcome','Image Processing', 'Video', 'Face Detection', 'Feature Detection', 'Object Detection') ) if selected_box == 'Welcome': welcome() if selected_box == 'Image Processing': photo() if selected_box == 'Video': video() if selected_box == 'Face Detection': face_detection() if selected_box == 'Feature Detection': feature_detection() if selected_box == 'Object Detection': object_detection()if __name__ == \"__main__\": main()"
},
{
"code": null,
"e": 1983,
"s": 1899,
"text": "The below image shows the welcome page. Let's look at the welcome function as well."
},
{
"code": null,
"e": 2375,
"s": 1983,
"text": "def welcome(): st.title('Image Processing using Streamlit') st.subheader('A simple app that shows different image processing algorithms. You can choose the options' + ' from the left. I have implemented only a few to show how it works on Streamlit. ' + 'You are free to add stuff to this app.') st.image('hackershrine.jpg',use_column_width=True)"
},
{
"code": null,
"e": 2617,
"s": 2375,
"text": "With st.title you can create a bold title and with st.subheader you can have a bold with lower font size. And with st.image you can display any image on your streamlit app. Make sure you set the column width to true so that it fits properly."
},
{
"code": null,
"e": 3220,
"s": 2617,
"text": "Next, we have the image processing part in the sidebar. Here, we will see thresholding, edge detection, and contours. I have used a slider to change the value of the threshold as per user convenience. To make an interactive slider you simply write st.slider in streamlit. With the help of OpenCV, we are doing the conversion of RGB to Gray and then using the threshold function in OpenCV. We pass the value of the slider in the threshold function. So when we move the slider the value changes and is stored in thresh1. Then we use st.image to display the thresh1 image. Make sure you set clamp to True."
},
{
"code": null,
"e": 3471,
"s": 3220,
"text": "Next, we have a bar chart displaying that image. You can do this using the bar chart function in streamlit. The value that is passed is calculated with the cv2.calchist function. You can use different histograms and plots for analysis of your images."
},
{
"code": null,
"e": 3747,
"s": 3471,
"text": "Then we have the Canny edge detection technique. I have made a button and when the user clicks on it, it runs the algorithm and displays the output. You can create a button simply by writing st.button along with if statement. Inside the if you write your edge detection code."
},
{
"code": null,
"e": 3940,
"s": 3747,
"text": "For Contours, again I have used a slider to change the image so that it the contours change. In OpenCV, you have the find contours function and draw contours function where you pass the image."
},
{
"code": null,
"e": 5478,
"s": 3940,
"text": "def photo():st.header(\"Thresholding, Edge Detection and Contours\") if st.button('See Original Image of Tom'): original = Image.open('tom.jpg') st.image(original, use_column_width=True) image = cv2.imread('tom.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) x = st.slider('Change Threshold value',min_value = 50,max_value = 255)ret,thresh1 = cv2.threshold(image,x,255,cv2.THRESH_BINARY) thresh1 = thresh1.astype(np.float64) st.image(thresh1, use_column_width=True,clamp = True) st.text(\"Bar Chart of the image\") histr = cv2.calcHist([image],[0],None,[256],[0,256]) st.bar_chart(histr) st.text(\"Press the button below to view Canny Edge Detection Technique\") if st.button('Canny Edge Detector'): image = load_image(\"jerry.jpg\") edges = cv2.Canny(image,50,300) cv2.imwrite('edges.jpg',edges) st.image(edges,use_column_width=True,clamp=True) y = st.slider('Change Value to increase or decrease contours',min_value = 50,max_value = 255) if st.button('Contours'): im = load_image(\"jerry1.jpg\") imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,y,255,0) image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) img = cv2.drawContours(im, contours, -1, (0,255,0), 3) st.image(thresh, use_column_width=True, clamp = True) st.image(img, use_column_width=True, clamp = True)"
},
{
"code": null,
"e": 5910,
"s": 5478,
"text": "The next part we will look at is Face detection. For face detection, I am using a haar cascade file. Using the cascadeClassifier we will load the XML file. We have the detectMultiScale function where we pass the image to find the faces in that image. If we find the image then draw a rectangle around the face. If you wish to save the image then you can use write function. Then we display the image using st.image using Streamlit."
},
{
"code": null,
"e": 6587,
"s": 5910,
"text": "def face_detection(): st.header(\"Face Detection using haarcascade\") if st.button('See Original Image'): original = Image.open('friends.jpeg') st.image(original, use_column_width=True) image2 = cv2.imread(\"friends.jpeg\")face_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\") faces = face_cascade.detectMultiScale(image2) print(f\"{len(faces)} faces detected in the image.\") for x, y, width, height in faces: cv2.rectangle(image2, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2) cv2.imwrite(\"faces.jpg\", image2) st.image(image2, use_column_width=True,clamp = True)"
},
{
"code": null,
"e": 6936,
"s": 6587,
"text": "The last part that I want to show is the Object Detection. I have used wallclock and eye haar cascade files to do object detection. Similar to face detection, we will load the XML files and use the detect multiscale function. If the respective objects are found we are going to draw a rectangle around that object. The below images show the output."
},
{
"code": null,
"e": 8419,
"s": 6936,
"text": "def object_detection(): st.header('Object Detection') st.subheader(\"Object Detection is done using different haarcascade files.\") img = load_image(\"clock.jpg\") img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) clock = cv2.CascadeClassifier('haarcascade_wallclock.xml') found = clock.detectMultiScale(img_gray, minSize =(20, 20)) amount_found = len(found) st.text(\"Detecting a clock from an image\") if amount_found != 0: for (x, y, width, height) in found: cv2.rectangle(img_rgb, (x, y), (x + height, y + width), (0, 255, 0), 5) st.image(img_rgb, use_column_width=True,clamp = True) st.text(\"Detecting eyes from an image\") image = load_image(\"eyes.jpg\") img_gray_ = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) img_rgb_ = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) eye = cv2.CascadeClassifier('haarcascade_eye.xml') found = eye.detectMultiScale(img_gray_, minSize =(20, 20)) amount_found_ = len(found) if amount_found_ != 0: for (x, y, width, height) in found: cv2.rectangle(img_rgb_, (x, y), (x + height, y + width), (0, 255, 0), 5) st.image(img_rgb_, use_column_width=True,clamp = True)"
},
{
"code": null,
"e": 8487,
"s": 8419,
"text": "You can find the code on my Github. I have also made a video on it."
}
] |
How to Get Started with PySpark. PySpark is a Python API to using Spark... | by Sanket Gupta | Towards Data Science | PySpark is a Python API to using Spark, which is a parallel and distributed engine for running big data applications. Getting started with PySpark took me a few hours — when it shouldn’t have — as I had to read a lot of blogs/documentation to debug some of the setup issues. This blog is an attempt to help you get up and running on PySpark in no time!
UPDATE: I have written a new blog post on PySpark and how to get started with Spark with some of the managed services such as Databricks and EMR as well as some of the common architectures. It is titled Moving from Pandas to Spark. Check it out if you are interested to learn more!
These steps are for Mac OS X (I am running OS X 10.13 High Sierra), and for Python 3.6.
You can install Anaconda and if you already have it, start a new conda environment using conda create -n pyspark_env python=3 This will create a new conda environment with latest version of Python 3 for us to try our mini-PySpark project. Activate the environment with source activate pyspark_env
You could try using pip to install pyspark but I couldn’t get the pyspark cluster to get started properly. Reading several answers on Stack Overflow and the official documentation, I came across this:
The Python packaging for Spark is not intended to replace all of the other use cases. This Python packaged version of Spark is suitable for interacting with an existing cluster (be it Spark standalone, YARN, or Mesos) - but does not contain the tools required to setup your own standalone Spark cluster. You can download the full version of Spark from the Apache Spark downloads page.
Using the link above, I went ahead and downloaded the spark-2.3.0-bin-hadoop2.7.tgz and stored the unpacked version in my home directory.
Several instructions recommended using Java 8 or later, and I went ahead and installed Java 10. This actually resulted in several errors such as the following when I tried to run collect() or count() in my Spark cluster:
py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.: java.lang.IllegalArgumentException
My initial guess was it had to do something with Py4J installation, which I tried re-installing a couple of times without any help. Not many people were talking about this error, and after reading several Stack Overflow posts, I came across this post which talked about how Spark 2.2.1 was having problems with Java 9 and beyond. The recommended solution was to install Java 8.
So, install Java 8 JDK and move to the next step.
To tell the bash how to find Spark package and Java SDK, add following lines to your .bash_profile (if you are using vim, you can do vim ~/.bash_profile to edit this file)
export JAVA_HOME=$(/usr/libexec/java_home)export SPARK_HOME=~/spark-2.3.0-bin-hadoop2.7export PATH=$SPARK_HOME/bin:$PATHexport PYSPARK_PYTHON=python3
These commands tell the bash how to use the recently installed Java and Spark packages. Run source ~/.bash_profile to source this file or open a new terminal to auto-source this file.
Run pyspark command and you will get to this:
You could use command line to run Spark commands, but it is not very convenient. You can install jupyter notebook using pip install jupyter notebook , and when you run jupyter notebook you can access the Spark cluster in the notebook. You can also just use vim or nano or any other code editor of your choice to write code into python files that you can run from command line.
Run a small and quick program to estimate the value of pi to see your Spark cluster in action!
import randomNUM_SAMPLES = 100000000def inside(p): x, y = random.random(), random.random() return x*x + y*y < 1count = sc.parallelize(range(0, NUM_SAMPLES)).filter(inside).count()pi = 4 * count / NUM_SAMPLESprint(“Pi is roughly”, pi)
There are lot of things in PySpark to explore such as Resilient Distributed Datasets or RDDs (update: now DataFrame API is the best way to use Spark, RDDs talk about “how” to do tasks vs Dataframes which talk about “what” — this makes Dataframes much faster and optimized) and MLlib.
UPDATE JUNE 2021: I have written a new blog post on PySpark and how to get started with Spark with some of the managed services such as Databricks and EMR as well as some of the common architectures. It is titled Moving from Pandas to Spark. Check it out if you are interested to learn more! Thank you for reading. | [
{
"code": null,
"e": 525,
"s": 172,
"text": "PySpark is a Python API to using Spark, which is a parallel and distributed engine for running big data applications. Getting started with PySpark took me a few hours — when it shouldn’t have — as I had to read a lot of blogs/documentation to debug some of the setup issues. This blog is an attempt to help you get up and running on PySpark in no time!"
},
{
"code": null,
"e": 807,
"s": 525,
"text": "UPDATE: I have written a new blog post on PySpark and how to get started with Spark with some of the managed services such as Databricks and EMR as well as some of the common architectures. It is titled Moving from Pandas to Spark. Check it out if you are interested to learn more!"
},
{
"code": null,
"e": 895,
"s": 807,
"text": "These steps are for Mac OS X (I am running OS X 10.13 High Sierra), and for Python 3.6."
},
{
"code": null,
"e": 1192,
"s": 895,
"text": "You can install Anaconda and if you already have it, start a new conda environment using conda create -n pyspark_env python=3 This will create a new conda environment with latest version of Python 3 for us to try our mini-PySpark project. Activate the environment with source activate pyspark_env"
},
{
"code": null,
"e": 1393,
"s": 1192,
"text": "You could try using pip to install pyspark but I couldn’t get the pyspark cluster to get started properly. Reading several answers on Stack Overflow and the official documentation, I came across this:"
},
{
"code": null,
"e": 1778,
"s": 1393,
"text": "The Python packaging for Spark is not intended to replace all of the other use cases. This Python packaged version of Spark is suitable for interacting with an existing cluster (be it Spark standalone, YARN, or Mesos) - but does not contain the tools required to setup your own standalone Spark cluster. You can download the full version of Spark from the Apache Spark downloads page."
},
{
"code": null,
"e": 1916,
"s": 1778,
"text": "Using the link above, I went ahead and downloaded the spark-2.3.0-bin-hadoop2.7.tgz and stored the unpacked version in my home directory."
},
{
"code": null,
"e": 2137,
"s": 1916,
"text": "Several instructions recommended using Java 8 or later, and I went ahead and installed Java 10. This actually resulted in several errors such as the following when I tried to run collect() or count() in my Spark cluster:"
},
{
"code": null,
"e": 2291,
"s": 2137,
"text": "py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.: java.lang.IllegalArgumentException"
},
{
"code": null,
"e": 2669,
"s": 2291,
"text": "My initial guess was it had to do something with Py4J installation, which I tried re-installing a couple of times without any help. Not many people were talking about this error, and after reading several Stack Overflow posts, I came across this post which talked about how Spark 2.2.1 was having problems with Java 9 and beyond. The recommended solution was to install Java 8."
},
{
"code": null,
"e": 2719,
"s": 2669,
"text": "So, install Java 8 JDK and move to the next step."
},
{
"code": null,
"e": 2891,
"s": 2719,
"text": "To tell the bash how to find Spark package and Java SDK, add following lines to your .bash_profile (if you are using vim, you can do vim ~/.bash_profile to edit this file)"
},
{
"code": null,
"e": 3041,
"s": 2891,
"text": "export JAVA_HOME=$(/usr/libexec/java_home)export SPARK_HOME=~/spark-2.3.0-bin-hadoop2.7export PATH=$SPARK_HOME/bin:$PATHexport PYSPARK_PYTHON=python3"
},
{
"code": null,
"e": 3225,
"s": 3041,
"text": "These commands tell the bash how to use the recently installed Java and Spark packages. Run source ~/.bash_profile to source this file or open a new terminal to auto-source this file."
},
{
"code": null,
"e": 3271,
"s": 3225,
"text": "Run pyspark command and you will get to this:"
},
{
"code": null,
"e": 3648,
"s": 3271,
"text": "You could use command line to run Spark commands, but it is not very convenient. You can install jupyter notebook using pip install jupyter notebook , and when you run jupyter notebook you can access the Spark cluster in the notebook. You can also just use vim or nano or any other code editor of your choice to write code into python files that you can run from command line."
},
{
"code": null,
"e": 3743,
"s": 3648,
"text": "Run a small and quick program to estimate the value of pi to see your Spark cluster in action!"
},
{
"code": null,
"e": 3977,
"s": 3743,
"text": "import randomNUM_SAMPLES = 100000000def inside(p): x, y = random.random(), random.random() return x*x + y*y < 1count = sc.parallelize(range(0, NUM_SAMPLES)).filter(inside).count()pi = 4 * count / NUM_SAMPLESprint(“Pi is roughly”, pi)"
},
{
"code": null,
"e": 4261,
"s": 3977,
"text": "There are lot of things in PySpark to explore such as Resilient Distributed Datasets or RDDs (update: now DataFrame API is the best way to use Spark, RDDs talk about “how” to do tasks vs Dataframes which talk about “what” — this makes Dataframes much faster and optimized) and MLlib."
}
] |
Attn: Illustrated Attention. Attention illustrated in GIFs and how... | by Raimi Karim | Towards Data Science | (TLDR: animation for attention here)
Changelog:5 Jan 2022 — Fix typos and improve clarity
For decades, Statistical Machine Translation has been the dominant translation model [9], until the birth of Neural Machine Translation (NMT). NMT is an emerging approach to machine translation that attempts to build and train a single, large neural network that reads an input text and outputs a translation [1].
The pioneers of NMT are proposals from Kalchbrenner and Blunsom (2013), Sutskever et. al (2014) and Cho. et. al (2014b), where the more familiar framework is the sequence-to-sequence (seq2seq) learning from Sutskever et. al. This article will be based on the seq2seq framework and how attention can be built on it.
In seq2seq, the idea is to have two recurrent neural networks (RNNs) with an encoder-decoder architecture: read the input words one by one to obtain a vector representation of a fixed dimensionality (encoder), and, conditioned on these inputs, extract the output words one by one using another RNN (decoder). Explanation adapted from [5].
The trouble with seq2seq is that the only information that the decoder receives from the encoder is the last encoder hidden state (the 2 tiny red nodes in Fig. 0.1), a vector representation that is like a numerical summary of an input sequence. So, for a long input text (Fig. 0.2), we unreasonably expect the decoder to use just this one vector representation (hoping that it ‘sufficiently summarises the input sequence’) to output a translation. This might lead to catastrophic forgetting. This paragraph has 100 words. Can you translate this paragraph to another language you know, right after this question mark?
If we can’t, then we shouldn’t be so cruel to the decoder. How about instead of just one vector representation, let’s give the decoder a vector representation from every encoder time step so that it can make well-informed translations? Enter attention.
Attention is an interface between the encoder and decoder that provides the decoder with information from every encoder hidden state (apart from the hidden state in red in Fig. 0.3). With this setting, the model can selectively focus on useful parts of the input sequence and hence, learn the alignment between them. This helps the model to cope effectively with long input sentences [9].
Definition: alignmentAlignment means matching segments of an original text with their corresponding segments of the translation. Definition adapted from here.
There are 2 types of attention, as introduced in [2]. The type of attention that uses all the encoder hidden states is also known as global attention. In contrast, local attention uses only a subset of the encoder hidden states. As the scope of this article is global attention, any references made to “attention” in this article are taken to mean “global attention.”
This article provides a summary of how attention works using animations so that we can understand them without (or after having read a paper or tutorial full of) mathematical notations 😬. As examples, I will be sharing 4 NMT architectures that were designed in the past 5 years. I will also be peppering this article with some intuitions on some concepts so keep a lookout for them!
Contents1. Attention: Overview2. Attention: Examples3. SummaryAppendix: Score Functions
Before we look at how attention is used, allow me to share with you the intuition behind a translation task using the seq2seq model.
Intuition: seq2seqA translator reads the German text from start till the end. Once done, he starts translating to English word by word. It is possible that if the sentence is extremely long, he might have forgotten what he has read in the earlier parts of the text.
So that’s a simple seq2seq model. The step-by-step calculation for the attention layer I am about to go through is a seq2seq+attention model. Here’s a quick intuition on this model.
Intuition: seq2seq + attentionA translator reads the German text while writing down the keywords from the start till the end, after which he starts translating to English. While translating each German word, he makes use of the keywords he has written down.
Attention places different focus on different words by assigning each word with a score. Then, using the softmaxed scores, we aggregate the encoder hidden states using a weighted sum of the encoder hidden states, to get the context vector. The implementations of an attention layer can be broken down into 4 steps.
Step 0: Prepare hidden states.
Let’s first prepare all the available encoder hidden states (green) and the first decoder hidden state (red). In our example, we have 4 encoder hidden states and the current decoder hidden state. (Note: the last consolidated encoder hidden state is fed as input to the first time step of the decoder. The output of the first time step of the decoder is called the first decoder hidden state, as seen below.)
Step 1: Obtain a score for every encoder hidden state.
A score (scalar) is obtained by a score function (also known as the alignment score function [2] or alignment model [1]). In this example, the score function is a dot product between the decoder and encoder hidden states.
See Appendix A for a variety of score functions.
decoder_hidden = [10, 5, 10]encoder_hidden score--------------------- [0, 1, 1] 15 (= 10×0 + 5×1 + 10×1, the dot product) [5, 0, 1] 60 [1, 1, 0] 15 [0, 5, 1] 35
In the above example, we obtain a high attention score of 60 for the encoder hidden state [5, 0, 1]. This means that the next word (next output by the decoder) is going to be heavily influenced by this encoder hidden state.
Step 2: Run all the scores through a softmax layer.
We put the scores to a softmax layer so that the softmaxed scores (scalar) add up to 1. These softmaxed scores represent the attention distribution [3, 10].
encoder_hidden score score^----------------------------- [0, 1, 1] 15 0 [5, 0, 1] 60 1 [1, 1, 0] 15 0 [0, 5, 1] 35 0
Notice that based on the softmaxed score score^, the distribution of attention is only placed on [5, 0, 1] as expected. In reality, these numbers are not binary but a floating-point between 0 and 1.
Step 3: Multiply each encoder hidden state by its softmaxed score.
By multiplying each encoder hidden state with its softmaxed score (scalar), we obtain the alignment vector [2] or the annotation vector [1]. This is exactly the mechanism where alignment takes place.
encoder score score^ alignment---------------------------------[0, 1, 1] 15 0 [0, 0, 0][5, 0, 1] 60 1 [5, 0, 1][1, 1, 0] 15 0 [0, 0, 0][0, 5, 1] 35 0 [0, 0, 0]
Here we see that the alignment for all encoder hidden states except [5, 0, 1] are reduced to 0 due to low attention scores. This means we can expect that the first translated word should match the input word with the [5, 0, 1] embedding.
Step 4: Sum up the alignment vectors.
The alignment vectors are summed up to produce the context vector [1, 2]. A context vector is aggregated information of the alignment vectors from the previous step.
encoder score score^ alignment---------------------------------[0, 1, 1] 15 0 [0, 0, 0][5, 0, 1] 60 1 [5, 0, 1][1, 1, 0] 15 0 [0, 0, 0][0, 5, 1] 35 0 [0, 0, 0]context = [0+5+0+0, 0+0+0+0, 0+1+0+0] = [5, 0, 1]
Step 5: Feed the context vector into the decoder.
The manner this is done depends on the architecture design. Later we will see in the examples in Sections 2a, 2b and 2c how the architectures make use of the context vector for the decoder.
That’s about it! Here’s the entire animation:
Training and inferenceDuring inference, the input to each decoder time step t is the predicted output from decoder time step t-1. During training, the input to each decoder time step t is our ground truth output from decoder time step t-1.
Intuition: How does attention actually work?
Answer: Backpropagation, surprise surprise. Backpropagation will do whatever it takes to ensure that the outputs will be close to the ground truth. This is done by altering the weights in the RNNs and the score function (if any). These weights will affect the encoder hidden states and decoder hidden states, which in turn affect the attention scores.
[Back to top]
We have seen both the seq2seq and the seq2seq+attention architectures in the previous section. In the next sub-sections, let’s examine 3 more seq2seq-based architectures for NMT that implement attention. For completeness, I have also appended their Bilingual Evaluation Understudy (BLEU) scores — a standard metric for evaluating a generated sentence to a reference sentence.
This implementation of attention is one of the founding attention fathers. The authors use the word ‘align’ in the title of the paper “Neural Machine Translation by Learning to Jointly Align and Translate” to mean adjusting the weights that are directly responsible for the score while training the model. The following are things to take note of about the architecture:
The encoder is a bidirectional (forward+backward) gated recurrent unit (BiGRU). The decoder is a GRU whose initial hidden state is a vector modified from the last hidden state from the backward encoder GRU (not shown in the diagram below).The score function in the attention layer is the additive/concat.The input to the next decoder step is the concatenation between the generated word from the previous decoder time step (pink) and the context vector from the current time step (dark green).
The encoder is a bidirectional (forward+backward) gated recurrent unit (BiGRU). The decoder is a GRU whose initial hidden state is a vector modified from the last hidden state from the backward encoder GRU (not shown in the diagram below).
The score function in the attention layer is the additive/concat.
The input to the next decoder step is the concatenation between the generated word from the previous decoder time step (pink) and the context vector from the current time step (dark green).
The authors achieved a BLEU score of 26.75 on the WMT’14 English-to-French dataset.
Intuition: seq2seq with bidirectional encoder + attention
Translator A reads the German text while writing down the keywords. Translator B (who takes on a senior role because he has an extra ability to translate a sentence from reading it backwards) reads the same German text from the last word to the first while jotting down the keywords. These two regularly discuss every word they read thus far. Once done reading this German text, Translator B is then tasked to translate the German sentence to English word by word, based on the discussion and the consolidated keywords that both of them have picked up.
Translator A is the forward RNN, Translator B is the backward RNN.
The authors of Effective Approaches to Attention-based Neural Machine Translation have made it a point to simplify and generalise the architecture from Bahdanau et. al. Here’s how:
The encoder is a two-stacked long short-term memory (LSTM) network. The decoder also has the same architecture, whose initial hidden states are the last encoder hidden states.The score functions they experimented were (i) additive/concat, (ii) dot product, (iii) location-based, and (iv) ‘general’.The concatenation between the output from the current decoder time step and the context vector from the current time step is fed into a feed-forward neural network to give the final output (pink) of the current decoder time step.
The encoder is a two-stacked long short-term memory (LSTM) network. The decoder also has the same architecture, whose initial hidden states are the last encoder hidden states.
The score functions they experimented were (i) additive/concat, (ii) dot product, (iii) location-based, and (iv) ‘general’.
The concatenation between the output from the current decoder time step and the context vector from the current time step is fed into a feed-forward neural network to give the final output (pink) of the current decoder time step.
On the WMT’15 English-to-German, the model achieved a BLEU score of 25.9.
Intuition: seq2seq with 2-layer stacked encoder + attention
Translator A reads the German text while writing down the keywords. Likewise, Translator B (who is more senior than Translator A) also reads the same German text, while jotting down the keywords. Note that the junior Translator A has to report to Translator B at every word they read. Once done reading, both of them translate the sentence to English together word by word, based on the consolidated keywords that they have picked up.
[Back to top]
Because most of us must have used Google Translate in one way or another, I feel that it is imperative to talk about Google’s NMT, which was implemented in 2016. GNMT is a combination of the previous 2 examples we have seen (heavily inspired by the first [1]).
The encoder consists of a stack of 8 LSTMs, where the first is bidirectional (whose outputs are concatenated), and a residual connection exists between outputs from consecutive layers (starting from the 3rd layer). The decoder is a separate stack of 8 unidirectional LSTMs.The score function used is the additive/concat, like in [1].Again, like in [1], the input to the next decoder step is the concatenation between the output from the previous decoder time step (pink) and the context vector from the current time step (dark green).
The encoder consists of a stack of 8 LSTMs, where the first is bidirectional (whose outputs are concatenated), and a residual connection exists between outputs from consecutive layers (starting from the 3rd layer). The decoder is a separate stack of 8 unidirectional LSTMs.
The score function used is the additive/concat, like in [1].
Again, like in [1], the input to the next decoder step is the concatenation between the output from the previous decoder time step (pink) and the context vector from the current time step (dark green).
The model achieves 38.95 BLEU on WMT’14 English-to-French, and 24.17 BLEU on WMT’14 English-to-German.
Intuition: GNMT — seq2seq with 8-stacked encoder (+bidirection+residual connections) + attention
8 translators sit in a column from bottom to top, starting with Translator A, B, ..., H. Every translator reads the same German text. At every word, Translator A shares his/her findings with Translator B, who will improve it and share it with Translator C — repeat this process until we reach Translator H. Also, while reading the German text, Translator H writes down the relevant keywords based on what he knows and the information he has received.
Once everyone is done reading this English text, Translator A is told to translate the first word. First, he tries to recall, then he shares his answer with Translator B, who improves the answer and shares with Translator C — repeat this until we reach Translator H. Translator H then writes the first translation word, based on the keywords he wrote and the answers he got. Repeat this until we get the translation out.
Here’s a quick summary of all the architectures that you have seen in this article:
seq2seq
seq2seq + attention
seq2seq with bidirectional encoder + attention
seq2seq with 2-stacked encoder + attention
GNMT — seq2seq with 8-stacked encoder (+bidirection+residual connections) + attention
That’s it for now! In my next post, I will walk through with you the concept of self-attention and how it has been used in Google’s Transformer and Self-Attention Generative Adversarial Network (SAGAN). Keep an eye on this space!
Below are some of the score functions as compiled by Lilian Weng. The score functions additive/concat and dot product have been mentioned in this article. The idea behind score functions involving the dot product operation (dot product, cosine similarity etc.), is to measure the similarity between two vectors. For feed-forward neural network score functions, the idea is to let the model learn the alignment weights together with the translation.
[Back to top]
[1] Neural Machine Translation by Jointly Learning to Align and Translate (Bahdanau et. al, 2015)
[2] Effective Approaches to Attention-based Neural Machine Translation (Luong et. al, 2015)
[3] Attention Is All You Need (Vaswani et. al, 2017)
[4] Self-Attention GAN (Zhang et. al, 2018)
[5] Sequence to Sequence Learning with Neural Networks (Sutskever et. al, 2014)
[6] TensorFlow’s seq2seq Tutorial with Attention (Tutorial on seq2seq+attention)
[7] Lilian Weng’s Blog on Attention (Great start to attention)
[8] Jay Alammar’s Blog on Seq2Seq with Attention (Great illustrations and worked example on seq2seq+attention)
[9] Google’s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation (Wu et. al, 2016)
Illustrated: Self-Attention
Animated RNN, LSTM and GRU
Line-by-Line Word2Vec Implementation (on word embeddings)
Step-by-Step Tutorial on Linear Regression with Stochastic Gradient Descent
10 Gradient Descent Optimisation Algorithms + Cheat Sheet
Counting No. of Parameters in Deep Learning Models
If you like my content and haven’t already subscribed to Medium, subscribe via my referral link here! NOTE: A portion of your membership fees will be apportioned to me as referral fees.
Special thanks to Derek, William Tjhi, Yu Xuan, Ren Jie, Chris, and Serene for ideas, suggestions and corrections to this article.
Follow me on Twitter @remykarem or LinkedIn. You may also reach out to me via [email protected]. Feel free to visit my website at remykarem.github.io. | [
{
"code": null,
"e": 209,
"s": 172,
"text": "(TLDR: animation for attention here)"
},
{
"code": null,
"e": 262,
"s": 209,
"text": "Changelog:5 Jan 2022 — Fix typos and improve clarity"
},
{
"code": null,
"e": 576,
"s": 262,
"text": "For decades, Statistical Machine Translation has been the dominant translation model [9], until the birth of Neural Machine Translation (NMT). NMT is an emerging approach to machine translation that attempts to build and train a single, large neural network that reads an input text and outputs a translation [1]."
},
{
"code": null,
"e": 891,
"s": 576,
"text": "The pioneers of NMT are proposals from Kalchbrenner and Blunsom (2013), Sutskever et. al (2014) and Cho. et. al (2014b), where the more familiar framework is the sequence-to-sequence (seq2seq) learning from Sutskever et. al. This article will be based on the seq2seq framework and how attention can be built on it."
},
{
"code": null,
"e": 1230,
"s": 891,
"text": "In seq2seq, the idea is to have two recurrent neural networks (RNNs) with an encoder-decoder architecture: read the input words one by one to obtain a vector representation of a fixed dimensionality (encoder), and, conditioned on these inputs, extract the output words one by one using another RNN (decoder). Explanation adapted from [5]."
},
{
"code": null,
"e": 1847,
"s": 1230,
"text": "The trouble with seq2seq is that the only information that the decoder receives from the encoder is the last encoder hidden state (the 2 tiny red nodes in Fig. 0.1), a vector representation that is like a numerical summary of an input sequence. So, for a long input text (Fig. 0.2), we unreasonably expect the decoder to use just this one vector representation (hoping that it ‘sufficiently summarises the input sequence’) to output a translation. This might lead to catastrophic forgetting. This paragraph has 100 words. Can you translate this paragraph to another language you know, right after this question mark?"
},
{
"code": null,
"e": 2100,
"s": 1847,
"text": "If we can’t, then we shouldn’t be so cruel to the decoder. How about instead of just one vector representation, let’s give the decoder a vector representation from every encoder time step so that it can make well-informed translations? Enter attention."
},
{
"code": null,
"e": 2489,
"s": 2100,
"text": "Attention is an interface between the encoder and decoder that provides the decoder with information from every encoder hidden state (apart from the hidden state in red in Fig. 0.3). With this setting, the model can selectively focus on useful parts of the input sequence and hence, learn the alignment between them. This helps the model to cope effectively with long input sentences [9]."
},
{
"code": null,
"e": 2648,
"s": 2489,
"text": "Definition: alignmentAlignment means matching segments of an original text with their corresponding segments of the translation. Definition adapted from here."
},
{
"code": null,
"e": 3016,
"s": 2648,
"text": "There are 2 types of attention, as introduced in [2]. The type of attention that uses all the encoder hidden states is also known as global attention. In contrast, local attention uses only a subset of the encoder hidden states. As the scope of this article is global attention, any references made to “attention” in this article are taken to mean “global attention.”"
},
{
"code": null,
"e": 3399,
"s": 3016,
"text": "This article provides a summary of how attention works using animations so that we can understand them without (or after having read a paper or tutorial full of) mathematical notations 😬. As examples, I will be sharing 4 NMT architectures that were designed in the past 5 years. I will also be peppering this article with some intuitions on some concepts so keep a lookout for them!"
},
{
"code": null,
"e": 3487,
"s": 3399,
"text": "Contents1. Attention: Overview2. Attention: Examples3. SummaryAppendix: Score Functions"
},
{
"code": null,
"e": 3620,
"s": 3487,
"text": "Before we look at how attention is used, allow me to share with you the intuition behind a translation task using the seq2seq model."
},
{
"code": null,
"e": 3886,
"s": 3620,
"text": "Intuition: seq2seqA translator reads the German text from start till the end. Once done, he starts translating to English word by word. It is possible that if the sentence is extremely long, he might have forgotten what he has read in the earlier parts of the text."
},
{
"code": null,
"e": 4068,
"s": 3886,
"text": "So that’s a simple seq2seq model. The step-by-step calculation for the attention layer I am about to go through is a seq2seq+attention model. Here’s a quick intuition on this model."
},
{
"code": null,
"e": 4326,
"s": 4068,
"text": "Intuition: seq2seq + attentionA translator reads the German text while writing down the keywords from the start till the end, after which he starts translating to English. While translating each German word, he makes use of the keywords he has written down."
},
{
"code": null,
"e": 4641,
"s": 4326,
"text": "Attention places different focus on different words by assigning each word with a score. Then, using the softmaxed scores, we aggregate the encoder hidden states using a weighted sum of the encoder hidden states, to get the context vector. The implementations of an attention layer can be broken down into 4 steps."
},
{
"code": null,
"e": 4672,
"s": 4641,
"text": "Step 0: Prepare hidden states."
},
{
"code": null,
"e": 5080,
"s": 4672,
"text": "Let’s first prepare all the available encoder hidden states (green) and the first decoder hidden state (red). In our example, we have 4 encoder hidden states and the current decoder hidden state. (Note: the last consolidated encoder hidden state is fed as input to the first time step of the decoder. The output of the first time step of the decoder is called the first decoder hidden state, as seen below.)"
},
{
"code": null,
"e": 5135,
"s": 5080,
"text": "Step 1: Obtain a score for every encoder hidden state."
},
{
"code": null,
"e": 5357,
"s": 5135,
"text": "A score (scalar) is obtained by a score function (also known as the alignment score function [2] or alignment model [1]). In this example, the score function is a dot product between the decoder and encoder hidden states."
},
{
"code": null,
"e": 5406,
"s": 5357,
"text": "See Appendix A for a variety of score functions."
},
{
"code": null,
"e": 5600,
"s": 5406,
"text": "decoder_hidden = [10, 5, 10]encoder_hidden score--------------------- [0, 1, 1] 15 (= 10×0 + 5×1 + 10×1, the dot product) [5, 0, 1] 60 [1, 1, 0] 15 [0, 5, 1] 35"
},
{
"code": null,
"e": 5824,
"s": 5600,
"text": "In the above example, we obtain a high attention score of 60 for the encoder hidden state [5, 0, 1]. This means that the next word (next output by the decoder) is going to be heavily influenced by this encoder hidden state."
},
{
"code": null,
"e": 5876,
"s": 5824,
"text": "Step 2: Run all the scores through a softmax layer."
},
{
"code": null,
"e": 6033,
"s": 5876,
"text": "We put the scores to a softmax layer so that the softmaxed scores (scalar) add up to 1. These softmaxed scores represent the attention distribution [3, 10]."
},
{
"code": null,
"e": 6208,
"s": 6033,
"text": "encoder_hidden score score^----------------------------- [0, 1, 1] 15 0 [5, 0, 1] 60 1 [1, 1, 0] 15 0 [0, 5, 1] 35 0"
},
{
"code": null,
"e": 6407,
"s": 6208,
"text": "Notice that based on the softmaxed score score^, the distribution of attention is only placed on [5, 0, 1] as expected. In reality, these numbers are not binary but a floating-point between 0 and 1."
},
{
"code": null,
"e": 6474,
"s": 6407,
"text": "Step 3: Multiply each encoder hidden state by its softmaxed score."
},
{
"code": null,
"e": 6674,
"s": 6474,
"text": "By multiplying each encoder hidden state with its softmaxed score (scalar), we obtain the alignment vector [2] or the annotation vector [1]. This is exactly the mechanism where alignment takes place."
},
{
"code": null,
"e": 6873,
"s": 6674,
"text": "encoder score score^ alignment---------------------------------[0, 1, 1] 15 0 [0, 0, 0][5, 0, 1] 60 1 [5, 0, 1][1, 1, 0] 15 0 [0, 0, 0][0, 5, 1] 35 0 [0, 0, 0]"
},
{
"code": null,
"e": 7111,
"s": 6873,
"text": "Here we see that the alignment for all encoder hidden states except [5, 0, 1] are reduced to 0 due to low attention scores. This means we can expect that the first translated word should match the input word with the [5, 0, 1] embedding."
},
{
"code": null,
"e": 7149,
"s": 7111,
"text": "Step 4: Sum up the alignment vectors."
},
{
"code": null,
"e": 7315,
"s": 7149,
"text": "The alignment vectors are summed up to produce the context vector [1, 2]. A context vector is aggregated information of the alignment vectors from the previous step."
},
{
"code": null,
"e": 7555,
"s": 7315,
"text": "encoder score score^ alignment---------------------------------[0, 1, 1] 15 0 [0, 0, 0][5, 0, 1] 60 1 [5, 0, 1][1, 1, 0] 15 0 [0, 0, 0][0, 5, 1] 35 0 [0, 0, 0]context = [0+5+0+0, 0+0+0+0, 0+1+0+0] = [5, 0, 1]"
},
{
"code": null,
"e": 7605,
"s": 7555,
"text": "Step 5: Feed the context vector into the decoder."
},
{
"code": null,
"e": 7795,
"s": 7605,
"text": "The manner this is done depends on the architecture design. Later we will see in the examples in Sections 2a, 2b and 2c how the architectures make use of the context vector for the decoder."
},
{
"code": null,
"e": 7841,
"s": 7795,
"text": "That’s about it! Here’s the entire animation:"
},
{
"code": null,
"e": 8081,
"s": 7841,
"text": "Training and inferenceDuring inference, the input to each decoder time step t is the predicted output from decoder time step t-1. During training, the input to each decoder time step t is our ground truth output from decoder time step t-1."
},
{
"code": null,
"e": 8126,
"s": 8081,
"text": "Intuition: How does attention actually work?"
},
{
"code": null,
"e": 8478,
"s": 8126,
"text": "Answer: Backpropagation, surprise surprise. Backpropagation will do whatever it takes to ensure that the outputs will be close to the ground truth. This is done by altering the weights in the RNNs and the score function (if any). These weights will affect the encoder hidden states and decoder hidden states, which in turn affect the attention scores."
},
{
"code": null,
"e": 8492,
"s": 8478,
"text": "[Back to top]"
},
{
"code": null,
"e": 8868,
"s": 8492,
"text": "We have seen both the seq2seq and the seq2seq+attention architectures in the previous section. In the next sub-sections, let’s examine 3 more seq2seq-based architectures for NMT that implement attention. For completeness, I have also appended their Bilingual Evaluation Understudy (BLEU) scores — a standard metric for evaluating a generated sentence to a reference sentence."
},
{
"code": null,
"e": 9239,
"s": 8868,
"text": "This implementation of attention is one of the founding attention fathers. The authors use the word ‘align’ in the title of the paper “Neural Machine Translation by Learning to Jointly Align and Translate” to mean adjusting the weights that are directly responsible for the score while training the model. The following are things to take note of about the architecture:"
},
{
"code": null,
"e": 9733,
"s": 9239,
"text": "The encoder is a bidirectional (forward+backward) gated recurrent unit (BiGRU). The decoder is a GRU whose initial hidden state is a vector modified from the last hidden state from the backward encoder GRU (not shown in the diagram below).The score function in the attention layer is the additive/concat.The input to the next decoder step is the concatenation between the generated word from the previous decoder time step (pink) and the context vector from the current time step (dark green)."
},
{
"code": null,
"e": 9973,
"s": 9733,
"text": "The encoder is a bidirectional (forward+backward) gated recurrent unit (BiGRU). The decoder is a GRU whose initial hidden state is a vector modified from the last hidden state from the backward encoder GRU (not shown in the diagram below)."
},
{
"code": null,
"e": 10039,
"s": 9973,
"text": "The score function in the attention layer is the additive/concat."
},
{
"code": null,
"e": 10229,
"s": 10039,
"text": "The input to the next decoder step is the concatenation between the generated word from the previous decoder time step (pink) and the context vector from the current time step (dark green)."
},
{
"code": null,
"e": 10313,
"s": 10229,
"text": "The authors achieved a BLEU score of 26.75 on the WMT’14 English-to-French dataset."
},
{
"code": null,
"e": 10371,
"s": 10313,
"text": "Intuition: seq2seq with bidirectional encoder + attention"
},
{
"code": null,
"e": 10924,
"s": 10371,
"text": "Translator A reads the German text while writing down the keywords. Translator B (who takes on a senior role because he has an extra ability to translate a sentence from reading it backwards) reads the same German text from the last word to the first while jotting down the keywords. These two regularly discuss every word they read thus far. Once done reading this German text, Translator B is then tasked to translate the German sentence to English word by word, based on the discussion and the consolidated keywords that both of them have picked up."
},
{
"code": null,
"e": 10991,
"s": 10924,
"text": "Translator A is the forward RNN, Translator B is the backward RNN."
},
{
"code": null,
"e": 11172,
"s": 10991,
"text": "The authors of Effective Approaches to Attention-based Neural Machine Translation have made it a point to simplify and generalise the architecture from Bahdanau et. al. Here’s how:"
},
{
"code": null,
"e": 11700,
"s": 11172,
"text": "The encoder is a two-stacked long short-term memory (LSTM) network. The decoder also has the same architecture, whose initial hidden states are the last encoder hidden states.The score functions they experimented were (i) additive/concat, (ii) dot product, (iii) location-based, and (iv) ‘general’.The concatenation between the output from the current decoder time step and the context vector from the current time step is fed into a feed-forward neural network to give the final output (pink) of the current decoder time step."
},
{
"code": null,
"e": 11876,
"s": 11700,
"text": "The encoder is a two-stacked long short-term memory (LSTM) network. The decoder also has the same architecture, whose initial hidden states are the last encoder hidden states."
},
{
"code": null,
"e": 12000,
"s": 11876,
"text": "The score functions they experimented were (i) additive/concat, (ii) dot product, (iii) location-based, and (iv) ‘general’."
},
{
"code": null,
"e": 12230,
"s": 12000,
"text": "The concatenation between the output from the current decoder time step and the context vector from the current time step is fed into a feed-forward neural network to give the final output (pink) of the current decoder time step."
},
{
"code": null,
"e": 12304,
"s": 12230,
"text": "On the WMT’15 English-to-German, the model achieved a BLEU score of 25.9."
},
{
"code": null,
"e": 12364,
"s": 12304,
"text": "Intuition: seq2seq with 2-layer stacked encoder + attention"
},
{
"code": null,
"e": 12799,
"s": 12364,
"text": "Translator A reads the German text while writing down the keywords. Likewise, Translator B (who is more senior than Translator A) also reads the same German text, while jotting down the keywords. Note that the junior Translator A has to report to Translator B at every word they read. Once done reading, both of them translate the sentence to English together word by word, based on the consolidated keywords that they have picked up."
},
{
"code": null,
"e": 12813,
"s": 12799,
"text": "[Back to top]"
},
{
"code": null,
"e": 13074,
"s": 12813,
"text": "Because most of us must have used Google Translate in one way or another, I feel that it is imperative to talk about Google’s NMT, which was implemented in 2016. GNMT is a combination of the previous 2 examples we have seen (heavily inspired by the first [1])."
},
{
"code": null,
"e": 13609,
"s": 13074,
"text": "The encoder consists of a stack of 8 LSTMs, where the first is bidirectional (whose outputs are concatenated), and a residual connection exists between outputs from consecutive layers (starting from the 3rd layer). The decoder is a separate stack of 8 unidirectional LSTMs.The score function used is the additive/concat, like in [1].Again, like in [1], the input to the next decoder step is the concatenation between the output from the previous decoder time step (pink) and the context vector from the current time step (dark green)."
},
{
"code": null,
"e": 13883,
"s": 13609,
"text": "The encoder consists of a stack of 8 LSTMs, where the first is bidirectional (whose outputs are concatenated), and a residual connection exists between outputs from consecutive layers (starting from the 3rd layer). The decoder is a separate stack of 8 unidirectional LSTMs."
},
{
"code": null,
"e": 13944,
"s": 13883,
"text": "The score function used is the additive/concat, like in [1]."
},
{
"code": null,
"e": 14146,
"s": 13944,
"text": "Again, like in [1], the input to the next decoder step is the concatenation between the output from the previous decoder time step (pink) and the context vector from the current time step (dark green)."
},
{
"code": null,
"e": 14249,
"s": 14146,
"text": "The model achieves 38.95 BLEU on WMT’14 English-to-French, and 24.17 BLEU on WMT’14 English-to-German."
},
{
"code": null,
"e": 14346,
"s": 14249,
"text": "Intuition: GNMT — seq2seq with 8-stacked encoder (+bidirection+residual connections) + attention"
},
{
"code": null,
"e": 14797,
"s": 14346,
"text": "8 translators sit in a column from bottom to top, starting with Translator A, B, ..., H. Every translator reads the same German text. At every word, Translator A shares his/her findings with Translator B, who will improve it and share it with Translator C — repeat this process until we reach Translator H. Also, while reading the German text, Translator H writes down the relevant keywords based on what he knows and the information he has received."
},
{
"code": null,
"e": 15218,
"s": 14797,
"text": "Once everyone is done reading this English text, Translator A is told to translate the first word. First, he tries to recall, then he shares his answer with Translator B, who improves the answer and shares with Translator C — repeat this until we reach Translator H. Translator H then writes the first translation word, based on the keywords he wrote and the answers he got. Repeat this until we get the translation out."
},
{
"code": null,
"e": 15302,
"s": 15218,
"text": "Here’s a quick summary of all the architectures that you have seen in this article:"
},
{
"code": null,
"e": 15310,
"s": 15302,
"text": "seq2seq"
},
{
"code": null,
"e": 15330,
"s": 15310,
"text": "seq2seq + attention"
},
{
"code": null,
"e": 15377,
"s": 15330,
"text": "seq2seq with bidirectional encoder + attention"
},
{
"code": null,
"e": 15420,
"s": 15377,
"text": "seq2seq with 2-stacked encoder + attention"
},
{
"code": null,
"e": 15506,
"s": 15420,
"text": "GNMT — seq2seq with 8-stacked encoder (+bidirection+residual connections) + attention"
},
{
"code": null,
"e": 15736,
"s": 15506,
"text": "That’s it for now! In my next post, I will walk through with you the concept of self-attention and how it has been used in Google’s Transformer and Self-Attention Generative Adversarial Network (SAGAN). Keep an eye on this space!"
},
{
"code": null,
"e": 16185,
"s": 15736,
"text": "Below are some of the score functions as compiled by Lilian Weng. The score functions additive/concat and dot product have been mentioned in this article. The idea behind score functions involving the dot product operation (dot product, cosine similarity etc.), is to measure the similarity between two vectors. For feed-forward neural network score functions, the idea is to let the model learn the alignment weights together with the translation."
},
{
"code": null,
"e": 16199,
"s": 16185,
"text": "[Back to top]"
},
{
"code": null,
"e": 16297,
"s": 16199,
"text": "[1] Neural Machine Translation by Jointly Learning to Align and Translate (Bahdanau et. al, 2015)"
},
{
"code": null,
"e": 16389,
"s": 16297,
"text": "[2] Effective Approaches to Attention-based Neural Machine Translation (Luong et. al, 2015)"
},
{
"code": null,
"e": 16442,
"s": 16389,
"text": "[3] Attention Is All You Need (Vaswani et. al, 2017)"
},
{
"code": null,
"e": 16486,
"s": 16442,
"text": "[4] Self-Attention GAN (Zhang et. al, 2018)"
},
{
"code": null,
"e": 16566,
"s": 16486,
"text": "[5] Sequence to Sequence Learning with Neural Networks (Sutskever et. al, 2014)"
},
{
"code": null,
"e": 16647,
"s": 16566,
"text": "[6] TensorFlow’s seq2seq Tutorial with Attention (Tutorial on seq2seq+attention)"
},
{
"code": null,
"e": 16710,
"s": 16647,
"text": "[7] Lilian Weng’s Blog on Attention (Great start to attention)"
},
{
"code": null,
"e": 16821,
"s": 16710,
"text": "[8] Jay Alammar’s Blog on Seq2Seq with Attention (Great illustrations and worked example on seq2seq+attention)"
},
{
"code": null,
"e": 16942,
"s": 16821,
"text": "[9] Google’s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation (Wu et. al, 2016)"
},
{
"code": null,
"e": 16970,
"s": 16942,
"text": "Illustrated: Self-Attention"
},
{
"code": null,
"e": 16997,
"s": 16970,
"text": "Animated RNN, LSTM and GRU"
},
{
"code": null,
"e": 17055,
"s": 16997,
"text": "Line-by-Line Word2Vec Implementation (on word embeddings)"
},
{
"code": null,
"e": 17131,
"s": 17055,
"text": "Step-by-Step Tutorial on Linear Regression with Stochastic Gradient Descent"
},
{
"code": null,
"e": 17189,
"s": 17131,
"text": "10 Gradient Descent Optimisation Algorithms + Cheat Sheet"
},
{
"code": null,
"e": 17240,
"s": 17189,
"text": "Counting No. of Parameters in Deep Learning Models"
},
{
"code": null,
"e": 17426,
"s": 17240,
"text": "If you like my content and haven’t already subscribed to Medium, subscribe via my referral link here! NOTE: A portion of your membership fees will be apportioned to me as referral fees."
},
{
"code": null,
"e": 17557,
"s": 17426,
"text": "Special thanks to Derek, William Tjhi, Yu Xuan, Ren Jie, Chris, and Serene for ideas, suggestions and corrections to this article."
}
] |
Tryit Editor v3.7 | Tryit: Audio autoplay and muted | [] |
How to count unique elements in the array using java? | The interface Set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false −
If you try to add all the elements of the array to a Set, it accepts only unique elements −
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class CountingUniqueElements {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created ::");
int size = sc.nextInt();
int count = 0;
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i = 0; i<size; i++) {
myArray[i] = sc.nextInt();
}
System.out.println("The array created is :: "+Arrays.toString(myArray));
System.out.println("indices of duplicate elements in the array are elements :: ");
Set set = new HashSet();
for(int i = 0; i<myArray.length; i++) {
if(set.add(myArray[i])) {
count++;
System.out.println("Index :: "+i+" Element :: "+myArray[i]);
}
}
}
}
Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
45
45
45
69
32
69
The array created is :: [45, 45, 45, 69, 32, 69]
indices of duplicate elements in the array are elements ::
Index :: 0 Element :: 45
Index :: 3 Element :: 69
Index :: 4 Element :: 32 | [
{
"code": null,
"e": 1265,
"s": 1062,
"text": "The interface Set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false −"
},
{
"code": null,
"e": 1357,
"s": 1265,
"text": "If you try to add all the elements of the array to a Set, it accepts only unique elements −"
},
{
"code": null,
"e": 2313,
"s": 1357,
"text": "import java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Scanner;\nimport java.util.Set;\n\npublic class CountingUniqueElements {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created ::\");\n \n int size = sc.nextInt();\n int count = 0;\n int[] myArray = new int[size];\n \n System.out.println(\"Enter the elements of the array ::\");\n\n for(int i = 0; i<size; i++) {\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"The array created is :: \"+Arrays.toString(myArray));\n System.out.println(\"indices of duplicate elements in the array are elements :: \");\n Set set = new HashSet();\n\n for(int i = 0; i<myArray.length; i++) {\n if(set.add(myArray[i])) {\n count++;\n System.out.println(\"Index :: \"+i+\" Element :: \"+myArray[i]);\n }\n }\n }\n}"
},
{
"code": null,
"e": 2605,
"s": 2313,
"text": "Enter the size of the array that is to be created ::\n6\nEnter the elements of the array ::\n45\n45\n45\n69\n32\n69\nThe array created is :: [45, 45, 45, 69, 32, 69]\nindices of duplicate elements in the array are elements ::\nIndex :: 0 Element :: 45\nIndex :: 3 Element :: 69\nIndex :: 4 Element :: 32\n"
}
] |
HTML - Entities | Some characters are reserved in HTML and they have special meaning when used in HTML document. For example, you cannot use the greater than and less than signs or angle brackets within your HTML text because the browser will treat them differently and will try to draw a meaning related to HTML tag.
HTML processors must support following five special characters listed in the table that follows.
If you want to write <div id = "character"> as a code then you will have to write as follows −
<!DOCTYPE html>
<html>
<head>
<title>HTML Entities</title>
</head>
<body>
<div id = "character">
</body>
</html>
This will produce the following result −
There is also a long list of special characters in HTML 4.0. In order for these to appear in your document, you can use either the numerical codes or the entity names. For example, to insert a copyright symbol you can use either of the following −
© 2007
or
© 2007
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2674,
"s": 2374,
"text": "Some characters are reserved in HTML and they have special meaning when used in HTML document. For example, you cannot use the greater than and less than signs or angle brackets within your HTML text because the browser will treat them differently and will try to draw a meaning related to HTML tag."
},
{
"code": null,
"e": 2771,
"s": 2674,
"text": "HTML processors must support following five special characters listed in the table that follows."
},
{
"code": null,
"e": 2866,
"s": 2771,
"text": "If you want to write <div id = \"character\"> as a code then you will have to write as follows −"
},
{
"code": null,
"e": 3012,
"s": 2866,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Entities</title>\n </head>\n\n <body>\n <div id = \"character\">\n </body>\n\n</html>"
},
{
"code": null,
"e": 3053,
"s": 3012,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3301,
"s": 3053,
"text": "There is also a long list of special characters in HTML 4.0. In order for these to appear in your document, you can use either the numerical codes or the entity names. For example, to insert a copyright symbol you can use either of the following −"
},
{
"code": null,
"e": 3329,
"s": 3301,
"text": "© 2007\nor\n© 2007\n"
},
{
"code": null,
"e": 3362,
"s": 3329,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3376,
"s": 3362,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3411,
"s": 3376,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3425,
"s": 3411,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3460,
"s": 3425,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3477,
"s": 3460,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3512,
"s": 3477,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3543,
"s": 3512,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3576,
"s": 3543,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3607,
"s": 3576,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3642,
"s": 3607,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3673,
"s": 3642,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3680,
"s": 3673,
"text": " Print"
},
{
"code": null,
"e": 3691,
"s": 3680,
"text": " Add Notes"
}
] |
Cordova - Plugman | Cordova Plugman is a useful command line tool for installing and managing plugins. You should use plugman if your app needs to run on one specific platform. If you want to create a cross-platform app you should use cordova-cli which will modify plugins for different platforms.
Open the command prompt window and run the following code snippet to install plugman.
C:\Users\username\Desktop\CordovaProject>npm install -g plugman
To understand how to install the Cordova plugin using plugman, we will use the Camera plugin as an example.
C:\Users\username\Desktop\CordovaProject>plugman
install --platform android --project platforms\android
--plugin cordova-plugin-camera
plugman uninstall --platform android --project platforms\android
--plugin cordova-plugin-camera
We need to consider three parameters as shown above.
--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10).
--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10).
--project − path where the project is built. In our case, it is platforms\android directory.
--project − path where the project is built. In our case, it is platforms\android directory.
--plugin − the plugin that we want to install.
--plugin − the plugin that we want to install.
If you set valid parameters, the command prompt window should display the following output.
You can use the uninstall method in similar way.
C:\Users\username\Desktop\CordovaProject>plugman uninstall
--platform android --project platforms\android --plugin cordova-plugin-camera
The command prompt console will display the following output.
Plugman offers some additional methods that can be used. The methods are listed in the following table.
install
Used for installing Cordova plugins.
uninstall
Used for uninstalling Cordova plugins.
fetch
Used for copying Cordova plugin to specific location.
prepare
Used for updating configuration file to help JS module support.
adduser
Used for adding user account to the registry.
publish
Used for publishing plugin to the registry.
unpublish
Used for unpublishing plugin from the registry.
search
Used for searching the plugins in the registry.
config
Used for registry settings configuration.
create
Used for creating custom plugin.
platform
Used for adding or removing platform from the custom created plugin.
If you are stuck, you can always use the plugman -help command. The version can be checked by using plugman -v. To search for the plugin, you can use plugman search and finally you can change the plugin registry by using the plugman config set registry command.
Since Cordova is used for cross platform development, in our subsequent chapters we will use Cordova CLI instead of Plugman for installing plugins.
45 Lectures
2 hours
Skillbakerystudios
16 Lectures
1 hours
Nilay Mehta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2458,
"s": 2180,
"text": "Cordova Plugman is a useful command line tool for installing and managing plugins. You should use plugman if your app needs to run on one specific platform. If you want to create a cross-platform app you should use cordova-cli which will modify plugins for different platforms."
},
{
"code": null,
"e": 2544,
"s": 2458,
"text": "Open the command prompt window and run the following code snippet to install plugman."
},
{
"code": null,
"e": 2609,
"s": 2544,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>npm install -g plugman\n"
},
{
"code": null,
"e": 2717,
"s": 2609,
"text": "To understand how to install the Cordova plugin using plugman, we will use the Camera plugin as an example."
},
{
"code": null,
"e": 2969,
"s": 2717,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>plugman \n install --platform android --project platforms\\android \n --plugin cordova-plugin-camera \n plugman uninstall --platform android --project platforms\\android \n --plugin cordova-plugin-camera \n"
},
{
"code": null,
"e": 3022,
"s": 2969,
"text": "We need to consider three parameters as shown above."
},
{
"code": null,
"e": 3112,
"s": 3022,
"text": "--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10)."
},
{
"code": null,
"e": 3202,
"s": 3112,
"text": "--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10)."
},
{
"code": null,
"e": 3296,
"s": 3202,
"text": "--project − path where the project is built. In our case, it is platforms\\android directory."
},
{
"code": null,
"e": 3390,
"s": 3296,
"text": "--project − path where the project is built. In our case, it is platforms\\android directory."
},
{
"code": null,
"e": 3437,
"s": 3390,
"text": "--plugin − the plugin that we want to install."
},
{
"code": null,
"e": 3484,
"s": 3437,
"text": "--plugin − the plugin that we want to install."
},
{
"code": null,
"e": 3576,
"s": 3484,
"text": "If you set valid parameters, the command prompt window should display the following output."
},
{
"code": null,
"e": 3625,
"s": 3576,
"text": "You can use the uninstall method in similar way."
},
{
"code": null,
"e": 3769,
"s": 3625,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>plugman uninstall \n --platform android --project platforms\\android --plugin cordova-plugin-camera \n"
},
{
"code": null,
"e": 3831,
"s": 3769,
"text": "The command prompt console will display the following output."
},
{
"code": null,
"e": 3935,
"s": 3831,
"text": "Plugman offers some additional methods that can be used. The methods are listed in the following table."
},
{
"code": null,
"e": 3943,
"s": 3935,
"text": "install"
},
{
"code": null,
"e": 3980,
"s": 3943,
"text": "Used for installing Cordova plugins."
},
{
"code": null,
"e": 3990,
"s": 3980,
"text": "uninstall"
},
{
"code": null,
"e": 4029,
"s": 3990,
"text": "Used for uninstalling Cordova plugins."
},
{
"code": null,
"e": 4035,
"s": 4029,
"text": "fetch"
},
{
"code": null,
"e": 4089,
"s": 4035,
"text": "Used for copying Cordova plugin to specific location."
},
{
"code": null,
"e": 4097,
"s": 4089,
"text": "prepare"
},
{
"code": null,
"e": 4161,
"s": 4097,
"text": "Used for updating configuration file to help JS module support."
},
{
"code": null,
"e": 4169,
"s": 4161,
"text": "adduser"
},
{
"code": null,
"e": 4215,
"s": 4169,
"text": "Used for adding user account to the registry."
},
{
"code": null,
"e": 4223,
"s": 4215,
"text": "publish"
},
{
"code": null,
"e": 4267,
"s": 4223,
"text": "Used for publishing plugin to the registry."
},
{
"code": null,
"e": 4277,
"s": 4267,
"text": "unpublish"
},
{
"code": null,
"e": 4325,
"s": 4277,
"text": "Used for unpublishing plugin from the registry."
},
{
"code": null,
"e": 4332,
"s": 4325,
"text": "search"
},
{
"code": null,
"e": 4380,
"s": 4332,
"text": "Used for searching the plugins in the registry."
},
{
"code": null,
"e": 4387,
"s": 4380,
"text": "config"
},
{
"code": null,
"e": 4429,
"s": 4387,
"text": "Used for registry settings configuration."
},
{
"code": null,
"e": 4436,
"s": 4429,
"text": "create"
},
{
"code": null,
"e": 4469,
"s": 4436,
"text": "Used for creating custom plugin."
},
{
"code": null,
"e": 4478,
"s": 4469,
"text": "platform"
},
{
"code": null,
"e": 4547,
"s": 4478,
"text": "Used for adding or removing platform from the custom created plugin."
},
{
"code": null,
"e": 4809,
"s": 4547,
"text": "If you are stuck, you can always use the plugman -help command. The version can be checked by using plugman -v. To search for the plugin, you can use plugman search and finally you can change the plugin registry by using the plugman config set registry command."
},
{
"code": null,
"e": 4957,
"s": 4809,
"text": "Since Cordova is used for cross platform development, in our subsequent chapters we will use Cordova CLI instead of Plugman for installing plugins."
},
{
"code": null,
"e": 4990,
"s": 4957,
"text": "\n 45 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5010,
"s": 4990,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5043,
"s": 5010,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5056,
"s": 5043,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5063,
"s": 5056,
"text": " Print"
},
{
"code": null,
"e": 5074,
"s": 5063,
"text": " Add Notes"
}
] |
How to check if a Python string contains only digits? | There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. You can call it as follows −
print("12345".isdigit())
print("12345a".isdigit())
True
False
You can also use regexes for the same result. For matching only digits, we can call the re.match(regex, string) using the regex: "^[0-9]+$".
import re
print(bool(re.match('^[0-9]+$', '123abc')))
print (bool(re.match('^[0-9]+$', '123')))
False
True
re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool(). | [
{
"code": null,
"e": 1257,
"s": 1062,
"text": "There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. You can call it as follows −"
},
{
"code": null,
"e": 1308,
"s": 1257,
"text": "print(\"12345\".isdigit())\nprint(\"12345a\".isdigit())"
},
{
"code": null,
"e": 1319,
"s": 1308,
"text": "True\nFalse"
},
{
"code": null,
"e": 1461,
"s": 1319,
"text": "You can also use regexes for the same result. For matching only digits, we can call the re.match(regex, string) using the regex: \"^[0-9]+$\". "
},
{
"code": null,
"e": 1557,
"s": 1461,
"text": "import re\nprint(bool(re.match('^[0-9]+$', '123abc')))\nprint (bool(re.match('^[0-9]+$', '123')))"
},
{
"code": null,
"e": 1568,
"s": 1557,
"text": "False\nTrue"
},
{
"code": null,
"e": 1675,
"s": 1568,
"text": "re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool()."
}
] |
AWK - Loops | This chapter explains AWK's loops with suitable example. Loops are used to execute a set of actions in a repeated manner. The loop execution continues as long as the loop condition is true.
The syntax of for loop is −
for (initialization; condition; increment/decrement)
action
Initially, the for statement performs initialization action, then it checks the condition. If the condition is true, it executes actions, thereafter it performs increment or decrement operation. The loop execution continues as long as the condition is true. For instance, the following example prints 1 to 5 using for loop −
[jerry]$ awk 'BEGIN { for (i = 1; i <= 5; ++i) print i }'
On executing this code, you get the following result −
1
2
3
4
5
The while loop keeps executing the action until a particular logical condition evaluates to true. Here is the syntax of while loop −
while (condition)
action
AWK first checks the condition; if the condition is true, it executes the action. This process repeats as long as the loop condition evaluates to true. For instance, the following example prints 1 to 5 using while loop −
[jerry]$ awk 'BEGIN {i = 1; while (i < 6) { print i; ++i } }'
On executing this code, you get the following result −
1
2
3
4
5
The do-while loop is similar to the while loop, except that the test condition is evaluated at the end of the loop. Here is the syntax of do-whileloop −
do
action
while (condition)
In a do-while loop, the action statement gets executed at least once even when the condition statement evaluates to false. For instance, the following example prints 1 to 5 numbers using do-while loop −
[jerry]$ awk 'BEGIN {i = 1; do { print i; ++i } while (i < 6) }'
On executing this code, you get the following result −
1
2
3
4
5
As its name suggests, it is used to end the loop execution. Here is an example which ends the loop when the sum becomes greater than 50.
[jerry]$ awk 'BEGIN {
sum = 0; for (i = 0; i < 20; ++i) {
sum += i; if (sum > 50) break; else print "Sum =", sum
}
}'
On executing this code, you get the following result −
Sum = 0
Sum = 1
Sum = 3
Sum = 6
Sum = 10
Sum = 15
Sum = 21
Sum = 28
Sum = 36
Sum = 45
The continue statement is used inside a loop to skip to the next iteration of the loop. It is useful when you wish to skip the processing of some data inside the loop. For instance, the following example uses continue statement to print the even numbers between 1 to 20.
[jerry]$ awk 'BEGIN {
for (i = 1; i <= 20; ++i) {
if (i % 2 == 0) print i ; else continue
}
}'
On executing this code, you get the following result −
2
4
6
8
10
12
14
16
18
20
It is used to stop the execution of the script. It accepts an integer as an argument which is the exit status code for AWK process. If no argument is supplied, exit returns status zero. Here is an example that stops the execution when the sum becomes greater than 50.
[jerry]$ awk 'BEGIN {
sum = 0; for (i = 0; i < 20; ++i) {
sum += i; if (sum > 50) exit(10); else print "Sum =", sum
}
}'
On executing this code, you get the following result −
Sum = 0
Sum = 1
Sum = 3
Sum = 6
Sum = 10
Sum = 15
Sum = 21
Sum = 28
Sum = 36
Sum = 45
Let us check the return status of the script.
[jerry]$ echo $?
On executing this code, you get the following result −
10
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2047,
"s": 1857,
"text": "This chapter explains AWK's loops with suitable example. Loops are used to execute a set of actions in a repeated manner. The loop execution continues as long as the loop condition is true."
},
{
"code": null,
"e": 2075,
"s": 2047,
"text": "The syntax of for loop is −"
},
{
"code": null,
"e": 2139,
"s": 2075,
"text": "for (initialization; condition; increment/decrement)\n action\n"
},
{
"code": null,
"e": 2464,
"s": 2139,
"text": "Initially, the for statement performs initialization action, then it checks the condition. If the condition is true, it executes actions, thereafter it performs increment or decrement operation. The loop execution continues as long as the condition is true. For instance, the following example prints 1 to 5 using for loop −"
},
{
"code": null,
"e": 2522,
"s": 2464,
"text": "[jerry]$ awk 'BEGIN { for (i = 1; i <= 5; ++i) print i }'"
},
{
"code": null,
"e": 2577,
"s": 2522,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2588,
"s": 2577,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 2721,
"s": 2588,
"text": "The while loop keeps executing the action until a particular logical condition evaluates to true. Here is the syntax of while loop −"
},
{
"code": null,
"e": 2750,
"s": 2721,
"text": "while (condition)\n action\n"
},
{
"code": null,
"e": 2971,
"s": 2750,
"text": "AWK first checks the condition; if the condition is true, it executes the action. This process repeats as long as the loop condition evaluates to true. For instance, the following example prints 1 to 5 using while loop −"
},
{
"code": null,
"e": 3033,
"s": 2971,
"text": "[jerry]$ awk 'BEGIN {i = 1; while (i < 6) { print i; ++i } }'"
},
{
"code": null,
"e": 3088,
"s": 3033,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 3099,
"s": 3088,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 3252,
"s": 3099,
"text": "The do-while loop is similar to the while loop, except that the test condition is evaluated at the end of the loop. Here is the syntax of do-whileloop −"
},
{
"code": null,
"e": 3284,
"s": 3252,
"text": "do\n action\nwhile (condition)\n"
},
{
"code": null,
"e": 3487,
"s": 3284,
"text": "In a do-while loop, the action statement gets executed at least once even when the condition statement evaluates to false. For instance, the following example prints 1 to 5 numbers using do-while loop −"
},
{
"code": null,
"e": 3552,
"s": 3487,
"text": "[jerry]$ awk 'BEGIN {i = 1; do { print i; ++i } while (i < 6) }'"
},
{
"code": null,
"e": 3607,
"s": 3552,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 3618,
"s": 3607,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 3755,
"s": 3618,
"text": "As its name suggests, it is used to end the loop execution. Here is an example which ends the loop when the sum becomes greater than 50."
},
{
"code": null,
"e": 3888,
"s": 3755,
"text": "[jerry]$ awk 'BEGIN {\n sum = 0; for (i = 0; i < 20; ++i) { \n sum += i; if (sum > 50) break; else print \"Sum =\", sum \n } \n}'"
},
{
"code": null,
"e": 3943,
"s": 3888,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 4030,
"s": 3943,
"text": "Sum = 0\nSum = 1\nSum = 3\nSum = 6\nSum = 10\nSum = 15\nSum = 21\nSum = 28\nSum = 36\nSum = 45\n"
},
{
"code": null,
"e": 4301,
"s": 4030,
"text": "The continue statement is used inside a loop to skip to the next iteration of the loop. It is useful when you wish to skip the processing of some data inside the loop. For instance, the following example uses continue statement to print the even numbers between 1 to 20."
},
{
"code": null,
"e": 4409,
"s": 4301,
"text": "[jerry]$ awk 'BEGIN {\n for (i = 1; i <= 20; ++i) {\n if (i % 2 == 0) print i ; else continue\n } \n}'"
},
{
"code": null,
"e": 4464,
"s": 4409,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 4491,
"s": 4464,
"text": "2\n4\n6\n8\n10\n12\n14\n16\n18\n20\n"
},
{
"code": null,
"e": 4759,
"s": 4491,
"text": "It is used to stop the execution of the script. It accepts an integer as an argument which is the exit status code for AWK process. If no argument is supplied, exit returns status zero. Here is an example that stops the execution when the sum becomes greater than 50."
},
{
"code": null,
"e": 4894,
"s": 4759,
"text": "[jerry]$ awk 'BEGIN {\n sum = 0; for (i = 0; i < 20; ++i) {\n sum += i; if (sum > 50) exit(10); else print \"Sum =\", sum \n } \n}'"
},
{
"code": null,
"e": 4949,
"s": 4894,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 5036,
"s": 4949,
"text": "Sum = 0\nSum = 1\nSum = 3\nSum = 6\nSum = 10\nSum = 15\nSum = 21\nSum = 28\nSum = 36\nSum = 45\n"
},
{
"code": null,
"e": 5082,
"s": 5036,
"text": "Let us check the return status of the script."
},
{
"code": null,
"e": 5099,
"s": 5082,
"text": "[jerry]$ echo $?"
},
{
"code": null,
"e": 5154,
"s": 5099,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 5158,
"s": 5154,
"text": "10\n"
},
{
"code": null,
"e": 5165,
"s": 5158,
"text": " Print"
},
{
"code": null,
"e": 5176,
"s": 5165,
"text": " Add Notes"
}
] |
Display a message on console while focusing on input type in JavaScript? | For this, you can use the concept of focus(). Following is the code −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/
4.7.0/css/font-awesome.min.css">
</head>
<body>
<input id='txtInput' placeholder="Enter the value......."/>
<button id='submitBtn'>Submit</button>
<script>
const submitButton = document.getElementById('submitBtn');
submitButton.addEventListener('click', () => {
console.log('Submitting information to the server.....');
})
const txtInput = document.getElementById('txtInput');
txtInput.addEventListener('blur', () => {
console.log('Enter the new value into the text box......');
txtInput.focus();
});
txtInput.focus();
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
After focusing at the input text box, you will get the following output. | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "For this, you can use the concept of focus(). Following is the code −"
},
{
"code": null,
"e": 1143,
"s": 1132,
"text": " Live Demo"
},
{
"code": null,
"e": 2186,
"s": 1143,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/\n4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<input id='txtInput' placeholder=\"Enter the value.......\"/>\n<button id='submitBtn'>Submit</button>\n<script>\n const submitButton = document.getElementById('submitBtn');\n submitButton.addEventListener('click', () => {\n console.log('Submitting information to the server.....');\n })\n const txtInput = document.getElementById('txtInput');\n txtInput.addEventListener('blur', () => {\n console.log('Enter the new value into the text box......');\n txtInput.focus();\n });\n txtInput.focus();\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2348,
"s": 2186,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2389,
"s": 2348,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2462,
"s": 2389,
"text": "After focusing at the input text box, you will get the following output."
}
] |
Data Type Conversion in R - GeeksforGeeks | 21 Apr, 2021
Prerequisite: Data Types in the R
Data Type conversion is the process of converting one type of data to another type of data. R Programming Language has only 3 data types: Numeric, Logical, Character. In this article, we are going to see how to convert the data type in the R Programming language
Since R is a weakly typed language or dynamically typed language, R language automatically creates data types based on the values assigned to the variable. We see a glimpse of this in the code below:
R
# value assignmentname <- "GeeksforGeeks"age <- 20pwd <- FALSE # type checkingtypeof(name)typeof(age)typeof(pwd)
Output:
[1] "character"
[1] "double"
[1] "logical"
We have used typeof(value) function to check the type of the values assigned to the variables in the above code.
Any numeric value which is not 0, on conversion to Logical type gets converted to TRUE. Here “20” is a non-zero numeric value. Hence, it gets converted to TRUE.
“FALSE” is a character type which on conversion becomes FALSE of logical type. The double quotes are removed on conversion from character type to Logical type.
Syntax: as.logical(value)
Example:
R
# value assignmentage <- 20pwd <- "FALSE" # Converting typeas.logical(age)as.logical(pwd)
Output:
[1] TRUE
[1] FALSE
Any character type values are always enclosed within double quotes(” “). Hence, the conversion of 20 of numeric type gets converted into “20” of character type. Similarly, converting the FALSE of logical type into character type gives us “FALSE”.
Syntax: as.character(value)
Example:
R
# value assignmentage <- 20pwd <- FALSE # Converting typeas.character(age)as.character(pwd)
Output:
[1] "20"
[1] "FALSE"
Syntax: as.numeric(value)
“20” of character type on being converted to numeric type becomes 20, just the double quotes got removed. Conversion of Logical type to Numeric, FALSE-> 0 and TRUE-> 1.
Example:
R
# value assignmentage <- "20"pwd <- FALSE # Converting typeas.numeric(age)as.numeric(pwd)
Output:
[1] 20
[1] 0
In the code below, we have converted 2 sample vectors into a single matrix by using the syntax below. The elements of the vectors are filled in Row major order.
Syntax: rbind(vector1, vector2, vector3.....vectorN)
We have converted 2 sample vectors into a single matrix by using the syntax below. The elements of the vectors are filled in Column major order.
Syntax: cbind(vector1, vector2, vector3.....vectorN)
Example:
R
# sample vectorsvector1 <- c('red','green',"blue","yellow")vector2 <- c(1,2,3,4) print("Row Major Order")rbind(vector1,vector2)print("Column Major Order")cbind(vector1,vector2)
Output:
[1] "Row Major Order"
[,1] [,2] [,3] [,4]
vector1 "red" "green" "blue" "yellow"
vector2 "1" "2" "3" "4"
[1] "Column Major Order"
vector1 vector2
[1,] "red" "1"
[2,] "green" "2"
[3,] "blue" "3"
[4,] "yellow" "4"
In the code below, on the conversion of our sample vectors into dataframe, elements are filled in the column-major order. The first vector becomes the 1st column, the second vector became the 2nd column.
Syntax: data.frame(vector1, vector2, vector3.....vectorN)
Example:
R
# sample vectorsvector1 <- c('red', 'green', "blue", "yellow")vector2 <- c(1, 2, 3, 4) data.frame(vector1, vector2)
Output:
vector1 vector2
1 red 1
2 green 2
3 blue 3
4 yellow 4
In the code below, the sample matrix is containing elements from 1 to 6, we have specified nrows=2 which means our sample matrix will be containing 2 rows, then we have used the syntax below which converts the matrix into one long vector. The elements of the matrix are accessed in column-major order.
Syntax: as.vector(matrix_name)
Example:
R
# sample matrixmat<- matrix(c(1:6), nrow = 2)print("Sample Matrix")mat print("After conversion into vector")as.vector(mat)
Output:
[1] "Sample Matrix"
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[1] "After conversion into vector"
[1] 1 2 3 4 5 6
In the code below, the sample matrix is containing elements from 1 to 6, we have specified nrows=2 which means our sample matrix will be containing 2 rows, then we have used the syntax below which converts the matrix into a dataframe. The elements of the matrix are accessed in column-major order.
Syntax: as.data.frame(matrix_name)
Example:
R
# sample matrixmat<- matrix(c(1:6), nrow = 2)print("Sample Matrix")mat print("After conversion into Dataframe")as.data.frame(mat)
Output:
[1] "Sample Matrix"
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[1] "After conversion into Dataframe"
V1 V2 V3
1 1 3 5
2 2 4 6
In the code below, we have created a sample dataframe containing elements of different types, then we have used the syntax below which converts the dataframe into a matrix of character type, which means each element of the matrix is of character type.
Syntax: as.matrix(dataframe_name)
Example:
R
# sample dataframedf <- data.frame( serial = c (1:5), name = c("Welcome","to","Geeks","for","Geeks"), stipend = c(2000,3000.5,5000,4000,500.2), stringsAsFactors = FALSE) print("Sample Dataframe")df print("After conversion into Matrix")as.matrix(df)
Output:
[1] "Sample Dataframe"
serial name stipend
1 1 Welcome 2000.0
2 2 to 3000.5
3 3 Geeks 5000.0
4 4 for 4000.0
5 5 Geeks 500.2
[1] "After conversion into Matrix"
serial name stipend
[1,] "1" "Welcome" "2000.0"
[2,] "2" "to" "3000.5"
[3,] "3" "Geeks" "5000.0"
[4,] "4" "for" "4000.0"
[5,] "5" "Geeks" " 500.2"
Picked
R Data-types
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Data Visualization in R
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25196,
"s": 25162,
"text": "Prerequisite: Data Types in the R"
},
{
"code": null,
"e": 25459,
"s": 25196,
"text": "Data Type conversion is the process of converting one type of data to another type of data. R Programming Language has only 3 data types: Numeric, Logical, Character. In this article, we are going to see how to convert the data type in the R Programming language"
},
{
"code": null,
"e": 25659,
"s": 25459,
"text": "Since R is a weakly typed language or dynamically typed language, R language automatically creates data types based on the values assigned to the variable. We see a glimpse of this in the code below:"
},
{
"code": null,
"e": 25661,
"s": 25659,
"text": "R"
},
{
"code": "# value assignmentname <- \"GeeksforGeeks\"age <- 20pwd <- FALSE # type checkingtypeof(name)typeof(age)typeof(pwd)",
"e": 25775,
"s": 25661,
"text": null
},
{
"code": null,
"e": 25783,
"s": 25775,
"text": "Output:"
},
{
"code": null,
"e": 25826,
"s": 25783,
"text": "[1] \"character\"\n[1] \"double\"\n[1] \"logical\""
},
{
"code": null,
"e": 25939,
"s": 25826,
"text": "We have used typeof(value) function to check the type of the values assigned to the variables in the above code."
},
{
"code": null,
"e": 26102,
"s": 25939,
"text": "Any numeric value which is not 0, on conversion to Logical type gets converted to TRUE. Here “20” is a non-zero numeric value. Hence, it gets converted to TRUE. "
},
{
"code": null,
"e": 26262,
"s": 26102,
"text": "“FALSE” is a character type which on conversion becomes FALSE of logical type. The double quotes are removed on conversion from character type to Logical type."
},
{
"code": null,
"e": 26288,
"s": 26262,
"text": "Syntax: as.logical(value)"
},
{
"code": null,
"e": 26297,
"s": 26288,
"text": "Example:"
},
{
"code": null,
"e": 26299,
"s": 26297,
"text": "R"
},
{
"code": "# value assignmentage <- 20pwd <- \"FALSE\" # Converting typeas.logical(age)as.logical(pwd)",
"e": 26390,
"s": 26299,
"text": null
},
{
"code": null,
"e": 26398,
"s": 26390,
"text": "Output:"
},
{
"code": null,
"e": 26417,
"s": 26398,
"text": "[1] TRUE\n[1] FALSE"
},
{
"code": null,
"e": 26665,
"s": 26417,
"text": "Any character type values are always enclosed within double quotes(” “). Hence, the conversion of 20 of numeric type gets converted into “20” of character type. Similarly, converting the FALSE of logical type into character type gives us “FALSE”."
},
{
"code": null,
"e": 26693,
"s": 26665,
"text": "Syntax: as.character(value)"
},
{
"code": null,
"e": 26702,
"s": 26693,
"text": "Example:"
},
{
"code": null,
"e": 26704,
"s": 26702,
"text": "R"
},
{
"code": "# value assignmentage <- 20pwd <- FALSE # Converting typeas.character(age)as.character(pwd)",
"e": 26797,
"s": 26704,
"text": null
},
{
"code": null,
"e": 26805,
"s": 26797,
"text": "Output:"
},
{
"code": null,
"e": 26826,
"s": 26805,
"text": "[1] \"20\"\n[1] \"FALSE\""
},
{
"code": null,
"e": 26852,
"s": 26826,
"text": "Syntax: as.numeric(value)"
},
{
"code": null,
"e": 27022,
"s": 26852,
"text": " “20” of character type on being converted to numeric type becomes 20, just the double quotes got removed. Conversion of Logical type to Numeric, FALSE-> 0 and TRUE-> 1."
},
{
"code": null,
"e": 27031,
"s": 27022,
"text": "Example:"
},
{
"code": null,
"e": 27033,
"s": 27031,
"text": "R"
},
{
"code": "# value assignmentage <- \"20\"pwd <- FALSE # Converting typeas.numeric(age)as.numeric(pwd)",
"e": 27124,
"s": 27033,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27124,
"text": "Output:"
},
{
"code": null,
"e": 27145,
"s": 27132,
"text": "[1] 20\n[1] 0"
},
{
"code": null,
"e": 27306,
"s": 27145,
"text": "In the code below, we have converted 2 sample vectors into a single matrix by using the syntax below. The elements of the vectors are filled in Row major order."
},
{
"code": null,
"e": 27359,
"s": 27306,
"text": "Syntax: rbind(vector1, vector2, vector3.....vectorN)"
},
{
"code": null,
"e": 27504,
"s": 27359,
"text": "We have converted 2 sample vectors into a single matrix by using the syntax below. The elements of the vectors are filled in Column major order."
},
{
"code": null,
"e": 27558,
"s": 27504,
"text": "Syntax: cbind(vector1, vector2, vector3.....vectorN)"
},
{
"code": null,
"e": 27567,
"s": 27558,
"text": "Example:"
},
{
"code": null,
"e": 27569,
"s": 27567,
"text": "R"
},
{
"code": "# sample vectorsvector1 <- c('red','green',\"blue\",\"yellow\")vector2 <- c(1,2,3,4) print(\"Row Major Order\")rbind(vector1,vector2)print(\"Column Major Order\")cbind(vector1,vector2)",
"e": 27747,
"s": 27569,
"text": null
},
{
"code": null,
"e": 27755,
"s": 27747,
"text": "Output:"
},
{
"code": null,
"e": 28027,
"s": 27755,
"text": "[1] \"Row Major Order\"\n [,1] [,2] [,3] [,4] \nvector1 \"red\" \"green\" \"blue\" \"yellow\"\nvector2 \"1\" \"2\" \"3\" \"4\" \n \n[1] \"Column Major Order\"\n vector1 vector2\n[1,] \"red\" \"1\" \n[2,] \"green\" \"2\" \n[3,] \"blue\" \"3\" \n[4,] \"yellow\" \"4\" "
},
{
"code": null,
"e": 28231,
"s": 28027,
"text": "In the code below, on the conversion of our sample vectors into dataframe, elements are filled in the column-major order. The first vector becomes the 1st column, the second vector became the 2nd column."
},
{
"code": null,
"e": 28291,
"s": 28231,
"text": "Syntax: data.frame(vector1, vector2, vector3.....vectorN) "
},
{
"code": null,
"e": 28300,
"s": 28291,
"text": "Example:"
},
{
"code": null,
"e": 28302,
"s": 28300,
"text": "R"
},
{
"code": "# sample vectorsvector1 <- c('red', 'green', \"blue\", \"yellow\")vector2 <- c(1, 2, 3, 4) data.frame(vector1, vector2)",
"e": 28419,
"s": 28302,
"text": null
},
{
"code": null,
"e": 28427,
"s": 28419,
"text": "Output:"
},
{
"code": null,
"e": 28516,
"s": 28427,
"text": " vector1 vector2\n1 red 1\n2 green 2\n3 blue 3\n4 yellow 4"
},
{
"code": null,
"e": 28819,
"s": 28516,
"text": "In the code below, the sample matrix is containing elements from 1 to 6, we have specified nrows=2 which means our sample matrix will be containing 2 rows, then we have used the syntax below which converts the matrix into one long vector. The elements of the matrix are accessed in column-major order. "
},
{
"code": null,
"e": 28850,
"s": 28819,
"text": "Syntax: as.vector(matrix_name)"
},
{
"code": null,
"e": 28859,
"s": 28850,
"text": "Example:"
},
{
"code": null,
"e": 28861,
"s": 28859,
"text": "R"
},
{
"code": "# sample matrixmat<- matrix(c(1:6), nrow = 2)print(\"Sample Matrix\")mat print(\"After conversion into vector\")as.vector(mat)",
"e": 28985,
"s": 28861,
"text": null
},
{
"code": null,
"e": 28993,
"s": 28985,
"text": "Output:"
},
{
"code": null,
"e": 29125,
"s": 28993,
"text": "[1] \"Sample Matrix\"\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n\n[1] \"After conversion into vector\"\n[1] 1 2 3 4 5 6"
},
{
"code": null,
"e": 29424,
"s": 29125,
"text": "In the code below, the sample matrix is containing elements from 1 to 6, we have specified nrows=2 which means our sample matrix will be containing 2 rows, then we have used the syntax below which converts the matrix into a dataframe. The elements of the matrix are accessed in column-major order. "
},
{
"code": null,
"e": 29459,
"s": 29424,
"text": "Syntax: as.data.frame(matrix_name)"
},
{
"code": null,
"e": 29468,
"s": 29459,
"text": "Example:"
},
{
"code": null,
"e": 29470,
"s": 29468,
"text": "R"
},
{
"code": "# sample matrixmat<- matrix(c(1:6), nrow = 2)print(\"Sample Matrix\")mat print(\"After conversion into Dataframe\")as.data.frame(mat)",
"e": 29601,
"s": 29470,
"text": null
},
{
"code": null,
"e": 29609,
"s": 29601,
"text": "Output:"
},
{
"code": null,
"e": 29761,
"s": 29609,
"text": "[1] \"Sample Matrix\"\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n\n[1] \"After conversion into Dataframe\"\n V1 V2 V3\n1 1 3 5\n2 2 4 6"
},
{
"code": null,
"e": 30013,
"s": 29761,
"text": "In the code below, we have created a sample dataframe containing elements of different types, then we have used the syntax below which converts the dataframe into a matrix of character type, which means each element of the matrix is of character type."
},
{
"code": null,
"e": 30047,
"s": 30013,
"text": "Syntax: as.matrix(dataframe_name)"
},
{
"code": null,
"e": 30056,
"s": 30047,
"text": "Example:"
},
{
"code": null,
"e": 30058,
"s": 30056,
"text": "R"
},
{
"code": "# sample dataframedf <- data.frame( serial = c (1:5), name = c(\"Welcome\",\"to\",\"Geeks\",\"for\",\"Geeks\"), stipend = c(2000,3000.5,5000,4000,500.2), stringsAsFactors = FALSE) print(\"Sample Dataframe\")df print(\"After conversion into Matrix\")as.matrix(df)",
"e": 30319,
"s": 30058,
"text": null
},
{
"code": null,
"e": 30327,
"s": 30319,
"text": "Output:"
},
{
"code": null,
"e": 30722,
"s": 30327,
"text": "[1] \"Sample Dataframe\"\n serial name stipend\n1 1 Welcome 2000.0\n2 2 to 3000.5\n3 3 Geeks 5000.0\n4 4 for 4000.0\n5 5 Geeks 500.2\n\n[1] \"After conversion into Matrix\"\n serial name stipend \n[1,] \"1\" \"Welcome\" \"2000.0\"\n[2,] \"2\" \"to\" \"3000.5\"\n[3,] \"3\" \"Geeks\" \"5000.0\"\n[4,] \"4\" \"for\" \"4000.0\"\n[5,] \"5\" \"Geeks\" \" 500.2\""
},
{
"code": null,
"e": 30729,
"s": 30722,
"text": "Picked"
},
{
"code": null,
"e": 30742,
"s": 30729,
"text": "R Data-types"
},
{
"code": null,
"e": 30753,
"s": 30742,
"text": "R Language"
},
{
"code": null,
"e": 30851,
"s": 30753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30860,
"s": 30851,
"text": "Comments"
},
{
"code": null,
"e": 30873,
"s": 30860,
"text": "Old Comments"
},
{
"code": null,
"e": 30925,
"s": 30873,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30963,
"s": 30925,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30998,
"s": 30963,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31056,
"s": 30998,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31080,
"s": 31056,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 31117,
"s": 31080,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 31160,
"s": 31117,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 31210,
"s": 31160,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 31247,
"s": 31210,
"text": "How to import an Excel File into R ?"
}
] |
Display result of a table into a temp table with MySQL? | Let us first create a table −
mysql> create table DemoTable1 (Id int,Name varchar(100));
Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(100,'John');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1 values(110,'Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1 values(120,'Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values(130,'David');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+------+--------+
| Id | Name |
+------+--------+
| 100 | John |
| 110 | Chris |
| 120 | Robert |
| 130 | David |
+------+--------+
4 rows in set (0.00 sec)
Following is the query to display result of a table into a temporary table −
mysql> create temporary table DemoTable2
select *from DemoTable1;
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
Let us check the table records of temporary table −
mysql> select *from DemoTable2;
This will produce the following output −
+------+--------+
| Id | Name |
+------+--------+
| 100 | John |
| 110 | Chris |
| 120 | Robert |
| 130 | David |
+------+--------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1188,
"s": 1092,
"text": "mysql> create table DemoTable1 (Id int,Name varchar(100));\nQuery OK, 0 rows affected (0.89 sec)"
},
{
"code": null,
"e": 1244,
"s": 1188,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1592,
"s": 1244,
"text": "mysql> insert into DemoTable1 values(100,'John');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable1 values(110,'Chris');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1 values(120,'Robert');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1 values(130,'David');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1652,
"s": 1592,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1684,
"s": 1652,
"text": "mysql> select *from DemoTable1;"
},
{
"code": null,
"e": 1725,
"s": 1684,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1894,
"s": 1725,
"text": "+------+--------+\n| Id | Name |\n+------+--------+\n| 100 | John |\n| 110 | Chris |\n| 120 | Robert |\n| 130 | David |\n+------+--------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1971,
"s": 1894,
"text": "Following is the query to display result of a table into a temporary table −"
},
{
"code": null,
"e": 2114,
"s": 1971,
"text": "mysql> create temporary table DemoTable2\n select *from DemoTable1;\nQuery OK, 4 rows affected (0.01 sec)\nRecords: 4 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2166,
"s": 2114,
"text": "Let us check the table records of temporary table −"
},
{
"code": null,
"e": 2198,
"s": 2166,
"text": "mysql> select *from DemoTable2;"
},
{
"code": null,
"e": 2239,
"s": 2198,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2408,
"s": 2239,
"text": "+------+--------+\n| Id | Name |\n+------+--------+\n| 100 | John |\n| 110 | Chris |\n| 120 | Robert |\n| 130 | David |\n+------+--------+\n4 rows in set (0.00 sec)"
}
] |
Lodash _.mergeWith() Method - GeeksforGeeks | 14 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 _.mergeWith() method uses a customizer function that is invoked to produce the merged values of the given destination and source properties. When the customizer function returns undefined, the merging is handled by the method instead. It is almost the same as _.merge() method.
Syntax:
_.mergeWith( object, sources, customizer )
Parameters: This method accepts three parameters as mentioned above and described below:
object: This parameter holds the destination object.
sources: This parameter holds the source object. It is an optional parameter.
customizer: This is the function to customize assigned values.
Return Value: This method returns the object.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // The destination objectvar object = { 'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]}; // The source objectvar other = { 'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]}; // Using the _.mergeWith() method console.log(_.mergeWith(object, other));
Output:
{ ‘amit’: [{‘chinmoy’: 30, ‘susanta’: 20 }, { ‘durgam’: 40, ‘kripamoy’: 50 }] }
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Defining the customizer functionfunction customizer(obj, src) { if (_.isArray(obj)) { return obj.concat(src); }} // The destination objectvar object = { 'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]}; // The source objectvar other = { 'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]}; // Using the _.mergeWith() method console.log(_.mergeWith(object, other, customizer));
Output:
{ ‘amit’: [{‘susanta’: 20 }, { ‘durgam’: 40}, {‘chinmoy’: 30}, {‘kripamoy’: 50 } ]}
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24387,
"s": 24359,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 24527,
"s": 24387,
"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": 24809,
"s": 24527,
"text": "The _.mergeWith() method uses a customizer function that is invoked to produce the merged values of the given destination and source properties. When the customizer function returns undefined, the merging is handled by the method instead. It is almost the same as _.merge() method."
},
{
"code": null,
"e": 24817,
"s": 24809,
"text": "Syntax:"
},
{
"code": null,
"e": 24861,
"s": 24817,
"text": "_.mergeWith( object, sources, customizer )\n"
},
{
"code": null,
"e": 24950,
"s": 24861,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25003,
"s": 24950,
"text": "object: This parameter holds the destination object."
},
{
"code": null,
"e": 25081,
"s": 25003,
"text": "sources: This parameter holds the source object. It is an optional parameter."
},
{
"code": null,
"e": 25144,
"s": 25081,
"text": "customizer: This is the function to customize assigned values."
},
{
"code": null,
"e": 25190,
"s": 25144,
"text": "Return Value: This method returns the object."
},
{
"code": null,
"e": 25201,
"s": 25190,
"text": "Example 1:"
},
{
"code": null,
"e": 25212,
"s": 25201,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // The destination objectvar object = { 'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]}; // The source objectvar other = { 'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]}; // Using the _.mergeWith() method console.log(_.mergeWith(object, other));",
"e": 25529,
"s": 25212,
"text": null
},
{
"code": null,
"e": 25537,
"s": 25529,
"text": "Output:"
},
{
"code": null,
"e": 25617,
"s": 25537,
"text": "{ ‘amit’: [{‘chinmoy’: 30, ‘susanta’: 20 }, { ‘durgam’: 40, ‘kripamoy’: 50 }] }"
},
{
"code": null,
"e": 25630,
"s": 25617,
"text": "Example 2: "
},
{
"code": null,
"e": 25641,
"s": 25630,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Defining the customizer functionfunction customizer(obj, src) { if (_.isArray(obj)) { return obj.concat(src); }} // The destination objectvar object = { 'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]}; // The source objectvar other = { 'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]}; // Using the _.mergeWith() method console.log(_.mergeWith(object, other, customizer));",
"e": 26093,
"s": 25641,
"text": null
},
{
"code": null,
"e": 26101,
"s": 26093,
"text": "Output:"
},
{
"code": null,
"e": 26185,
"s": 26101,
"text": "{ ‘amit’: [{‘susanta’: 20 }, { ‘durgam’: 40}, {‘chinmoy’: 30}, {‘kripamoy’: 50 } ]}"
},
{
"code": null,
"e": 26203,
"s": 26185,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 26214,
"s": 26203,
"text": "JavaScript"
},
{
"code": null,
"e": 26231,
"s": 26214,
"text": "Web Technologies"
},
{
"code": null,
"e": 26329,
"s": 26231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26338,
"s": 26329,
"text": "Comments"
},
{
"code": null,
"e": 26351,
"s": 26338,
"text": "Old Comments"
},
{
"code": null,
"e": 26412,
"s": 26351,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26457,
"s": 26412,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26529,
"s": 26457,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26575,
"s": 26529,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26623,
"s": 26575,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 26679,
"s": 26623,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26712,
"s": 26679,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26774,
"s": 26712,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26817,
"s": 26774,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Adding and Deleting Cookies in Selenium Python - GeeksforGeeks | 02 Jul, 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.Playing around with cookies is often essential a cookie might need to be added manually or removed manually to implement some stage of website such as authentication. Various method to play around with cookies in selenium python are –
add_cookie method is used to add a cookie to your current session. This cookie can be used by website itself or by you.
Syntax –
add_cookie(cookie_dict)
Example –Now one can use add_cookie method as a driver method as below –
driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’})
To check individual implementation of add_cookie method in project visit – add_cookie driver method.
get_cookie method is used to get a cookie with a specified name. It returns the cookie if found, None if not.Syntax –
driver.get_cookie(name)
Example –Now one can use get_cookie method as a driver method as below –
driver.get("https://www.geeksforgeeks.org/")
driver.get_cookie("foo")
To check individual implementation of get_cookie method in project visit – get_cookie driver method.
delete_cookie method is used to delete a cookie with a specified value.Syntax –
driver.delete_cookie(name)
Example –Now one can use delete_cookie method as a driver method as below –
driver.get("https://www.geeksforgeeks.org/")
driver.delete_cookie("foo")
To check individual implementation of delete_cookie method in project visit – delete_cookie driver method.
get_cookies method is used to get all cookies in current session. It returns a set of dictionaries, corresponding to cookies visible in the current session.
Syntax –
driver.get_cookies()
Example –Now one can use get_cookies method as a driver method as below –
driver.get("https://www.geeksforgeeks.org/")
driver.get_cookies()
To check individual implementation of get_cookies method in project visit – get_cookies driver method.
To demonstrate, cookies in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # add_cookie method driverdriver.add_cookie({"name" : "foo", "value" : "bar"}) # get browser cookiedriver.get_cookie("foo") # get all cookies in scope of sessionprint(driver.get_cookies()) # delete browser cookiedriver.delete_cookie("foo") # clear all cookies in scope of sessiondriver.delete_all_cookies()
Output –Cookie with name foo and value bar is added as verified below –Terminal Output –
Akanksha_Rai
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 25275,
"s": 24302,
"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.Playing around with cookies is often essential a cookie might need to be added manually or removed manually to implement some stage of website such as authentication. Various method to play around with cookies in selenium python are –"
},
{
"code": null,
"e": 25395,
"s": 25275,
"text": "add_cookie method is used to add a cookie to your current session. This cookie can be used by website itself or by you."
},
{
"code": null,
"e": 25404,
"s": 25395,
"text": "Syntax –"
},
{
"code": null,
"e": 25428,
"s": 25404,
"text": "add_cookie(cookie_dict)"
},
{
"code": null,
"e": 25501,
"s": 25428,
"text": "Example –Now one can use add_cookie method as a driver method as below –"
},
{
"code": null,
"e": 25555,
"s": 25501,
"text": "driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’})\n"
},
{
"code": null,
"e": 25656,
"s": 25555,
"text": "To check individual implementation of add_cookie method in project visit – add_cookie driver method."
},
{
"code": null,
"e": 25774,
"s": 25656,
"text": "get_cookie method is used to get a cookie with a specified name. It returns the cookie if found, None if not.Syntax –"
},
{
"code": null,
"e": 25798,
"s": 25774,
"text": "driver.get_cookie(name)"
},
{
"code": null,
"e": 25871,
"s": 25798,
"text": "Example –Now one can use get_cookie method as a driver method as below –"
},
{
"code": null,
"e": 25942,
"s": 25871,
"text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_cookie(\"foo\")\n"
},
{
"code": null,
"e": 26043,
"s": 25942,
"text": "To check individual implementation of get_cookie method in project visit – get_cookie driver method."
},
{
"code": null,
"e": 26123,
"s": 26043,
"text": "delete_cookie method is used to delete a cookie with a specified value.Syntax –"
},
{
"code": null,
"e": 26150,
"s": 26123,
"text": "driver.delete_cookie(name)"
},
{
"code": null,
"e": 26226,
"s": 26150,
"text": "Example –Now one can use delete_cookie method as a driver method as below –"
},
{
"code": null,
"e": 26300,
"s": 26226,
"text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.delete_cookie(\"foo\")\n"
},
{
"code": null,
"e": 26407,
"s": 26300,
"text": "To check individual implementation of delete_cookie method in project visit – delete_cookie driver method."
},
{
"code": null,
"e": 26564,
"s": 26407,
"text": "get_cookies method is used to get all cookies in current session. It returns a set of dictionaries, corresponding to cookies visible in the current session."
},
{
"code": null,
"e": 26573,
"s": 26564,
"text": "Syntax –"
},
{
"code": null,
"e": 26594,
"s": 26573,
"text": "driver.get_cookies()"
},
{
"code": null,
"e": 26668,
"s": 26594,
"text": "Example –Now one can use get_cookies method as a driver method as below –"
},
{
"code": null,
"e": 26735,
"s": 26668,
"text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_cookies()\n"
},
{
"code": null,
"e": 26838,
"s": 26735,
"text": "To check individual implementation of get_cookies method in project visit – get_cookies driver method."
},
{
"code": null,
"e": 26956,
"s": 26838,
"text": "To demonstrate, cookies in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object."
},
{
"code": null,
"e": 26966,
"s": 26956,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # add_cookie method driverdriver.add_cookie({\"name\" : \"foo\", \"value\" : \"bar\"}) # get browser cookiedriver.get_cookie(\"foo\") # get all cookies in scope of sessionprint(driver.get_cookies()) # delete browser cookiedriver.delete_cookie(\"foo\") # clear all cookies in scope of sessiondriver.delete_all_cookies()",
"e": 27453,
"s": 26966,
"text": null
},
{
"code": null,
"e": 27542,
"s": 27453,
"text": "Output –Cookie with name foo and value bar is added as verified below –Terminal Output –"
},
{
"code": null,
"e": 27555,
"s": 27542,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27571,
"s": 27555,
"text": "Python-selenium"
},
{
"code": null,
"e": 27580,
"s": 27571,
"text": "selenium"
},
{
"code": null,
"e": 27587,
"s": 27580,
"text": "Python"
},
{
"code": null,
"e": 27685,
"s": 27587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27694,
"s": 27685,
"text": "Comments"
},
{
"code": null,
"e": 27707,
"s": 27694,
"text": "Old Comments"
},
{
"code": null,
"e": 27725,
"s": 27707,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27760,
"s": 27725,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27782,
"s": 27760,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27814,
"s": 27782,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27844,
"s": 27814,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27886,
"s": 27844,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27912,
"s": 27886,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27949,
"s": 27912,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27992,
"s": 27949,
"text": "Python program to convert a list to string"
}
] |
AngularJS | orderBy Filter - GeeksforGeeks | 30 Apr, 2019
The orderBy filter is a handy tool used in angular js.The orderBy channel encourages you to sort an exhibit.Of course, it sorts strings in sequential order requests and numbers in the numerical request.
Syntax:
{{ orderBy_expression | orderBy : expression : reverse }}
Parameter explanation:
expression: It is utilized to decide the request. It very well may be a string, work or a cluster.invert: It is discretionary. If you want your data to be displayed in reverse order please make sure that reverse condition in parameters to set true.
Examples: Order by case when we go through names
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="orderCtrl"> <ul> <li ng-repeat="x in customers | orderBy : 'name'"> {{x.name + ", " + x.city}} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('orderCtrl', function($scope) { $scope.customers = [ {"name" : "Amber", "city" : "ajmer"}, {"name" : "lakshay ", "city" : "vizag"}, {"name" : "karan", "city" : "London"}, {"name" : "bhaskar", "city" : "peshawar"}, ]; }); </script> <p>The array items are arranged by "name".</p> </body> </html>
Output :
Examples: Order by case when we go through gdp by “-” and “+” orderBy
<!DOCTYPE html><html><head> <title>AnngularJS Filters : orderBy </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <style> .tabled{float:left; padding:10px;} </style> </head><body ng-app="orderByDemo"> <script> angular.module('orderByDemo', []) .controller('orderByController', ['$scope', function($scope) { $scope.countries = [{name:'SPAIN', states:'78', gdp:5}, {name:'FRANCE', states:'46', gdp:4}, {name:'PORTUGAL', states:'53', gdp:3}, {name:'CHILE', states:'06', gdp:2}, {name:'RUSSIA', states:'21', gdp:1}]; }]);</script><div ng-controller="orderByController"> <table class="tabled"> <tr> <th>Name</th> <th>No of States</th> <th>GDP(descending)</th> </tr> <!-- orderBy Descending (-) --> <tr ng-repeat="country in countries | orderBy:'-gdp'"> <td>{{country.name}}</td> <td>{{country.states}}</td> <td>{{country.gdp}}</td> </tr> </table> <table class="tabled"> <tr> <th>Name</th> <th>No of States</th> <th>GDP(ascending)</th> </tr> <!-- orderBy Ascending (+) --> <tr ng-repeat="country in countries | orderBy:'gdp'"> <td>{{country.name}}</td> <td>{{country.states}}</td> <td>{{country.gdp}}</td> </tr> </table></div></body></html> <strong> Examples: Order by case (seven wonders)
Output :
<!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script><body> <div ng-app="myApplication" ng-controller="orderCtrl"> <ul><li ng-repeat="x in sevenwonder | orderBy : '-country'">{{x.name + ", " + x.country}}</li></ul> </div> <script>var application = angular.module('myApplication', []);application.controller('orderCtrl', function($scope) { $scope.sevenwonder = [ {"name" : "Great Wall of China" ,"country" : "China"}, {"name" : "Christ the Redeemer Statue", "country" : "Brazil"}, {"name" : "Machu Picchu", "country" : "peru"}, {"name" : "Chichen Itza ", "country" : "Mexico"}, {"name" : "The Roman Colosseum", "country" : "Rome"}, {"name" : "Taj Mahal", "country" : "India"}, {"name" : "Petra", "country" : "Jordan"} ];});</script><p>The array items are sorted by "country".</p> </body></html>
Output :
Picked
AngularJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Calendar Component
Angular | keyup event
Angular PrimeNG Messages Component
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
How to set focus on input field automatically on page load in AngularJS ?
Angular PrimeNG Dropdown Component
What is AOT and JIT Compiler in Angular ?
Angular 10 (blur) Event | [
{
"code": null,
"e": 28369,
"s": 28341,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 28572,
"s": 28369,
"text": "The orderBy filter is a handy tool used in angular js.The orderBy channel encourages you to sort an exhibit.Of course, it sorts strings in sequential order requests and numbers in the numerical request."
},
{
"code": null,
"e": 28580,
"s": 28572,
"text": "Syntax:"
},
{
"code": null,
"e": 28640,
"s": 28580,
"text": "{{ orderBy_expression | orderBy : expression : reverse }} \n"
},
{
"code": null,
"e": 28663,
"s": 28640,
"text": "Parameter explanation:"
},
{
"code": null,
"e": 28912,
"s": 28663,
"text": "expression: It is utilized to decide the request. It very well may be a string, work or a cluster.invert: It is discretionary. If you want your data to be displayed in reverse order please make sure that reverse condition in parameters to set true."
},
{
"code": null,
"e": 28961,
"s": 28912,
"text": "Examples: Order by case when we go through names"
},
{
"code": "<!DOCTYPE html> <html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script> <body> <div ng-app=\"myApp\" ng-controller=\"orderCtrl\"> <ul> <li ng-repeat=\"x in customers | orderBy : 'name'\"> {{x.name + \", \" + x.city}} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('orderCtrl', function($scope) { $scope.customers = [ {\"name\" : \"Amber\", \"city\" : \"ajmer\"}, {\"name\" : \"lakshay \", \"city\" : \"vizag\"}, {\"name\" : \"karan\", \"city\" : \"London\"}, {\"name\" : \"bhaskar\", \"city\" : \"peshawar\"}, ]; }); </script> <p>The array items are arranged by \"name\".</p> </body> </html> ",
"e": 29672,
"s": 28961,
"text": null
},
{
"code": null,
"e": 29681,
"s": 29672,
"text": "Output :"
},
{
"code": null,
"e": 29751,
"s": 29681,
"text": "Examples: Order by case when we go through gdp by “-” and “+” orderBy"
},
{
"code": "<!DOCTYPE html><html><head> <title>AnngularJS Filters : orderBy </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> <style> .tabled{float:left; padding:10px;} </style> </head><body ng-app=\"orderByDemo\"> <script> angular.module('orderByDemo', []) .controller('orderByController', ['$scope', function($scope) { $scope.countries = [{name:'SPAIN', states:'78', gdp:5}, {name:'FRANCE', states:'46', gdp:4}, {name:'PORTUGAL', states:'53', gdp:3}, {name:'CHILE', states:'06', gdp:2}, {name:'RUSSIA', states:'21', gdp:1}]; }]);</script><div ng-controller=\"orderByController\"> <table class=\"tabled\"> <tr> <th>Name</th> <th>No of States</th> <th>GDP(descending)</th> </tr> <!-- orderBy Descending (-) --> <tr ng-repeat=\"country in countries | orderBy:'-gdp'\"> <td>{{country.name}}</td> <td>{{country.states}}</td> <td>{{country.gdp}}</td> </tr> </table> <table class=\"tabled\"> <tr> <th>Name</th> <th>No of States</th> <th>GDP(ascending)</th> </tr> <!-- orderBy Ascending (+) --> <tr ng-repeat=\"country in countries | orderBy:'gdp'\"> <td>{{country.name}}</td> <td>{{country.states}}</td> <td>{{country.gdp}}</td> </tr> </table></div></body></html> <strong> Examples: Order by case (seven wonders)",
"e": 31162,
"s": 29751,
"text": null
},
{
"code": null,
"e": 31171,
"s": 31162,
"text": "Output :"
},
{
"code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script><body> <div ng-app=\"myApplication\" ng-controller=\"orderCtrl\"> <ul><li ng-repeat=\"x in sevenwonder | orderBy : '-country'\">{{x.name + \", \" + x.country}}</li></ul> </div> <script>var application = angular.module('myApplication', []);application.controller('orderCtrl', function($scope) { $scope.sevenwonder = [ {\"name\" : \"Great Wall of China\" ,\"country\" : \"China\"}, {\"name\" : \"Christ the Redeemer Statue\", \"country\" : \"Brazil\"}, {\"name\" : \"Machu Picchu\", \"country\" : \"peru\"}, {\"name\" : \"Chichen Itza \", \"country\" : \"Mexico\"}, {\"name\" : \"The Roman Colosseum\", \"country\" : \"Rome\"}, {\"name\" : \"Taj Mahal\", \"country\" : \"India\"}, {\"name\" : \"Petra\", \"country\" : \"Jordan\"} ];});</script><p>The array items are sorted by \"country\".</p> </body></html>",
"e": 32085,
"s": 31171,
"text": null
},
{
"code": null,
"e": 32094,
"s": 32085,
"text": "Output :"
},
{
"code": null,
"e": 32101,
"s": 32094,
"text": "Picked"
},
{
"code": null,
"e": 32111,
"s": 32101,
"text": "AngularJS"
},
{
"code": null,
"e": 32209,
"s": 32111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32229,
"s": 32209,
"text": "Angular File Upload"
},
{
"code": null,
"e": 32264,
"s": 32229,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 32286,
"s": 32264,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 32321,
"s": 32286,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 32352,
"s": 32321,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 32440,
"s": 32352,
"text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?"
},
{
"code": null,
"e": 32514,
"s": 32440,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 32549,
"s": 32514,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 32591,
"s": 32549,
"text": "What is AOT and JIT Compiler in Angular ?"
}
] |
How to use <mat-divider> in Angular Material ? - GeeksforGeeks | 05 Feb, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-divider> tag is used to separate two sections or content with a horizontal line.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatDividerModule’ from ‘@angular/material/divider’ in the app.module.ts file.
After importing the ‘MatDividerModule’ we need to use <mat-divider> tag.
When we use <mat-divider>, a horizontal grey line is rendered on the screen.
The main purpose of this tag is to separate any two-block, div, or any sections.
Once done with the above steps then serve or start the project.
Project Structure: It will look like the following.
Code Implementation:
app.module.ts:
Javascript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatDividerModule } from '@angular/material/divider';import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatDividerModule, BrowserAnimationsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
app.component.html:
HTML
<h1 style="color:green"> GeeksforGeeks</h1> <mat-divider> </mat-divider> <h5>One stop Solution for all CS subjects</h5> <mat-divider> </mat-divider> <p> The above horizontal line is displayed due to the presence of mat-divider tag.</p>
Output:
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Angular 10 (blur) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 25488,
"s": 25109,
"text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-divider> tag is used to separate two sections or content with a horizontal line."
},
{
"code": null,
"e": 25509,
"s": 25488,
"text": "Installation syntax:"
},
{
"code": null,
"e": 25534,
"s": 25509,
"text": "ng add @angular/material"
},
{
"code": null,
"e": 25544,
"s": 25534,
"text": "Approach:"
},
{
"code": null,
"e": 25615,
"s": 25544,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 25736,
"s": 25615,
"text": "After completing the installation, Import ‘MatDividerModule’ from ‘@angular/material/divider’ in the app.module.ts file."
},
{
"code": null,
"e": 25809,
"s": 25736,
"text": "After importing the ‘MatDividerModule’ we need to use <mat-divider> tag."
},
{
"code": null,
"e": 25886,
"s": 25809,
"text": "When we use <mat-divider>, a horizontal grey line is rendered on the screen."
},
{
"code": null,
"e": 25967,
"s": 25886,
"text": "The main purpose of this tag is to separate any two-block, div, or any sections."
},
{
"code": null,
"e": 26031,
"s": 25967,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 26083,
"s": 26031,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 26104,
"s": 26083,
"text": "Code Implementation:"
},
{
"code": null,
"e": 26120,
"s": 26104,
"text": "app.module.ts: "
},
{
"code": null,
"e": 26131,
"s": 26120,
"text": "Javascript"
},
{
"code": "import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatDividerModule } from '@angular/material/divider';import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatDividerModule, BrowserAnimationsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }",
"e": 26682,
"s": 26131,
"text": null
},
{
"code": null,
"e": 26703,
"s": 26682,
"text": "app.component.html: "
},
{
"code": null,
"e": 26708,
"s": 26703,
"text": "HTML"
},
{
"code": "<h1 style=\"color:green\"> GeeksforGeeks</h1> <mat-divider> </mat-divider> <h5>One stop Solution for all CS subjects</h5> <mat-divider> </mat-divider> <p> The above horizontal line is displayed due to the presence of mat-divider tag.</p>",
"e": 26960,
"s": 26708,
"text": null
},
{
"code": null,
"e": 26968,
"s": 26960,
"text": "Output:"
},
{
"code": null,
"e": 26985,
"s": 26968,
"text": "Angular-material"
},
{
"code": null,
"e": 26992,
"s": 26985,
"text": "Picked"
},
{
"code": null,
"e": 27002,
"s": 26992,
"text": "AngularJS"
},
{
"code": null,
"e": 27019,
"s": 27002,
"text": "Web Technologies"
},
{
"code": null,
"e": 27117,
"s": 27019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27126,
"s": 27117,
"text": "Comments"
},
{
"code": null,
"e": 27139,
"s": 27126,
"text": "Old Comments"
},
{
"code": null,
"e": 27183,
"s": 27139,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27247,
"s": 27183,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 27300,
"s": 27247,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 27349,
"s": 27300,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 27373,
"s": 27349,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 27415,
"s": 27373,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27448,
"s": 27415,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27510,
"s": 27448,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27553,
"s": 27510,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Adding Permission in API - Django REST Framework - GeeksforGeeks | 14 Sep, 2021
There are many different scenarios to consider when it comes to access control. Allowing unauthorized access to risky operations or restricted areas results in a massive vulnerability. This highlights the importance of adding permissions in APIs.
Django REST framework allows us to leverage permissions to define what can be accessed and what actions can be performed in a meaningful or common way. The permission checks always run at the beginning of every view. It uses the authentication information in the ‘request.user’ and ‘request.auth’ properties for each incoming request. If the permission check fails, then the view code will not run.
Note: Together with authentication, permissions determine whether to grant or deny access for an incoming request. In this section, we will combine Basic Authentication with Django REST framework permission to set access control. You can refer Browsable API in Django REST Framework for Models, Serializers, and Views
Let’s dig deep into the Django REST framework permissions.
AllowAny
IsAuthenticated
IsAdminUser
IsAuthenticatedOrReadOnly
DjangoModelPermissions
DjangoModelPermissionsOrAnonReadOnly
DjangoObjectPermissions
The AllowAny permission class will allow unrestricted access, irrespective of whether the request was authenticated or unauthenticated. Here the permission settings default to unrestricted access
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
You don’t need to set this permission, but it is advised to mention it to make the intention explicit. Apart from mentioning it globally, you can set the permission policy on a per-view basis. If you are using the APIView class-based views, the code is as follows
Python3
from rest_framework.permissions import AllowAnyfrom rest_framework.response import Responsefrom rest_framework.views import APIView class ClassBasedView(APIView): permission_classes = [AllowAny] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content)
While using the @api_view decorator with function-based views, the code as follows
Python3
from rest_framework.decorators import api_view, permission_classesfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Response @api_view(['GET'])@permission_classes([AllowAny])def function_view(request, format=None): content = { 'status': 'request was permitted' } return Response(content)
The IsAuthenticated permission class denies unauthenticated users to use the APIs for any operations. This ensures APIs accessibility only to registered users. Let’s use the IsAuthenticated class in our RESTful web service. Here, we can set the permission policy on a per-view basis. Let’s import and add the permission class in our RobotDetail and RobotList class. The code is as follows:
from rest_framework.permissions import IsAuthenticated
Python3
class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' class RobotList(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list'
Let’s try to retrieve robots without providing any credentials. The HTTPie command is
http :8000/robot/
Output
Since we haven’t provided any authentication details, the API has rejected the request that retrieves the robot details. Now we will create a new user using Django’s interactive shell and try the HTTPie command with credentials.
Note: You can refer to the article Create a User for Django Using Django’s Interactive Shell.
The HTTPie command is as follows:
http -a “sonu”:”sn@pswrd” :8000/robot/
Output
Let’s try an HTTPie command that creates a new robot entry.
http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 1100′′ robot_category=”Articulated Robots” currency=”USD” price=25000 manufacturer=”ABB” manufacturing_date=”2020-05-10 00:00:00+00:00′′
Output
The IsAdminUser permission class will allow permission to users whose user.is_staff is True. This permission class ensures that the API is accessible to trusted administrators. Let’s make use of IsAdminUser permission class. Let’s import the permission class
from rest_framework.permissions import IsAdminUser
You can replace the RobotDetail and RobotList class with the below code.
Python3
class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminUser] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' class RobotList(generics.ListCreateAPIView): permission_classes = [IsAdminUser] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list'
Now let’s try by providing normal user credentials. The HTTPie command is
http -a “sonu”:”sn@pswrd” :8000/robot/
Output
You can notice the message saying “You do not have permission to perform this action”. This is because the user is not an administrator. Let’s provide our super admin credentials. The HTTPie command is
http -a “admin”:”admin@123′′ :8000/robot/
Output
The IsAuthenticatedOrReadOnly permission class allows unauthorized users to perform safe methods, whereas authenticated users can perform any operations. This class is useful when we need to set read permissions for anonymous users and read/write permissions for authenticated users. Let’s import the permission class
from rest_framework.permissions import IsAuthenticatedOrReadOnly
Now, you can replace the RobotDetail and RobotList class with the below code.
Python3
class RobotList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'
Let’s try to retrieve robot details without providing any credentials. The HTTPie command is as follows:
http :8000/robot/
Output
Now let’s try to create a new robot without providing credentials. The HTTPie command is as follows:
http POST :8000/robot/ name=”IRB 120′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2020-08-10 00:00:00+00:00′′
Output
The IsAuthenticatedOrReadOnly permission class permits only safe operations for unauthenticated users. Let’s create a new robot by providing user credentials.
http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 120′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2020-08-10 00:00:00+00:00′′
Output
In DjangoModelPermissions class, the authentication is granted only if the user is authenticated and has the relevant model permissions assigned. The model permissions are as follows
The user must have the add permission on the model to make POST requests.
The user must have the change permission on the model to make PUT and PATCH requests.
The user must have the delete permission on the model to make DELETE requests.
By default, the class permits GET requests for authenticated users. DjangoModelPermissions class ties into Django’s standard django.contrib.auth model permissions. It must only be applied to views that have a .queryset property or get_queryset() method.
You can import the DjangoModelPermissions class.
from rest_framework.permissions import DjangoModelPermissions
Next, replace the RobotDetail and RobotList class with the below code.
Python3
class RobotList(generics.ListCreateAPIView): permission_classes = [DjangoModelPermissions] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [DjangoModelPermissions] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'
Let’s try to create a robot by providing user credentials. The HTTPie command as follows:
http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 140′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2021-01-10 00:00:00+00:00′′
Output
You can notice, permission to create a robot is denied. This is because we haven’t set model-level permission for the given user. To set permission to add a robot, you can log in through the admin panel as a superuser and add permission by selecting the user under the Users section. Finally, save the changes. Sharing the screenshot below:
Let’s try again the same HTTPie command.
http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 140′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2021-01-10 00:00:00+00:00′′
Output
DjangoModelPermissionsOrAnonReadOnly permission class is the same as that of the DjangoModelPermissions class except it allows unauthenticated users to have read-only access to the API.
Let’s import the DjangoModelPermissionsOrAnonReadOnly class.
from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
Now you can add the permission class to RobotDetail and RobotList class. The code is as follows:
Python3
class RobotList(generics.ListCreateAPIView): permission_classes = [DjangoModelPermissionsOrAnonReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [DjangoModelPermissionsOrAnonReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'
Let’s try to retrieve robots without providing any credentials. The HTTPie command is as follows:
http :8000/robot/
Output
The DjangoObjectPermissions allows per-object permissions on models, which can set permissions for individual rows in a table (model instances). The user must be authenticated to grant authorization and should be assigned with relevant per-object permissions and relevant model permissions. To set relevant per-object permissions, we need to subclass the DjangoObjectPermissions and implement the has_object_permission() method. The relevant model permissions are as follows:
The user must have the add permission on the model to make POST requests.
The user must have the change permission on the model to make PUT and PATCH requests.
The user must have the delete permission on the model to make DELETE requests.
With DjangoModelPermissions you can create custom model permissions by overriding DjangoObjectPermissions. You can check Customizing Object Level Permission in Django REST Framework.
Django-REST
Python Django
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
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 25804,
"s": 25555,
"text": "There are many different scenarios to consider when it comes to access control. Allowing unauthorized access to risky operations or restricted areas results in a massive vulnerability. This highlights the importance of adding permissions in APIs. "
},
{
"code": null,
"e": 26204,
"s": 25804,
"text": "Django REST framework allows us to leverage permissions to define what can be accessed and what actions can be performed in a meaningful or common way. The permission checks always run at the beginning of every view. It uses the authentication information in the ‘request.user’ and ‘request.auth’ properties for each incoming request. If the permission check fails, then the view code will not run. "
},
{
"code": null,
"e": 26522,
"s": 26204,
"text": "Note: Together with authentication, permissions determine whether to grant or deny access for an incoming request. In this section, we will combine Basic Authentication with Django REST framework permission to set access control. You can refer Browsable API in Django REST Framework for Models, Serializers, and Views"
},
{
"code": null,
"e": 26581,
"s": 26522,
"text": "Let’s dig deep into the Django REST framework permissions."
},
{
"code": null,
"e": 26590,
"s": 26581,
"text": "AllowAny"
},
{
"code": null,
"e": 26606,
"s": 26590,
"text": "IsAuthenticated"
},
{
"code": null,
"e": 26618,
"s": 26606,
"text": "IsAdminUser"
},
{
"code": null,
"e": 26644,
"s": 26618,
"text": "IsAuthenticatedOrReadOnly"
},
{
"code": null,
"e": 26667,
"s": 26644,
"text": "DjangoModelPermissions"
},
{
"code": null,
"e": 26704,
"s": 26667,
"text": "DjangoModelPermissionsOrAnonReadOnly"
},
{
"code": null,
"e": 26728,
"s": 26704,
"text": "DjangoObjectPermissions"
},
{
"code": null,
"e": 26924,
"s": 26728,
"text": "The AllowAny permission class will allow unrestricted access, irrespective of whether the request was authenticated or unauthenticated. Here the permission settings default to unrestricted access"
},
{
"code": null,
"e": 27000,
"s": 26924,
"text": "'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.AllowAny',\n]"
},
{
"code": null,
"e": 27264,
"s": 27000,
"text": "You don’t need to set this permission, but it is advised to mention it to make the intention explicit. Apart from mentioning it globally, you can set the permission policy on a per-view basis. If you are using the APIView class-based views, the code is as follows"
},
{
"code": null,
"e": 27272,
"s": 27264,
"text": "Python3"
},
{
"code": "from rest_framework.permissions import AllowAnyfrom rest_framework.response import Responsefrom rest_framework.views import APIView class ClassBasedView(APIView): permission_classes = [AllowAny] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content)",
"e": 27618,
"s": 27272,
"text": null
},
{
"code": null,
"e": 27701,
"s": 27618,
"text": "While using the @api_view decorator with function-based views, the code as follows"
},
{
"code": null,
"e": 27709,
"s": 27701,
"text": "Python3"
},
{
"code": "from rest_framework.decorators import api_view, permission_classesfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Response @api_view(['GET'])@permission_classes([AllowAny])def function_view(request, format=None): content = { 'status': 'request was permitted' } return Response(content)",
"e": 28047,
"s": 27709,
"text": null
},
{
"code": null,
"e": 28437,
"s": 28047,
"text": "The IsAuthenticated permission class denies unauthenticated users to use the APIs for any operations. This ensures APIs accessibility only to registered users. Let’s use the IsAuthenticated class in our RESTful web service. Here, we can set the permission policy on a per-view basis. Let’s import and add the permission class in our RobotDetail and RobotList class. The code is as follows:"
},
{
"code": null,
"e": 28492,
"s": 28437,
"text": "from rest_framework.permissions import IsAuthenticated"
},
{
"code": null,
"e": 28500,
"s": 28492,
"text": "Python3"
},
{
"code": "class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' class RobotList(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list'",
"e": 28882,
"s": 28500,
"text": null
},
{
"code": null,
"e": 28968,
"s": 28882,
"text": "Let’s try to retrieve robots without providing any credentials. The HTTPie command is"
},
{
"code": null,
"e": 28986,
"s": 28968,
"text": "http :8000/robot/"
},
{
"code": null,
"e": 28993,
"s": 28986,
"text": "Output"
},
{
"code": null,
"e": 29222,
"s": 28993,
"text": "Since we haven’t provided any authentication details, the API has rejected the request that retrieves the robot details. Now we will create a new user using Django’s interactive shell and try the HTTPie command with credentials."
},
{
"code": null,
"e": 29317,
"s": 29222,
"text": "Note: You can refer to the article Create a User for Django Using Django’s Interactive Shell. "
},
{
"code": null,
"e": 29351,
"s": 29317,
"text": "The HTTPie command is as follows:"
},
{
"code": null,
"e": 29390,
"s": 29351,
"text": "http -a “sonu”:”sn@pswrd” :8000/robot/"
},
{
"code": null,
"e": 29397,
"s": 29390,
"text": "Output"
},
{
"code": null,
"e": 29458,
"s": 29397,
"text": "Let’s try an HTTPie command that creates a new robot entry. "
},
{
"code": null,
"e": 29649,
"s": 29458,
"text": "http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 1100′′ robot_category=”Articulated Robots” currency=”USD” price=25000 manufacturer=”ABB” manufacturing_date=”2020-05-10 00:00:00+00:00′′"
},
{
"code": null,
"e": 29656,
"s": 29649,
"text": "Output"
},
{
"code": null,
"e": 29915,
"s": 29656,
"text": "The IsAdminUser permission class will allow permission to users whose user.is_staff is True. This permission class ensures that the API is accessible to trusted administrators. Let’s make use of IsAdminUser permission class. Let’s import the permission class"
},
{
"code": null,
"e": 29966,
"s": 29915,
"text": "from rest_framework.permissions import IsAdminUser"
},
{
"code": null,
"e": 30040,
"s": 29966,
"text": " You can replace the RobotDetail and RobotList class with the below code."
},
{
"code": null,
"e": 30048,
"s": 30040,
"text": "Python3"
},
{
"code": "class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminUser] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' class RobotList(generics.ListCreateAPIView): permission_classes = [IsAdminUser] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list'",
"e": 30422,
"s": 30048,
"text": null
},
{
"code": null,
"e": 30496,
"s": 30422,
"text": "Now let’s try by providing normal user credentials. The HTTPie command is"
},
{
"code": null,
"e": 30535,
"s": 30496,
"text": "http -a “sonu”:”sn@pswrd” :8000/robot/"
},
{
"code": null,
"e": 30542,
"s": 30535,
"text": "Output"
},
{
"code": null,
"e": 30744,
"s": 30542,
"text": "You can notice the message saying “You do not have permission to perform this action”. This is because the user is not an administrator. Let’s provide our super admin credentials. The HTTPie command is"
},
{
"code": null,
"e": 30786,
"s": 30744,
"text": "http -a “admin”:”admin@123′′ :8000/robot/"
},
{
"code": null,
"e": 30793,
"s": 30786,
"text": "Output"
},
{
"code": null,
"e": 31111,
"s": 30793,
"text": "The IsAuthenticatedOrReadOnly permission class allows unauthorized users to perform safe methods, whereas authenticated users can perform any operations. This class is useful when we need to set read permissions for anonymous users and read/write permissions for authenticated users. Let’s import the permission class"
},
{
"code": null,
"e": 31176,
"s": 31111,
"text": "from rest_framework.permissions import IsAuthenticatedOrReadOnly"
},
{
"code": null,
"e": 31254,
"s": 31176,
"text": "Now, you can replace the RobotDetail and RobotList class with the below code."
},
{
"code": null,
"e": 31262,
"s": 31254,
"text": "Python3"
},
{
"code": "class RobotList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'",
"e": 31663,
"s": 31262,
"text": null
},
{
"code": null,
"e": 31768,
"s": 31663,
"text": "Let’s try to retrieve robot details without providing any credentials. The HTTPie command is as follows:"
},
{
"code": null,
"e": 31786,
"s": 31768,
"text": "http :8000/robot/"
},
{
"code": null,
"e": 31793,
"s": 31786,
"text": "Output"
},
{
"code": null,
"e": 31894,
"s": 31793,
"text": "Now let’s try to create a new robot without providing credentials. The HTTPie command is as follows:"
},
{
"code": null,
"e": 32063,
"s": 31894,
"text": "http POST :8000/robot/ name=”IRB 120′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2020-08-10 00:00:00+00:00′′"
},
{
"code": null,
"e": 32070,
"s": 32063,
"text": "Output"
},
{
"code": null,
"e": 32229,
"s": 32070,
"text": "The IsAuthenticatedOrReadOnly permission class permits only safe operations for unauthenticated users. Let’s create a new robot by providing user credentials."
},
{
"code": null,
"e": 32419,
"s": 32229,
"text": "http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 120′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2020-08-10 00:00:00+00:00′′"
},
{
"code": null,
"e": 32426,
"s": 32419,
"text": "Output"
},
{
"code": null,
"e": 32610,
"s": 32426,
"text": "In DjangoModelPermissions class, the authentication is granted only if the user is authenticated and has the relevant model permissions assigned. The model permissions are as follows"
},
{
"code": null,
"e": 32684,
"s": 32610,
"text": "The user must have the add permission on the model to make POST requests."
},
{
"code": null,
"e": 32770,
"s": 32684,
"text": "The user must have the change permission on the model to make PUT and PATCH requests."
},
{
"code": null,
"e": 32849,
"s": 32770,
"text": "The user must have the delete permission on the model to make DELETE requests."
},
{
"code": null,
"e": 33105,
"s": 32849,
"text": "By default, the class permits GET requests for authenticated users. DjangoModelPermissions class ties into Django’s standard django.contrib.auth model permissions. It must only be applied to views that have a .queryset property or get_queryset() method. "
},
{
"code": null,
"e": 33155,
"s": 33105,
"text": "You can import the DjangoModelPermissions class. "
},
{
"code": null,
"e": 33217,
"s": 33155,
"text": "from rest_framework.permissions import DjangoModelPermissions"
},
{
"code": null,
"e": 33288,
"s": 33217,
"text": "Next, replace the RobotDetail and RobotList class with the below code."
},
{
"code": null,
"e": 33296,
"s": 33288,
"text": "Python3"
},
{
"code": "class RobotList(generics.ListCreateAPIView): permission_classes = [DjangoModelPermissions] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [DjangoModelPermissions] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'",
"e": 33690,
"s": 33296,
"text": null
},
{
"code": null,
"e": 33780,
"s": 33690,
"text": "Let’s try to create a robot by providing user credentials. The HTTPie command as follows:"
},
{
"code": null,
"e": 33970,
"s": 33780,
"text": "http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 140′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2021-01-10 00:00:00+00:00′′"
},
{
"code": null,
"e": 33977,
"s": 33970,
"text": "Output"
},
{
"code": null,
"e": 34318,
"s": 33977,
"text": "You can notice, permission to create a robot is denied. This is because we haven’t set model-level permission for the given user. To set permission to add a robot, you can log in through the admin panel as a superuser and add permission by selecting the user under the Users section. Finally, save the changes. Sharing the screenshot below:"
},
{
"code": null,
"e": 34360,
"s": 34318,
"text": "Let’s try again the same HTTPie command. "
},
{
"code": null,
"e": 34550,
"s": 34360,
"text": "http -a “sonu”:”sn@pswrd” POST :8000/robot/ name=”IRB 140′′ robot_category=”Articulated Robots” currency=”USD” price=35000 manufacturer=”ABB” manufacturing_date=”2021-01-10 00:00:00+00:00′′"
},
{
"code": null,
"e": 34557,
"s": 34550,
"text": "Output"
},
{
"code": null,
"e": 34744,
"s": 34557,
"text": "DjangoModelPermissionsOrAnonReadOnly permission class is the same as that of the DjangoModelPermissions class except it allows unauthenticated users to have read-only access to the API. "
},
{
"code": null,
"e": 34805,
"s": 34744,
"text": "Let’s import the DjangoModelPermissionsOrAnonReadOnly class."
},
{
"code": null,
"e": 34881,
"s": 34805,
"text": "from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly"
},
{
"code": null,
"e": 34979,
"s": 34881,
"text": "Now you can add the permission class to RobotDetail and RobotList class. The code is as follows:"
},
{
"code": null,
"e": 34987,
"s": 34979,
"text": "Python3"
},
{
"code": "class RobotList(generics.ListCreateAPIView): permission_classes = [DjangoModelPermissionsOrAnonReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [DjangoModelPermissionsOrAnonReadOnly] queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'",
"e": 35409,
"s": 34987,
"text": null
},
{
"code": null,
"e": 35507,
"s": 35409,
"text": "Let’s try to retrieve robots without providing any credentials. The HTTPie command is as follows:"
},
{
"code": null,
"e": 35525,
"s": 35507,
"text": "http :8000/robot/"
},
{
"code": null,
"e": 35532,
"s": 35525,
"text": "Output"
},
{
"code": null,
"e": 36009,
"s": 35532,
"text": "The DjangoObjectPermissions allows per-object permissions on models, which can set permissions for individual rows in a table (model instances). The user must be authenticated to grant authorization and should be assigned with relevant per-object permissions and relevant model permissions. To set relevant per-object permissions, we need to subclass the DjangoObjectPermissions and implement the has_object_permission() method. The relevant model permissions are as follows:"
},
{
"code": null,
"e": 36083,
"s": 36009,
"text": "The user must have the add permission on the model to make POST requests."
},
{
"code": null,
"e": 36169,
"s": 36083,
"text": "The user must have the change permission on the model to make PUT and PATCH requests."
},
{
"code": null,
"e": 36248,
"s": 36169,
"text": "The user must have the delete permission on the model to make DELETE requests."
},
{
"code": null,
"e": 36431,
"s": 36248,
"text": "With DjangoModelPermissions you can create custom model permissions by overriding DjangoObjectPermissions. You can check Customizing Object Level Permission in Django REST Framework."
},
{
"code": null,
"e": 36443,
"s": 36431,
"text": "Django-REST"
},
{
"code": null,
"e": 36457,
"s": 36443,
"text": "Python Django"
},
{
"code": null,
"e": 36464,
"s": 36457,
"text": "Python"
},
{
"code": null,
"e": 36562,
"s": 36464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36594,
"s": 36562,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 36636,
"s": 36594,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 36678,
"s": 36636,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 36734,
"s": 36678,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 36761,
"s": 36734,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 36792,
"s": 36761,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 36821,
"s": 36792,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 36860,
"s": 36821,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 36896,
"s": 36860,
"text": "Python | Pandas dataframe.groupby()"
}
] |
C/C++ program to make a simple calculator? | A simple calculator is a calculator that performs some basic operations like ‘+’ , ‘-’ , ‘*’ , ‘/’. A calculator does basic operation in a fast way. We will use switch statement to make a calculator.
Operator − ‘+’ => 34 + 324 = 358
Operator − ‘-’ => 3874 - 324 = 3550
Operator − ‘*’ => 76 * 24 = 1824
Operator − ‘/’ => 645/5 = 129
#include <iostream<
using namespace std;
int main() {
char op = '+';
float a = 63, b= 7;
// cout << "Enter operator either + or - or * or /: ";
// cin >> op;
cout<<"The operator is "<<op<<endl;
// cout << "Enter two operands: ";
// cin>> a >> b;
cout<<"a = "<<a<<" b = "<<b<<endl;
switch(op) {
case '+':
cout <<"Sum of"<<a<<"and"<<b<<"is"<< a+b;
break;
case '-':
cout <<"Difference of"<<a<<"and"<<b<<"is"<<a-b;
break;
case '*':
cout <<"Product of"<<a<<"and"<<b<<"is"<<a*b;
break;
case '/':
cout <<"Division of"<<a<<"and"<<b<<"is"<<a/b;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
}
return 0;
}
The operator is +
a = 63 b = 7
Sum of63 and 7 is 70 | [
{
"code": null,
"e": 1262,
"s": 1062,
"text": "A simple calculator is a calculator that performs some basic operations like ‘+’ , ‘-’ , ‘*’ , ‘/’. A calculator does basic operation in a fast way. We will use switch statement to make a calculator."
},
{
"code": null,
"e": 1394,
"s": 1262,
"text": "Operator − ‘+’ => 34 + 324 = 358\nOperator − ‘-’ => 3874 - 324 = 3550\nOperator − ‘*’ => 76 * 24 = 1824\nOperator − ‘/’ => 645/5 = 129"
},
{
"code": null,
"e": 2226,
"s": 1394,
"text": "#include <iostream<\nusing namespace std;\nint main() {\n char op = '+';\n float a = 63, b= 7;\n // cout << \"Enter operator either + or - or * or /: \";\n // cin >> op;\n cout<<\"The operator is \"<<op<<endl;\n // cout << \"Enter two operands: \";\n // cin>> a >> b;\n cout<<\"a = \"<<a<<\" b = \"<<b<<endl;\n switch(op) {\n case '+':\n cout <<\"Sum of\"<<a<<\"and\"<<b<<\"is\"<< a+b;\n break;\n case '-':\n cout <<\"Difference of\"<<a<<\"and\"<<b<<\"is\"<<a-b;\n break;\n case '*':\n cout <<\"Product of\"<<a<<\"and\"<<b<<\"is\"<<a*b;\n break;\n case '/':\n cout <<\"Division of\"<<a<<\"and\"<<b<<\"is\"<<a/b;\n break;\n default:\n // If the operator is other than +, -, * or /, error message is shown\n cout << \"Error! operator is not correct\";\n break;\n }\n return 0;\n}"
},
{
"code": null,
"e": 2278,
"s": 2226,
"text": "The operator is +\na = 63 b = 7\nSum of63 and 7 is 70"
}
] |
How do we add a menu list in HTML? | Use the <menu> tag in HTML to add a menu list. The HTML <menu> tag is used for creating a menu list.
The HTML <menu> tag also supports the following additional attributes −
Note − This tag deprecated in HTML and redefined in HTML5
You can try to run the following code to add a menu list in HTML −
<!DOCTYPE html>
<html>
<head>
<title>HTML menu Tag</title>
</head>
<body>
<menu>
<li>ol - ordered list</li>
<li>ul - unordered list</li>
<li>dir - directory list</li>
<li>menu - menu list</li>
</menu>
</body>
</html> | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "Use the <menu> tag in HTML to add a menu list. The HTML <menu> tag is used for creating a menu list."
},
{
"code": null,
"e": 1235,
"s": 1163,
"text": "The HTML <menu> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 1293,
"s": 1235,
"text": "Note − This tag deprecated in HTML and redefined in HTML5"
},
{
"code": null,
"e": 1360,
"s": 1293,
"text": "You can try to run the following code to add a menu list in HTML −"
},
{
"code": null,
"e": 1643,
"s": 1360,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML menu Tag</title>\n </head>\n <body>\n <menu>\n <li>ol - ordered list</li>\n <li>ul - unordered list</li>\n <li>dir - directory list</li>\n <li>menu - menu list</li>\n </menu>\n </body>\n</html>"
}
] |
Inheritance in Python: Fundamentals for Data Scientists | by Erdem Isbilen | Towards Data Science | Class inheritance is an important concept in object-oriented programming. It enables us to extend the abilities of an existing class. To create a new class, we use an available class as a base and extend its functionality according to our needs. Since we build a new class by using methods and data definitions available in the base class, development & maintenance time reduces and code reusability increases.
This post will introduce you basics of class inheritance in Python.
Let’s write a Python3 code that contains a simple example of class inheritance;
import pandas as pdimport random# BASE CLASSclass CSVGetInfo: """ This class displays the summary of the tabular data contained in a CSV file """ instance_count = 0 # Initializer / Instance Attributes def __init__(self, path, file_name): CSVGetInfo.increase_instance_count() self.path = path self.file_name = file_name print("CSVGetInfo class object has been instantiated") # Instance Method def display_summary(self): data = pd.read_csv(self.path + self.file_name) print(self.file_name) print(data.head(self.generate_random_number(10))) print(data.info()) return data # Class Methods @classmethod def increase_instance_count(cls): cls.instance_count += 1 print(cls.instance_count) @classmethod def read_file_1(cls): return cls("/Users/erdemisbilen/Lessons/", "data_by_artists.csv") @classmethod def read_file_2(cls): return cls("/Users/erdemisbilen/Lessons/", "data_by_genres.csv") # Static Methods @staticmethod def generate_random_number(limit): return random.randint(1, limit)# SUB CLASSclass CSVGetColumnDetails(CSVGetInfo): """ This class displays the summary of a column in a tabular data contained in a CSV file """ # Initializer / Instance Attributes def __init__(self, path, file_name, column_name): CSVGetInfo.__init__(self, path, file_name) self.column_name = column_name print("CSVGetDetail class object has been instantiated") # Instance Method def display_column_summary(self): data = self.display_summary() print(data[self.column_name].describe()) @classmethod def read_file_1(cls, column_name): return cls("/Users/erdemisbilen/Lessons/", "data_by_artists.csv", column_name)if __name__ == '__main__': data = CSVGetColumnDetails.read_file_1("danceability") data.display_column_summary()
In our Python code above, we have CSVGetInfo base class which contains several methods and data definitions.
display_summary(self) instance method prints the summary of the tabular data contained in a CVS file by using the values provided in the path, and file_name.
There are also several class methods, read_file_1(cls), read_file_2(cls), and increase_instance_count(cls), to ease the object instantiation of the base class.
Consider that we want to create a new class, CSVGetColumnDetails, to get summary information of a specific column in a tabular data. We can write a new class starting from scratch, but a better way is to inherit and extend some of the methods and data definitions already available in CSVGetInfo class.
# BASE CLASSclass CSVGetInfo: .... ....# SUB CLASSclass CSVGetColumnDetails(CSVGetInfo): .... ....
class SubClassName(BaseClassName) is the Python inheritance syntax used to create a subclass. In our example, our base class is CSVGetInfo and our extended subclass is CSVGetColumnDetails.
We call __init__ method of our base class to instantiate the path and file_name attributes. We derive these attributes from our base class to our subclass.
The column_name attribute that is only available in our subclass level is instantiated with self notation representing CSVGetColumnDetails’s instances.
# Initializer / Instance Attributes def __init__(self, path, file_name, column_name): CSVGetInfo.__init__(self, path, file_name) self.column_name = column_name print("CSVGetDetail class object has been instantiated")
Then we create a new method in our subclass with the help of the display_summary() method derived from the base class. We use and extend the abilities of display_summary() in our subclass to define a new method.
# Instance Method def display_column_summary(self): data = self.display_summary() print(data[self.column_name].describe())
This new method in our subclass, display_column_summary(self), displays the summary of a specific column by using the data display_summary (derived from the base class) method returned. This subclass method also has a subclass attribute of column_name.
Note that we have read_file_1 class methods both defined in our base and subclass with the different implementations.
read_file_1 class method in the base class just passes path and file_name values to instantiate the base class objects whereas the one in the subclass instantiates the subclass objects with an additional argument, column_name.
This means that the read_file_1 method in the subclass overrides the same method available in the base class. When these methods are called, they perform their unique implementations.
# BASE CLASSclass CSVGetInfo: .... .... @classmethod def read_file_1(cls): return cls("/Users/erdemisbilen/Lessons/", "data_by_artists.csv")# SUB CLASSclass CSVGetColumnDetails(CSVGetInfo): .... .... @classmethod def read_file_1(cls, column_name): return cls("/Users/erdemisbilen/Lessons/", "data_by_artists.csv", column_name)
There may be some methods or attributes(instance variables) in the base class which are intended to be used only in the base class. They are called as private methods and named with double underbar convention, __privatemethodname. These methods should not be called outside of the base class including subclasses.
There may be also some other methods or attributes in the base class which are intended to be used only in base or subclass definitions. They are called as protected methods and named with single underbar convention, _protectedmethodname. These methods should only be called in base and subclass structures.
Inheritance increases code reusability and reduced development & maintenance time.
Inheritance allows us to define a class that takes and extends all the methods and data definitions available in a base class.
In this post, I explained the basics of class inheritance in Python.
The code in this post and the CSV files used are available in my GitHub repository.
I hope you found this post useful.
Thank you for reading! | [
{
"code": null,
"e": 583,
"s": 172,
"text": "Class inheritance is an important concept in object-oriented programming. It enables us to extend the abilities of an existing class. To create a new class, we use an available class as a base and extend its functionality according to our needs. Since we build a new class by using methods and data definitions available in the base class, development & maintenance time reduces and code reusability increases."
},
{
"code": null,
"e": 651,
"s": 583,
"text": "This post will introduce you basics of class inheritance in Python."
},
{
"code": null,
"e": 731,
"s": 651,
"text": "Let’s write a Python3 code that contains a simple example of class inheritance;"
},
{
"code": null,
"e": 2466,
"s": 731,
"text": "import pandas as pdimport random# BASE CLASSclass CSVGetInfo: \"\"\" This class displays the summary of the tabular data contained in a CSV file \"\"\" instance_count = 0 # Initializer / Instance Attributes def __init__(self, path, file_name): CSVGetInfo.increase_instance_count() self.path = path self.file_name = file_name print(\"CSVGetInfo class object has been instantiated\") # Instance Method def display_summary(self): data = pd.read_csv(self.path + self.file_name) print(self.file_name) print(data.head(self.generate_random_number(10))) print(data.info()) return data # Class Methods @classmethod def increase_instance_count(cls): cls.instance_count += 1 print(cls.instance_count) @classmethod def read_file_1(cls): return cls(\"/Users/erdemisbilen/Lessons/\", \"data_by_artists.csv\") @classmethod def read_file_2(cls): return cls(\"/Users/erdemisbilen/Lessons/\", \"data_by_genres.csv\") # Static Methods @staticmethod def generate_random_number(limit): return random.randint(1, limit)# SUB CLASSclass CSVGetColumnDetails(CSVGetInfo): \"\"\" This class displays the summary of a column in a tabular data contained in a CSV file \"\"\" # Initializer / Instance Attributes def __init__(self, path, file_name, column_name): CSVGetInfo.__init__(self, path, file_name) self.column_name = column_name print(\"CSVGetDetail class object has been instantiated\") # Instance Method def display_column_summary(self): data = self.display_summary() print(data[self.column_name].describe()) @classmethod def read_file_1(cls, column_name): return cls(\"/Users/erdemisbilen/Lessons/\", \"data_by_artists.csv\", column_name)if __name__ == '__main__': data = CSVGetColumnDetails.read_file_1(\"danceability\") data.display_column_summary()"
},
{
"code": null,
"e": 2575,
"s": 2466,
"text": "In our Python code above, we have CSVGetInfo base class which contains several methods and data definitions."
},
{
"code": null,
"e": 2733,
"s": 2575,
"text": "display_summary(self) instance method prints the summary of the tabular data contained in a CVS file by using the values provided in the path, and file_name."
},
{
"code": null,
"e": 2893,
"s": 2733,
"text": "There are also several class methods, read_file_1(cls), read_file_2(cls), and increase_instance_count(cls), to ease the object instantiation of the base class."
},
{
"code": null,
"e": 3196,
"s": 2893,
"text": "Consider that we want to create a new class, CSVGetColumnDetails, to get summary information of a specific column in a tabular data. We can write a new class starting from scratch, but a better way is to inherit and extend some of the methods and data definitions already available in CSVGetInfo class."
},
{
"code": null,
"e": 3295,
"s": 3196,
"text": "# BASE CLASSclass CSVGetInfo: .... ....# SUB CLASSclass CSVGetColumnDetails(CSVGetInfo): .... ...."
},
{
"code": null,
"e": 3484,
"s": 3295,
"text": "class SubClassName(BaseClassName) is the Python inheritance syntax used to create a subclass. In our example, our base class is CSVGetInfo and our extended subclass is CSVGetColumnDetails."
},
{
"code": null,
"e": 3640,
"s": 3484,
"text": "We call __init__ method of our base class to instantiate the path and file_name attributes. We derive these attributes from our base class to our subclass."
},
{
"code": null,
"e": 3792,
"s": 3640,
"text": "The column_name attribute that is only available in our subclass level is instantiated with self notation representing CSVGetColumnDetails’s instances."
},
{
"code": null,
"e": 4012,
"s": 3792,
"text": "# Initializer / Instance Attributes def __init__(self, path, file_name, column_name): CSVGetInfo.__init__(self, path, file_name) self.column_name = column_name print(\"CSVGetDetail class object has been instantiated\")"
},
{
"code": null,
"e": 4224,
"s": 4012,
"text": "Then we create a new method in our subclass with the help of the display_summary() method derived from the base class. We use and extend the abilities of display_summary() in our subclass to define a new method."
},
{
"code": null,
"e": 4349,
"s": 4224,
"text": "# Instance Method def display_column_summary(self): data = self.display_summary() print(data[self.column_name].describe())"
},
{
"code": null,
"e": 4602,
"s": 4349,
"text": "This new method in our subclass, display_column_summary(self), displays the summary of a specific column by using the data display_summary (derived from the base class) method returned. This subclass method also has a subclass attribute of column_name."
},
{
"code": null,
"e": 4720,
"s": 4602,
"text": "Note that we have read_file_1 class methods both defined in our base and subclass with the different implementations."
},
{
"code": null,
"e": 4947,
"s": 4720,
"text": "read_file_1 class method in the base class just passes path and file_name values to instantiate the base class objects whereas the one in the subclass instantiates the subclass objects with an additional argument, column_name."
},
{
"code": null,
"e": 5131,
"s": 4947,
"text": "This means that the read_file_1 method in the subclass overrides the same method available in the base class. When these methods are called, they perform their unique implementations."
},
{
"code": null,
"e": 5462,
"s": 5131,
"text": "# BASE CLASSclass CSVGetInfo: .... .... @classmethod def read_file_1(cls): return cls(\"/Users/erdemisbilen/Lessons/\", \"data_by_artists.csv\")# SUB CLASSclass CSVGetColumnDetails(CSVGetInfo): .... .... @classmethod def read_file_1(cls, column_name): return cls(\"/Users/erdemisbilen/Lessons/\", \"data_by_artists.csv\", column_name)"
},
{
"code": null,
"e": 5776,
"s": 5462,
"text": "There may be some methods or attributes(instance variables) in the base class which are intended to be used only in the base class. They are called as private methods and named with double underbar convention, __privatemethodname. These methods should not be called outside of the base class including subclasses."
},
{
"code": null,
"e": 6084,
"s": 5776,
"text": "There may be also some other methods or attributes in the base class which are intended to be used only in base or subclass definitions. They are called as protected methods and named with single underbar convention, _protectedmethodname. These methods should only be called in base and subclass structures."
},
{
"code": null,
"e": 6167,
"s": 6084,
"text": "Inheritance increases code reusability and reduced development & maintenance time."
},
{
"code": null,
"e": 6294,
"s": 6167,
"text": "Inheritance allows us to define a class that takes and extends all the methods and data definitions available in a base class."
},
{
"code": null,
"e": 6363,
"s": 6294,
"text": "In this post, I explained the basics of class inheritance in Python."
},
{
"code": null,
"e": 6447,
"s": 6363,
"text": "The code in this post and the CSV files used are available in my GitHub repository."
},
{
"code": null,
"e": 6482,
"s": 6447,
"text": "I hope you found this post useful."
}
] |
Design an Event Webpage using HTML & CSS - GeeksforGeeks | 07 Feb, 2022
Events webpage plays a vital role in promoting and booking for an event. In this article, we are going to build an event page, it will contain the details of the events like date, booking option and view more details button. We will use HTML to give the basic layout like title, details, buttons etc. and CSS will give a beautiful design to our layout like text-decoration, text color, background color, text alignment, margin, padding, box floating etc.
Approach:
We will create two div’s first for the left content (it will contain the details of the event) and the right one will have 3 boxes containing summary of events (like date, view more button etc.).
The left section containing the design has a header and text created using <h1> and <p> tag. The right section having 3 boxes contains – view more created using button, time created using span tag. It also contains a header and paragraph.
In CSS section, we will create box design using (box-sizing) for both left and right section, give background color, text alignment, text-decoration, and hover effect using transition effect. We will also give different background color to hover effects to
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> /* Styling the body */ body { margin: 0; padding: 0; } /* Styling section, giving background image and dimensions */ section { width: 100%; height: 100vh; background: url('https://media.geeksforgeeks.org/wp-content/uploads/20210408155049/gfg9.png'); background-size: cover; } /* Styling the left floating section */ section .leftBox { width: 50%; height: 100%; float: left; padding: 50px; box-sizing: border-box; } /* Styling the background of left floating section */ section .leftBox .content { color: #fff; background: rgba(0, 0, 0, 0.5); padding: 40px; transition: .5s; } /* Styling the hover effect of left floating section */ section .leftBox .content:hover { background: #e91e63; } /* Styling the header of left floating section */ section .leftBox .content h1 { margin: 0; padding: 0; font-size: 50px; text-transform: uppercase; } /* Styling the paragraph of left floating section */ section .leftBox .content p { margin: 10px 0 0; padding: 0; } /* Styling the three events section */ section .events { position: relative; width: 50%; height: 100%; background: rgba(0, 0, 0, 0.5); float: right; box-sizing: border-box; } /* Styling the links of the events section */ section .events ul { position: absolute; top: 50%; transform: translateY(-50%); margin: 0; padding: 40px; box-sizing: border-box; } /* Styling the lists of the event section */ section .events ul li { list-style: none; background: #fff; box-sizing: border-box; height: 200px; margin: 15px 0; } /* Styling the time class of events section */ section .events ul li .time { position: relative; padding: 20px; background: #262626; box-sizing: border-box; width: 30%; height: 100%; float: left; text-align: center; transition: .5s; } /* Styling the hover effect of events section */ section .events ul li:hover .time { background: #e91e63; } /* Styling the header of time class of events section */ section .events ul li .time h2 { position: absolute; margin: 0; padding: 0; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff; font-size: 60px; line-height: 30px; } /* Styling the texts of time class of events section */ section .events ul li .time h2 span { font-size: 30px; } /* Styling the details class of events section */ section .events ul li .details { padding: 20px; background: #fff; box-sizing: border-box; width: 70%; height: 100%; float: left; } /* Styling the header of the details class of events section */ section .events ul li .details h3 { position: relative; margin: 0; padding: 0; font-size: 22px; } /* Styling the lists of details class of events section */ section .events ul li .details p { position: relative; margin: 10px 0 0; padding: 0; font-size: 16px; } /* Styling the links of details class of events section */ section .events ul li .details a { display: inline-block; text-decoration: none; padding: 10px 15px; border: 1.5px solid #262626; margin-top: 8px; font-size: 18px; transition: .5s; } /* Styling the details class's hover effect */ section .events ul li .details a:hover { background: #e91e63; color: #fff; border-color: #e91e63; } </style></head> <body> <section> <div class="leftBox"> <div class="content"> <h1> Events and Shows </h1> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> </div> </div> <div class="events"> <ul> <li> <div class="time"> <h2> 15 <br><span>March</span> </h2> </div> <div class="details"> <h3> Where is the event happening? </h3> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <a href="#">View Details</a> </div> <div style="clear: both;"></div> </li> <li> <div class="time"> <h2> 27 <br><span>May</span> </h2> </div> <div class="details"> <h3> Where is the event happening? </h3> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <a href="#">View Details</a> </div> <div style="clear:both;"></div> </li> <li> <div class="time"> <h2> 12 <br><span>August</span> </h2> </div> <div class="details"> <h3> Where is the event happening? </h3> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <a href="#">View Details</a> </div> <div style="clear:both;"></div> </li> </ul> </div> </section></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.
as5853535
CSS-Properties
CSS-Questions
CSS-Selectors
HTML-Questions
HTML-Tags
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 31761,
"s": 31733,
"text": "\n07 Feb, 2022"
},
{
"code": null,
"e": 32216,
"s": 31761,
"text": "Events webpage plays a vital role in promoting and booking for an event. In this article, we are going to build an event page, it will contain the details of the events like date, booking option and view more details button. We will use HTML to give the basic layout like title, details, buttons etc. and CSS will give a beautiful design to our layout like text-decoration, text color, background color, text alignment, margin, padding, box floating etc."
},
{
"code": null,
"e": 32226,
"s": 32216,
"text": "Approach:"
},
{
"code": null,
"e": 32422,
"s": 32226,
"text": "We will create two div’s first for the left content (it will contain the details of the event) and the right one will have 3 boxes containing summary of events (like date, view more button etc.)."
},
{
"code": null,
"e": 32661,
"s": 32422,
"text": "The left section containing the design has a header and text created using <h1> and <p> tag. The right section having 3 boxes contains – view more created using button, time created using span tag. It also contains a header and paragraph."
},
{
"code": null,
"e": 32918,
"s": 32661,
"text": "In CSS section, we will create box design using (box-sizing) for both left and right section, give background color, text alignment, text-decoration, and hover effect using transition effect. We will also give different background color to hover effects to"
},
{
"code": null,
"e": 32927,
"s": 32918,
"text": "Example:"
},
{
"code": null,
"e": 32932,
"s": 32927,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Styling the body */ body { margin: 0; padding: 0; } /* Styling section, giving background image and dimensions */ section { width: 100%; height: 100vh; background: url('https://media.geeksforgeeks.org/wp-content/uploads/20210408155049/gfg9.png'); background-size: cover; } /* Styling the left floating section */ section .leftBox { width: 50%; height: 100%; float: left; padding: 50px; box-sizing: border-box; } /* Styling the background of left floating section */ section .leftBox .content { color: #fff; background: rgba(0, 0, 0, 0.5); padding: 40px; transition: .5s; } /* Styling the hover effect of left floating section */ section .leftBox .content:hover { background: #e91e63; } /* Styling the header of left floating section */ section .leftBox .content h1 { margin: 0; padding: 0; font-size: 50px; text-transform: uppercase; } /* Styling the paragraph of left floating section */ section .leftBox .content p { margin: 10px 0 0; padding: 0; } /* Styling the three events section */ section .events { position: relative; width: 50%; height: 100%; background: rgba(0, 0, 0, 0.5); float: right; box-sizing: border-box; } /* Styling the links of the events section */ section .events ul { position: absolute; top: 50%; transform: translateY(-50%); margin: 0; padding: 40px; box-sizing: border-box; } /* Styling the lists of the event section */ section .events ul li { list-style: none; background: #fff; box-sizing: border-box; height: 200px; margin: 15px 0; } /* Styling the time class of events section */ section .events ul li .time { position: relative; padding: 20px; background: #262626; box-sizing: border-box; width: 30%; height: 100%; float: left; text-align: center; transition: .5s; } /* Styling the hover effect of events section */ section .events ul li:hover .time { background: #e91e63; } /* Styling the header of time class of events section */ section .events ul li .time h2 { position: absolute; margin: 0; padding: 0; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff; font-size: 60px; line-height: 30px; } /* Styling the texts of time class of events section */ section .events ul li .time h2 span { font-size: 30px; } /* Styling the details class of events section */ section .events ul li .details { padding: 20px; background: #fff; box-sizing: border-box; width: 70%; height: 100%; float: left; } /* Styling the header of the details class of events section */ section .events ul li .details h3 { position: relative; margin: 0; padding: 0; font-size: 22px; } /* Styling the lists of details class of events section */ section .events ul li .details p { position: relative; margin: 10px 0 0; padding: 0; font-size: 16px; } /* Styling the links of details class of events section */ section .events ul li .details a { display: inline-block; text-decoration: none; padding: 10px 15px; border: 1.5px solid #262626; margin-top: 8px; font-size: 18px; transition: .5s; } /* Styling the details class's hover effect */ section .events ul li .details a:hover { background: #e91e63; color: #fff; border-color: #e91e63; } </style></head> <body> <section> <div class=\"leftBox\"> <div class=\"content\"> <h1> Events and Shows </h1> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassadors in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> </div> </div> <div class=\"events\"> <ul> <li> <div class=\"time\"> <h2> 15 <br><span>March</span> </h2> </div> <div class=\"details\"> <h3> Where is the event happening? </h3> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <a href=\"#\">View Details</a> </div> <div style=\"clear: both;\"></div> </li> <li> <div class=\"time\"> <h2> 27 <br><span>May</span> </h2> </div> <div class=\"details\"> <h3> Where is the event happening? </h3> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <a href=\"#\">View Details</a> </div> <div style=\"clear:both;\"></div> </li> <li> <div class=\"time\"> <h2> 12 <br><span>August</span> </h2> </div> <div class=\"details\"> <h3> Where is the event happening? </h3> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. </p> <a href=\"#\">View Details</a> </div> <div style=\"clear:both;\"></div> </li> </ul> </div> </section></body> </html>",
"e": 42605,
"s": 32932,
"text": null
},
{
"code": null,
"e": 42613,
"s": 42605,
"text": "Output:"
},
{
"code": null,
"e": 42750,
"s": 42613,
"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": 42760,
"s": 42750,
"text": "as5853535"
},
{
"code": null,
"e": 42775,
"s": 42760,
"text": "CSS-Properties"
},
{
"code": null,
"e": 42789,
"s": 42775,
"text": "CSS-Questions"
},
{
"code": null,
"e": 42803,
"s": 42789,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 42818,
"s": 42803,
"text": "HTML-Questions"
},
{
"code": null,
"e": 42828,
"s": 42818,
"text": "HTML-Tags"
},
{
"code": null,
"e": 42832,
"s": 42828,
"text": "CSS"
},
{
"code": null,
"e": 42837,
"s": 42832,
"text": "HTML"
},
{
"code": null,
"e": 42854,
"s": 42837,
"text": "Web Technologies"
},
{
"code": null,
"e": 42859,
"s": 42854,
"text": "HTML"
},
{
"code": null,
"e": 42957,
"s": 42859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43019,
"s": 42957,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 43069,
"s": 43019,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 43127,
"s": 43069,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 43175,
"s": 43127,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 43225,
"s": 43175,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 43287,
"s": 43225,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 43337,
"s": 43287,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 43397,
"s": 43337,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 43445,
"s": 43397,
"text": "How to update Node.js and NPM to next version ?"
}
] |
HTML DOM div object | The HTML DOM div object is associated with the HTML <div> element. Div is a general purpose block level element that allows us to group elements together to either apply style to them or to manipulate a group of HTML elements under a single tag name or id.
Following is the property for div object −
Following is the syntax for −
Creating a div object −
var p = document.createElement("DIV");
Let us look at an example for the HTML DOM div object −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Div object example</h2>
<p>click on the CREATE button to create a div element with some text in it.</p>
<button onclick="createDiv()">CREATE</button>
<script>
function createDiv() {
var d = document.createElement("DIV");
var txt = document.createTextNode("Sample Div element");
d.setAttribute("style", "margin:10px;width:200px;background-color: lightgreen;border:2px solid blue");
d.appendChild(txt);
document.body.appendChild(d);
}
</script>
</body>
</html>
This will produce the following output −
On clicking the CREATE button −
In the above example −
We have first created a button CREATE that will execute the createDiv() method when clicked by the user −
<button onclick="createDiv()">CREATE</button>
The createDiv() function creates a <div> element and assigns it to the variable d. It then creates a text node and assigns it to the variable txt. We then set the <div> element attributes using the setAttribute() method. The text node is then appended to the <div> element using the appendChild() method. The <div> element along with the text node is then appended as the document body child −
function createDiv() {
var d = document.createElement("DIV");
var txt = document.createTextNode("Sample Div element");
d.setAttribute("style", "margin:10px;width:200px;background-color: lightgreen;border:2px solid blue");
d.appendChild(txt);
document.body.appendChild(d);
} | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "The HTML DOM div object is associated with the HTML <div> element. Div is a general purpose block level element that allows us to group elements together to either apply style to them or to manipulate a group of HTML elements under a single tag name or id."
},
{
"code": null,
"e": 1362,
"s": 1319,
"text": "Following is the property for div object −"
},
{
"code": null,
"e": 1392,
"s": 1362,
"text": "Following is the syntax for −"
},
{
"code": null,
"e": 1416,
"s": 1392,
"text": "Creating a div object −"
},
{
"code": null,
"e": 1455,
"s": 1416,
"text": "var p = document.createElement(\"DIV\");"
},
{
"code": null,
"e": 1511,
"s": 1455,
"text": "Let us look at an example for the HTML DOM div object −"
},
{
"code": null,
"e": 1521,
"s": 1511,
"text": "Live Demo"
},
{
"code": null,
"e": 2050,
"s": 1521,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Div object example</h2>\n<p>click on the CREATE button to create a div element with some text in it.</p>\n<button onclick=\"createDiv()\">CREATE</button>\n<script>\n function createDiv() {\n var d = document.createElement(\"DIV\");\n var txt = document.createTextNode(\"Sample Div element\");\n d.setAttribute(\"style\", \"margin:10px;width:200px;background-color: lightgreen;border:2px solid blue\");\n d.appendChild(txt);\n document.body.appendChild(d);\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2091,
"s": 2050,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2123,
"s": 2091,
"text": "On clicking the CREATE button −"
},
{
"code": null,
"e": 2146,
"s": 2123,
"text": "In the above example −"
},
{
"code": null,
"e": 2252,
"s": 2146,
"text": "We have first created a button CREATE that will execute the createDiv() method when clicked by the user −"
},
{
"code": null,
"e": 2298,
"s": 2252,
"text": "<button onclick=\"createDiv()\">CREATE</button>"
},
{
"code": null,
"e": 2692,
"s": 2298,
"text": "The createDiv() function creates a <div> element and assigns it to the variable d. It then creates a text node and assigns it to the variable txt. We then set the <div> element attributes using the setAttribute() method. The text node is then appended to the <div> element using the appendChild() method. The <div> element along with the text node is then appended as the document body child −"
},
{
"code": null,
"e": 2981,
"s": 2692,
"text": "function createDiv() {\n var d = document.createElement(\"DIV\");\n var txt = document.createTextNode(\"Sample Div element\");\n d.setAttribute(\"style\", \"margin:10px;width:200px;background-color: lightgreen;border:2px solid blue\");\n d.appendChild(txt);\n document.body.appendChild(d);\n}"
}
] |
Optimization: Loss Function Under the Hood (Part I) | by Shuyu Luo | Towards Data Science | When building a machine learning model, some questions similar like these usually comes into my mind: How does a model being optimized? Why does Model A outperform Model B?
To answer them, I think one of entry points can be understanding loss functions of different models, and furthermore, being able to choose an appropriate loss function or self-define a loss function based on the goal of the project and the tolerance of error type. I will post a series of blogs discussing loss functions and optimization algorithms of a few common supervised learning models. I will try to explain in a way that is friendly to the audience who don’t have a strong mathematical background. Let’s start from Part I, Linear Regression.
For supervised learning, models are optimized by finding optimal coefficients that minimize cost function. Cost function is the sum of losses from each data point calculated with loss function. The model we choose to use is our hypothesis. Here is the hypothesis for Linear Regression model.
The most commonly used loss function for Linear Regression is Least Squared Error, and its cost function is also known as Mean Squared Error(MSE).
As we can see from the formula, cost function is a parabola curve. To minimize it, we need to find its vertex. It can be solved analytically or by using programming algorithms. In this blog, I will focus on one of the most popular programming solutions, Gradient Descent, to walk through the optimization process. Gradient Descent is pervasively applied in different models that takes steps based on a learning rate α, moving towards the vertex of the parabola to find the global minimum for Linear Regression, which is also known as the point with the slope equals to 0. So to get the slope, we take the derivative of cost function at each coefficient θ.
Next, continuously update each θ with a good amount of iterations along with the observation of reduction in cost function until it reaches a horizontal line. In reality, it is impossible for the slope to reach an exact value of 0 due to the chosen step size, but it can be close to 0 as much as possible depending on hyperparameters.
Now keep those concepts in mind, let’s use the real-world data (Boston Housing data from UCI Machine Learning Repository). Since I only demonstrate the optimization part in this blog, I will skip all the processes such as exploratory data analysis, feature engineering, etc., and directly go to data normalization being ready for prediction. Let’s take a look at the first few rows of data.
For explanation simplicity, I selected 2 features(RM: average number of rooms per dwelling, AGE: proportion of owner-occupied units built prior to 1940) to make the prediction, and target variable is MEDV(Median value of owner-occupied homes in $1000's). For calculation efficiency, I converted all the calculations to matrix format. Below are matrices for hypothesis, cost function, derivative of cost function, and the python query for matrix calculation.
# Instantiate a hypothesishypothesis = X@theta - y# Calculate cost functiondef cost(theta, X=X, y=y, m=m): cost = np.transpose((X@theta - y))@(X@theta - y) cost = (1/(2*m))*cost return cost# Calculate derivative of cost functiondef cost_dev(j, theta, X=X, y=y, m=m): dev = X[:, j]@(X@theta - y) dev = (1/m)*dev return dev
All coefficients are set to1 at the beginning. The query below returns 100,000 iterations to update coefficients simultaneously. When the trend starts to flatten out which means gradient descent has converged, and minimum of cost function has been reached.
# Assign a learning ratea = 0.001cost_list = []theta_temp = np.zeros(theta.shape)theta_list = []for i in range(100000): for j in range(len(theta)): theta_temp[j] = theta[j] - a*cost_dev(j, theta) theta = theta_temp theta_list.append(list(theta)) cost_val = cost(theta) cost_list.append(cost_val)
Can we make this trend better and be more confident to say the minimum is indeed reached? What would happen if we adjust learning rate to 0.0005 with 1,000,000 iterations.
The trend looks crazy. It’s not really a good demonstration of cost function, but we can be very confident about the result of optimization, assuming the minimum of MSE is reached with current setting. Let’s compare the coefficients just obtained from Gradient Descent algorithm manually to that obtained from Scikit-learn LinearRegression() with the same dataset.
Ta-da! They are almost the same. The goal of this blog is to unveil the basic optimization secret of machine learning model. There are many advanced variations of Gradient Descent and other algorithms have been applied in Scikit-learn packages. Of course, in most scenarios, there’s no need to be bothered by those mathematics. However, being able to understand loss function under the hood help us move forward to the next level as a machine learning engineer!
To be continued...... | [
{
"code": null,
"e": 220,
"s": 47,
"text": "When building a machine learning model, some questions similar like these usually comes into my mind: How does a model being optimized? Why does Model A outperform Model B?"
},
{
"code": null,
"e": 770,
"s": 220,
"text": "To answer them, I think one of entry points can be understanding loss functions of different models, and furthermore, being able to choose an appropriate loss function or self-define a loss function based on the goal of the project and the tolerance of error type. I will post a series of blogs discussing loss functions and optimization algorithms of a few common supervised learning models. I will try to explain in a way that is friendly to the audience who don’t have a strong mathematical background. Let’s start from Part I, Linear Regression."
},
{
"code": null,
"e": 1062,
"s": 770,
"text": "For supervised learning, models are optimized by finding optimal coefficients that minimize cost function. Cost function is the sum of losses from each data point calculated with loss function. The model we choose to use is our hypothesis. Here is the hypothesis for Linear Regression model."
},
{
"code": null,
"e": 1209,
"s": 1062,
"text": "The most commonly used loss function for Linear Regression is Least Squared Error, and its cost function is also known as Mean Squared Error(MSE)."
},
{
"code": null,
"e": 1865,
"s": 1209,
"text": "As we can see from the formula, cost function is a parabola curve. To minimize it, we need to find its vertex. It can be solved analytically or by using programming algorithms. In this blog, I will focus on one of the most popular programming solutions, Gradient Descent, to walk through the optimization process. Gradient Descent is pervasively applied in different models that takes steps based on a learning rate α, moving towards the vertex of the parabola to find the global minimum for Linear Regression, which is also known as the point with the slope equals to 0. So to get the slope, we take the derivative of cost function at each coefficient θ."
},
{
"code": null,
"e": 2200,
"s": 1865,
"text": "Next, continuously update each θ with a good amount of iterations along with the observation of reduction in cost function until it reaches a horizontal line. In reality, it is impossible for the slope to reach an exact value of 0 due to the chosen step size, but it can be close to 0 as much as possible depending on hyperparameters."
},
{
"code": null,
"e": 2591,
"s": 2200,
"text": "Now keep those concepts in mind, let’s use the real-world data (Boston Housing data from UCI Machine Learning Repository). Since I only demonstrate the optimization part in this blog, I will skip all the processes such as exploratory data analysis, feature engineering, etc., and directly go to data normalization being ready for prediction. Let’s take a look at the first few rows of data."
},
{
"code": null,
"e": 3049,
"s": 2591,
"text": "For explanation simplicity, I selected 2 features(RM: average number of rooms per dwelling, AGE: proportion of owner-occupied units built prior to 1940) to make the prediction, and target variable is MEDV(Median value of owner-occupied homes in $1000's). For calculation efficiency, I converted all the calculations to matrix format. Below are matrices for hypothesis, cost function, derivative of cost function, and the python query for matrix calculation."
},
{
"code": null,
"e": 3389,
"s": 3049,
"text": "# Instantiate a hypothesishypothesis = X@theta - y# Calculate cost functiondef cost(theta, X=X, y=y, m=m): cost = np.transpose((X@theta - y))@(X@theta - y) cost = (1/(2*m))*cost return cost# Calculate derivative of cost functiondef cost_dev(j, theta, X=X, y=y, m=m): dev = X[:, j]@(X@theta - y) dev = (1/m)*dev return dev"
},
{
"code": null,
"e": 3646,
"s": 3389,
"text": "All coefficients are set to1 at the beginning. The query below returns 100,000 iterations to update coefficients simultaneously. When the trend starts to flatten out which means gradient descent has converged, and minimum of cost function has been reached."
},
{
"code": null,
"e": 3984,
"s": 3646,
"text": "# Assign a learning ratea = 0.001cost_list = []theta_temp = np.zeros(theta.shape)theta_list = []for i in range(100000): for j in range(len(theta)): theta_temp[j] = theta[j] - a*cost_dev(j, theta) theta = theta_temp theta_list.append(list(theta)) cost_val = cost(theta) cost_list.append(cost_val)"
},
{
"code": null,
"e": 4156,
"s": 3984,
"text": "Can we make this trend better and be more confident to say the minimum is indeed reached? What would happen if we adjust learning rate to 0.0005 with 1,000,000 iterations."
},
{
"code": null,
"e": 4521,
"s": 4156,
"text": "The trend looks crazy. It’s not really a good demonstration of cost function, but we can be very confident about the result of optimization, assuming the minimum of MSE is reached with current setting. Let’s compare the coefficients just obtained from Gradient Descent algorithm manually to that obtained from Scikit-learn LinearRegression() with the same dataset."
},
{
"code": null,
"e": 4983,
"s": 4521,
"text": "Ta-da! They are almost the same. The goal of this blog is to unveil the basic optimization secret of machine learning model. There are many advanced variations of Gradient Descent and other algorithms have been applied in Scikit-learn packages. Of course, in most scenarios, there’s no need to be bothered by those mathematics. However, being able to understand loss function under the hood help us move forward to the next level as a machine learning engineer!"
}
] |
How to create a MenuBar in JavaFX? | A menu bar is a user interface element that holds all the menus, it is usually placed on the top. In JavaFX the javafx.scene.control.MenuBar class represents a menu bar. You can create a menu bar by instantiating this class.
A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class.
The MenuBar class contains an observable list which holds all the menus, you can get this list by invoking the getMenus() method.
You can create the required number of menus and add them to the observable list using the addAll() method as −
menuBar.getMenus().addAll(file, fileList, skin);
You can also pass them as parameters to the constructor while instantiating the MenuBar class as −
MenuBar menuBar = new menuBar(menu1, menu2, menu3);
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MenuBarExample extends Application {
public void start(Stage stage) {
//Creating file menu
Menu file = new Menu("File");
//Creating file menu items
MenuItem item1 = new MenuItem("Add Files");
MenuItem item2 = new MenuItem("Start Converting");
MenuItem item3 = new MenuItem("Stop Converting");
MenuItem item4 = new MenuItem("Remove File");
MenuItem item5 = new MenuItem("Exit");
//Adding all the menu items to the file menu
file.getItems().addAll(item1, item2, item3, item4, item5);
//Creating FileList menu
Menu fileList = new Menu("File List");
//Creating fileList menu items
MenuItem item6 = new MenuItem("Select All");
MenuItem item7 = new MenuItem("Invert Selection");
MenuItem item8 = new MenuItem("Remove");
//Adding all the items to File List menu
fileList.getItems().addAll(item6, item7, item8);
//Creating Skin menu
Menu skin = new Menu("_Skin");
//Creating skin menu items
MenuItem item9 = new MenuItem("Blue");
MenuItem item10 = new MenuItem("Red");
//Adding all elements to Skin menu
skin.getItems().addAll(item9, item10);
//Creating a menu bar
MenuBar menuBar = new MenuBar();
menuBar.setTranslateX(200);
menuBar.setTranslateY(20);
//Adding all the menus to the menu bar
menuBar.getMenus().addAll(file, fileList, skin);
//Setting the stage
Group root = new Group(menuBar);
Scene scene = new Scene(root, 595, 200, Color.BEIGE);
stage.setTitle("Menu Bar Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1287,
"s": 1062,
"text": "A menu bar is a user interface element that holds all the menus, it is usually placed on the top. In JavaFX the javafx.scene.control.MenuBar class represents a menu bar. You can create a menu bar by instantiating this class."
},
{
"code": null,
"e": 1422,
"s": 1287,
"text": "A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class."
},
{
"code": null,
"e": 1552,
"s": 1422,
"text": "The MenuBar class contains an observable list which holds all the menus, you can get this list by invoking the getMenus() method."
},
{
"code": null,
"e": 1663,
"s": 1552,
"text": "You can create the required number of menus and add them to the observable list using the addAll() method as −"
},
{
"code": null,
"e": 1712,
"s": 1663,
"text": "menuBar.getMenus().addAll(file, fileList, skin);"
},
{
"code": null,
"e": 1811,
"s": 1712,
"text": "You can also pass them as parameters to the constructor while instantiating the MenuBar class as −"
},
{
"code": null,
"e": 1863,
"s": 1811,
"text": "MenuBar menuBar = new menuBar(menu1, menu2, menu3);"
},
{
"code": null,
"e": 3851,
"s": 1863,
"text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Menu;\nimport javafx.scene.control.MenuBar;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class MenuBarExample extends Application {\n public void start(Stage stage) {\n //Creating file menu\n Menu file = new Menu(\"File\");\n //Creating file menu items\n MenuItem item1 = new MenuItem(\"Add Files\");\n MenuItem item2 = new MenuItem(\"Start Converting\");\n MenuItem item3 = new MenuItem(\"Stop Converting\");\n MenuItem item4 = new MenuItem(\"Remove File\");\n MenuItem item5 = new MenuItem(\"Exit\");\n //Adding all the menu items to the file menu\n file.getItems().addAll(item1, item2, item3, item4, item5);\n //Creating FileList menu\n Menu fileList = new Menu(\"File List\");\n //Creating fileList menu items\n MenuItem item6 = new MenuItem(\"Select All\");\n MenuItem item7 = new MenuItem(\"Invert Selection\");\n MenuItem item8 = new MenuItem(\"Remove\");\n //Adding all the items to File List menu\n fileList.getItems().addAll(item6, item7, item8);\n //Creating Skin menu\n Menu skin = new Menu(\"_Skin\");\n //Creating skin menu items\n MenuItem item9 = new MenuItem(\"Blue\");\n MenuItem item10 = new MenuItem(\"Red\");\n //Adding all elements to Skin menu\n skin.getItems().addAll(item9, item10);\n //Creating a menu bar\n MenuBar menuBar = new MenuBar();\n menuBar.setTranslateX(200);\n menuBar.setTranslateY(20);\n //Adding all the menus to the menu bar\n menuBar.getMenus().addAll(file, fileList, skin);\n //Setting the stage\n Group root = new Group(menuBar);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Menu Bar Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
CICS - READNEXT / READPREV | When we issue a STARTBR command, it does not make the records available. It just tells from where to start reading the file. To get the first record and sequence after that, we need to use the READNEXT command.
The FILE, INTO, and LENGTH parameters are defined in the same way as they are in the READ command. We only need the FILE parameter because CICS allows us to browse several files at once and this tells which one we want to read next.
The FILE, INTO, and LENGTH parameters are defined in the same way as they are in the READ command. We only need the FILE parameter because CICS allows us to browse several files at once and this tells which one we want to read next.
RIDFLD points to a data area into which the CICS will "feed back" the key of the record it just read.
RIDFLD points to a data area into which the CICS will "feed back" the key of the record it just read.
The READPREV command is almost like READNEXT, except that it lets us proceed backward through a data set instead of forward.
The READPREV command is almost like READNEXT, except that it lets us proceed backward through a data set instead of forward.
Following is the syntax of READNEXT / READPREV command −
EXEC CICS READNEXT/READPREV
FILE ('name')
INTO (data-value)
LENGTH (data-value)
RIDFLD (data-value)
END-EXEC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2137,
"s": 1926,
"text": "When we issue a STARTBR command, it does not make the records available. It just tells from where to start reading the file. To get the first record and sequence after that, we need to use the READNEXT command."
},
{
"code": null,
"e": 2370,
"s": 2137,
"text": "The FILE, INTO, and LENGTH parameters are defined in the same way as they are in the READ command. We only need the FILE parameter because CICS allows us to browse several files at once and this tells which one we want to read next."
},
{
"code": null,
"e": 2603,
"s": 2370,
"text": "The FILE, INTO, and LENGTH parameters are defined in the same way as they are in the READ command. We only need the FILE parameter because CICS allows us to browse several files at once and this tells which one we want to read next."
},
{
"code": null,
"e": 2705,
"s": 2603,
"text": "RIDFLD points to a data area into which the CICS will \"feed back\" the key of the record it just read."
},
{
"code": null,
"e": 2807,
"s": 2705,
"text": "RIDFLD points to a data area into which the CICS will \"feed back\" the key of the record it just read."
},
{
"code": null,
"e": 2932,
"s": 2807,
"text": "The READPREV command is almost like READNEXT, except that it lets us proceed backward through a data set instead of forward."
},
{
"code": null,
"e": 3057,
"s": 2932,
"text": "The READPREV command is almost like READNEXT, except that it lets us proceed backward through a data set instead of forward."
},
{
"code": null,
"e": 3114,
"s": 3057,
"text": "Following is the syntax of READNEXT / READPREV command −"
},
{
"code": null,
"e": 3236,
"s": 3114,
"text": "EXEC CICS READNEXT/READPREV\n FILE ('name')\n INTO (data-value)\n LENGTH (data-value)\n RIDFLD (data-value)\nEND-EXEC\n"
},
{
"code": null,
"e": 3243,
"s": 3236,
"text": " Print"
},
{
"code": null,
"e": 3254,
"s": 3243,
"text": " Add Notes"
}
] |
Stream Editor - Regular Expressions | It is the regular expressions that make SED powerful and efficient. A number of complex tasks can be solved with regular expressions. Any command-line expert knows the power of regular expressions.
Like many other GNU/Linux utilities, SED too supports regular expressions, which are often referred to as as regex. This chapter describes regular expressions in detail. The chapter is divided into three sections: Standard regular expressions, POSIX classes of regular expressions, and Meta characters.
In regular expressions terminology, the caret(^) symbol matches the start of a line. The following example prints all the lines that start with the pattern "The".
[jerry]$ sed -n '/^The/ p' books.txt
On executing the above code, you get the following result:
The Two Towers, J. R. R. Tolkien
The Alchemist, Paulo Coelho
The Fellowship of the Ring, J. R. R. Tolkien
The Pilgrimage, Paulo Coelho
End of line is represented by the dollar($) symbol. The following example prints the lines that end with "Coelho".
[jerry]$ sed -n '/Coelho$/ p' books.txt
On executing the above code, you get the following result:
The Alchemist, Paulo Coelho
The Pilgrimage, Paulo Coelho
The Dot(.) matches any single character except the end of line character. The following example prints all three letter words that end with the character "t".
[jerry]$ echo -e "cat\nbat\nrat\nmat\nbatting\nrats\nmats" | sed -n '/^..t$/p'
On executing the above code, you get the following result:
cat
bat
rat
mat
In regular expression terminology, a character set is represented by square brackets ([]). It is used to match only one out of several characters. The following example matches the patterns "Call" and "Tall" but not "Ball".
[jerry]$ echo -e "Call\nTall\nBall" | sed -n '/[CT]all/ p'
On executing the above code, you get the following result:
Call
Tall
In exclusive set, the caret negates the set of characters in the square brackets. The following example prints only "Ball".
[jerry]$ echo -e "Call\nTall\nBall" | sed -n '/[^CT]all/ p'
On executing the above code, you get the following result:
Ball
When a character range is provided, the regular expression matches any character within the range specified in square brackets. The following example matches "Call" and "Tall" but not "Ball".
[jerry]$ echo -e "Call\nTall\nBall" | sed -n '/[C-Z]all/ p'
On executing the above code, you get the following result:
Call
Tall
Now let us modify the range to "A-P" and observe the result.
[jerry]$ echo -e "Call\nTall\nBall" | sed -n '/[A-P]all/ p'
On executing the above code, you get the following result:
Call
Ball
In SED, the question mark (\?) matches zero or one occurrence of the preceding character. The following example matches "Behaviour" as well as "Behavior". Here, we made "u" as an optional character by using "\?".
[jerry]$ echo -e "Behaviour\nBehavior" | sed -n '/Behaviou\?r/ p'
On executing the above code, you get the following result:
Behaviour
Behavior
In SED, the plus symbol(\+) matches one or more occurrences of the preceding character. The following example matches one or more occurrences of "2".
[jerry]$ echo -e "111\n22\n123\n234\n456\n222" | sed -n '/2\+/ p'
On executing the above code, you get the following result:
22
123
234
222
Asterisks (*) matches the zero or more occurrence of the preceding character. The following example matches "ca", "cat", "catt", and so on.
[jerry]$ echo -e "ca\ncat" | sed -n '/cat*/ p'
On executing the above code, you get the following result:
ca
cat
{n} matches exactly "n" occurrences of the preceding character. The following example prints only three digit numbers. But before that, you need to create the following file which contains only numbers.
[jerry]$ cat numbers.txt
On executing the above code, you get the following result:
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
Let us write the SED expression.
[jerry]$ sed -n '/^[0-9]\{3\}$/ p' numbers.txt
On executing the above code, you get the following result:
100
Note that the pair of curly braces is escaped by the "\" character.
{n,} matches at least "n" occurrences of the preceding character. The following example prints all the numbers greater than or equal to five digits.
[jerry]$ sed -n '/^[0-9]\{5,\}$/ p' numbers.txt
On executing the above code, you get the following result:
10000
100000
1000000
10000000
100000000
1000000000
{m, n} matches at least "m" and at most "n" occurrences of the preceding character. The following example prints all the numbers having at least five digits but not more than eight digits.
[jerry]$ sed -n '/^[0-9]\{5,8\}$/ p' numbers.txt
On executing the above code, you get the following result:
10000
100000
1000000
10000000
In SED, the pipe character behaves like logical OR operation. It matches items from either side of the pipe. The following example either matches "str1" or "str3".
[jerry]$ echo -e "str1\nstr2\nstr3\nstr4" | sed -n '/str\(1\|3\)/ p'
On executing the above code, you get the following result:
str1
str3
Note that the pair of the parenthesis and pipe (|) is escaped by the "\" character.
There are certain special characters. For example, newline is represented by "\n", carriage return is represented by "\r", and so on. To use these characters into regular ASCII context, we have to escape them using the backward slash(\) character. This chapter illustrates escaping of special characters.
The following example matches the pattern "\".
[jerry]$ echo 'str1\str2' | sed -n '/\\/ p'
On executing the above code, you get the following result:
str1\str2
The following example matches the new line character.
[jerry]$ echo 'str1\nstr2' | sed -n '/\\n/ p'
On executing the above code, you get the following result:
str1\nstr2
The following example matches the carriage return.
[jerry]$ echo 'str1\rstr2' | sed -n '/\\r/ p'
On executing the above code, you get the following result:
str1\rstr2
This matches a character whose decimal ASCII value is "nnn". The following example matches only the character "a".
[jerry]$ echo -e "a\nb\nc" | sed -n '/\d97/ p'
On executing the above code, you get the following result:
a
This matches a character whose octal ASCII value is "nnn". The following example matches only the character "b".
[jerry]$ echo -e "a\nb\nc" | sed -n '/\o142/ p'
On executing the above code, you get the following result:
b
This matches a character whose hexadecimal ASCII value is "nnn". The following example matches only the character "c".
[jerry]$ echo -e "a\nb\nc" | sed -n '/\x63/ p'
On executing the above code, you get the following result:
c
There are certain reserved words which have special meaning. These reserved words are referred to as POSIX classes of regular expression. This section describes the POSIX classes supported by SED.
It implies alphabetical and numeric characters. The following example matches only "One" and "123", but does not match the tab character.
[jerry]$ echo -e "One\n123\n\t" | sed -n '/[[:alnum:]]/ p'
On executing the above code, you get the following result:
One
123
It implies alphabetical characters only. The following example matches only the word "One".
[jerry]$ echo -e "One\n123\n\t" | sed -n '/[[:alpha:]]/ p'
On executing the above code, you get the following result:
One
It implies blank character which can be either space or tab. The following example matches only the tab character.
[jerry]$ echo -e "One\n123\n\t" | sed -n '/[[:space:]]/ p' | cat -vte
On executing the above code, you get the following result:
^I$
Note that the command "cat -vte" is used to show tab characters (^I).
It implies decimal numbers only. The following example matches only digit "123".
[jerry]$ echo -e "abc\n123\n\t" | sed -n '/[[:digit:]]/ p'
On executing the above code, you get the following result:
123
It implies lowercase letters only. The following example matches only "one".
[jerry]$ echo -e "one\nTWO\n\t" | sed -n '/[[:lower:]]/ p'
On executing the above code, you get the following result:
one
It implies uppercase letters only. The following example matches only "TWO".
[jerry]$ echo -e "one\nTWO\n\t" | sed -n '/[[:upper:]]/ p'
On executing the above code, you get the following result:
TWO
It implies punctuation marks which include non-space or alphanumeric characters
[jerry]$ echo -e "One,Two\nThree\nFour" | sed -n '/[[:punct:]]/ p'
On executing the above code, you get the following result:
One,Two
It implies whitespace characters. The following example illustrates this.
[jerry]$ echo -e "One\n123\f\t" | sed -n '/[[:space:]]/ p' | cat -vte
On executing the above code, you get the following result:
123^L^I$
Like traditional regular expressions, SED also supports metacharacters. These are Perl style regular expressions. Note that metacharacter support is GNU SED specific and may not work with other variants of SED. Let us discuss metacharacters in detail.
In regular expression terminology, "\b" matches the word boundary. For example, "\bthe\b" matches "the" but not "these", "there", "they", "then", and so on. The following example illustrates this.
[jerry]$ echo -e "these\nthe\nthey\nthen" | sed -n '/\bthe\b/ p'
On executing the above code, you get the following result:
the
In regular expression terminology, "\B" matches non-word boundary. For example, "the\B" matches "these" and "they" but not "the". The following example illustrates this.
[jerry]$ echo -e "these\nthe\nthey" | sed -n '/the\B/ p'
On executing the above code, you get the following result:
these
they
In SED, "\s" implies single whitespace character. The following example matches "Line\t1" but does not match "Line1".
[jerry]$ echo -e "Line\t1\nLine2" | sed -n '/Line\s/ p'
On executing the above code, you get the following result:
Line 1
In SED, "\S" implies single whitespace character. The following example matches "Line2" but does not match "Line\t1".
[jerry]$ echo -e "Line\t1\nLine2" | sed -n '/Line\S/ p'
On executing the above code, you get the following result:
Line2
In SED, "\w" implies single word character, i.e., alphabetical characters, digits, and underscore (_). The following example illustrates this.
[jerry]$ echo -e "One\n123\n1_2\n&;#" | sed -n '/\w/ p'
On executing the above code, you get the following result:
One
123
1_2
In SED, "\W" implies single non-word character which is exactly opposite to "\w". The following example illustrates this.
[jerry]$ echo -e "One\n123\n1_2\n&;#" | sed -n '/\W/ p'
On executing the above code, you get the following result:
&;#
In SED, "\`" implies the beginning of the pattern space. The following example matches only the word "One".
[jerry]$ echo -e "One\nTwo One" | sed -n '/\`One/ p'
On executing the above code, you get the following result:
One
53 Lectures
3.5 hours
Senol Atac
14 Lectures
44 mins
Zach Miller
13 Lectures
2 hours
Sandip Bhattacharya
28 Lectures
1 hours
PARTHA MAJUMDAR
16 Lectures
1.5 hours
Taurius Litvinavicius
38 Lectures
2 hours
Davida Shensky
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2021,
"s": 1823,
"text": "It is the regular expressions that make SED powerful and efficient. A number of complex tasks can be solved with regular expressions. Any command-line expert knows the power of regular expressions."
},
{
"code": null,
"e": 2324,
"s": 2021,
"text": "Like many other GNU/Linux utilities, SED too supports regular expressions, which are often referred to as as regex. This chapter describes regular expressions in detail. The chapter is divided into three sections: Standard regular expressions, POSIX classes of regular expressions, and Meta characters."
},
{
"code": null,
"e": 2487,
"s": 2324,
"text": "In regular expressions terminology, the caret(^) symbol matches the start of a line. The following example prints all the lines that start with the pattern \"The\"."
},
{
"code": null,
"e": 2525,
"s": 2487,
"text": "[jerry]$ sed -n '/^The/ p' books.txt\n"
},
{
"code": null,
"e": 2584,
"s": 2525,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 2723,
"s": 2584,
"text": "The Two Towers, J. R. R. Tolkien \nThe Alchemist, Paulo Coelho \nThe Fellowship of the Ring, J. R. R. Tolkien \nThe Pilgrimage, Paulo Coelho\n"
},
{
"code": null,
"e": 2838,
"s": 2723,
"text": "End of line is represented by the dollar($) symbol. The following example prints the lines that end with \"Coelho\"."
},
{
"code": null,
"e": 2880,
"s": 2838,
"text": "[jerry]$ sed -n '/Coelho$/ p' books.txt \n"
},
{
"code": null,
"e": 2939,
"s": 2880,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 2998,
"s": 2939,
"text": "The Alchemist, Paulo Coelho \nThe Pilgrimage, Paulo Coelho\n"
},
{
"code": null,
"e": 3157,
"s": 2998,
"text": "The Dot(.) matches any single character except the end of line character. The following example prints all three letter words that end with the character \"t\"."
},
{
"code": null,
"e": 3238,
"s": 3157,
"text": "[jerry]$ echo -e \"cat\\nbat\\nrat\\nmat\\nbatting\\nrats\\nmats\" | sed -n '/^..t$/p' \n"
},
{
"code": null,
"e": 3297,
"s": 3238,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 3317,
"s": 3297,
"text": "cat \nbat \nrat \nmat\n"
},
{
"code": null,
"e": 3541,
"s": 3317,
"text": "In regular expression terminology, a character set is represented by square brackets ([]). It is used to match only one out of several characters. The following example matches the patterns \"Call\" and \"Tall\" but not \"Ball\"."
},
{
"code": null,
"e": 3601,
"s": 3541,
"text": "[jerry]$ echo -e \"Call\\nTall\\nBall\" | sed -n '/[CT]all/ p'\n"
},
{
"code": null,
"e": 3660,
"s": 3601,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 3672,
"s": 3660,
"text": "Call \nTall\n"
},
{
"code": null,
"e": 3796,
"s": 3672,
"text": "In exclusive set, the caret negates the set of characters in the square brackets. The following example prints only \"Ball\"."
},
{
"code": null,
"e": 3857,
"s": 3796,
"text": "[jerry]$ echo -e \"Call\\nTall\\nBall\" | sed -n '/[^CT]all/ p'\n"
},
{
"code": null,
"e": 3916,
"s": 3857,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 3923,
"s": 3916,
"text": "Ball \n"
},
{
"code": null,
"e": 4115,
"s": 3923,
"text": "When a character range is provided, the regular expression matches any character within the range specified in square brackets. The following example matches \"Call\" and \"Tall\" but not \"Ball\"."
},
{
"code": null,
"e": 4177,
"s": 4115,
"text": "[jerry]$ echo -e \"Call\\nTall\\nBall\" | sed -n '/[C-Z]all/ p' \n"
},
{
"code": null,
"e": 4236,
"s": 4177,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 4248,
"s": 4236,
"text": "Call \nTall\n"
},
{
"code": null,
"e": 4309,
"s": 4248,
"text": "Now let us modify the range to \"A-P\" and observe the result."
},
{
"code": null,
"e": 4371,
"s": 4309,
"text": "[jerry]$ echo -e \"Call\\nTall\\nBall\" | sed -n '/[A-P]all/ p' \n"
},
{
"code": null,
"e": 4430,
"s": 4371,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 4442,
"s": 4430,
"text": "Call \nBall\n"
},
{
"code": null,
"e": 4655,
"s": 4442,
"text": "In SED, the question mark (\\?) matches zero or one occurrence of the preceding character. The following example matches \"Behaviour\" as well as \"Behavior\". Here, we made \"u\" as an optional character by using \"\\?\"."
},
{
"code": null,
"e": 4723,
"s": 4655,
"text": "[jerry]$ echo -e \"Behaviour\\nBehavior\" | sed -n '/Behaviou\\?r/ p' \n"
},
{
"code": null,
"e": 4782,
"s": 4723,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 4803,
"s": 4782,
"text": "Behaviour \nBehavior\n"
},
{
"code": null,
"e": 4953,
"s": 4803,
"text": "In SED, the plus symbol(\\+) matches one or more occurrences of the preceding character. The following example matches one or more occurrences of \"2\"."
},
{
"code": null,
"e": 5021,
"s": 4953,
"text": "[jerry]$ echo -e \"111\\n22\\n123\\n234\\n456\\n222\" | sed -n '/2\\+/ p'\n"
},
{
"code": null,
"e": 5080,
"s": 5021,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 5100,
"s": 5080,
"text": "22 \n123 \n234 \n222 \n"
},
{
"code": null,
"e": 5240,
"s": 5100,
"text": "Asterisks (*) matches the zero or more occurrence of the preceding character. The following example matches \"ca\", \"cat\", \"catt\", and so on."
},
{
"code": null,
"e": 5289,
"s": 5240,
"text": "[jerry]$ echo -e \"ca\\ncat\" | sed -n '/cat*/ p' \n"
},
{
"code": null,
"e": 5348,
"s": 5289,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 5358,
"s": 5348,
"text": "ca \ncat \n"
},
{
"code": null,
"e": 5561,
"s": 5358,
"text": "{n} matches exactly \"n\" occurrences of the preceding character. The following example prints only three digit numbers. But before that, you need to create the following file which contains only numbers."
},
{
"code": null,
"e": 5588,
"s": 5561,
"text": "[jerry]$ cat numbers.txt \n"
},
{
"code": null,
"e": 5647,
"s": 5588,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 5722,
"s": 5647,
"text": "1 \n10 \n100 \n1000 \n10000 \n100000 \n1000000 \n10000000 \n100000000 \n1000000000\n"
},
{
"code": null,
"e": 5755,
"s": 5722,
"text": "Let us write the SED expression."
},
{
"code": null,
"e": 5804,
"s": 5755,
"text": "[jerry]$ sed -n '/^[0-9]\\{3\\}$/ p' numbers.txt \n"
},
{
"code": null,
"e": 5863,
"s": 5804,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 5868,
"s": 5863,
"text": "100\n"
},
{
"code": null,
"e": 5936,
"s": 5868,
"text": "Note that the pair of curly braces is escaped by the \"\\\" character."
},
{
"code": null,
"e": 6085,
"s": 5936,
"text": "{n,} matches at least \"n\" occurrences of the preceding character. The following example prints all the numbers greater than or equal to five digits."
},
{
"code": null,
"e": 6134,
"s": 6085,
"text": "[jerry]$ sed -n '/^[0-9]\\{5,\\}$/ p' numbers.txt\n"
},
{
"code": null,
"e": 6193,
"s": 6134,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 6250,
"s": 6193,
"text": "10000 \n100000 \n1000000\n10000000 \n100000000 \n1000000000 \n"
},
{
"code": null,
"e": 6439,
"s": 6250,
"text": "{m, n} matches at least \"m\" and at most \"n\" occurrences of the preceding character. The following example prints all the numbers having at least five digits but not more than eight digits."
},
{
"code": null,
"e": 6489,
"s": 6439,
"text": "[jerry]$ sed -n '/^[0-9]\\{5,8\\}$/ p' numbers.txt\n"
},
{
"code": null,
"e": 6548,
"s": 6489,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 6583,
"s": 6548,
"text": "10000 \n100000 \n1000000 \n10000000 \n"
},
{
"code": null,
"e": 6747,
"s": 6583,
"text": "In SED, the pipe character behaves like logical OR operation. It matches items from either side of the pipe. The following example either matches \"str1\" or \"str3\"."
},
{
"code": null,
"e": 6818,
"s": 6747,
"text": "[jerry]$ echo -e \"str1\\nstr2\\nstr3\\nstr4\" | sed -n '/str\\(1\\|3\\)/ p' \n"
},
{
"code": null,
"e": 6877,
"s": 6818,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 6889,
"s": 6877,
"text": "str1 \nstr3\n"
},
{
"code": null,
"e": 6973,
"s": 6889,
"text": "Note that the pair of the parenthesis and pipe (|) is escaped by the \"\\\" character."
},
{
"code": null,
"e": 7278,
"s": 6973,
"text": "There are certain special characters. For example, newline is represented by \"\\n\", carriage return is represented by \"\\r\", and so on. To use these characters into regular ASCII context, we have to escape them using the backward slash(\\) character. This chapter illustrates escaping of special characters."
},
{
"code": null,
"e": 7325,
"s": 7278,
"text": "The following example matches the pattern \"\\\"."
},
{
"code": null,
"e": 7370,
"s": 7325,
"text": "[jerry]$ echo 'str1\\str2' | sed -n '/\\\\/ p'\n"
},
{
"code": null,
"e": 7430,
"s": 7370,
"text": "On executing the above code, you get the following result: "
},
{
"code": null,
"e": 7442,
"s": 7430,
"text": "str1\\str2 \n"
},
{
"code": null,
"e": 7496,
"s": 7442,
"text": "The following example matches the new line character."
},
{
"code": null,
"e": 7543,
"s": 7496,
"text": "[jerry]$ echo 'str1\\nstr2' | sed -n '/\\\\n/ p'\n"
},
{
"code": null,
"e": 7602,
"s": 7543,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 7614,
"s": 7602,
"text": "str1\\nstr2\n"
},
{
"code": null,
"e": 7665,
"s": 7614,
"text": "The following example matches the carriage return."
},
{
"code": null,
"e": 7712,
"s": 7665,
"text": "[jerry]$ echo 'str1\\rstr2' | sed -n '/\\\\r/ p'\n"
},
{
"code": null,
"e": 7771,
"s": 7712,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 7783,
"s": 7771,
"text": "str1\\rstr2\n"
},
{
"code": null,
"e": 7898,
"s": 7783,
"text": "This matches a character whose decimal ASCII value is \"nnn\". The following example matches only the character \"a\"."
},
{
"code": null,
"e": 7946,
"s": 7898,
"text": "[jerry]$ echo -e \"a\\nb\\nc\" | sed -n '/\\d97/ p'\n"
},
{
"code": null,
"e": 8006,
"s": 7946,
"text": "On executing the above code, you get the following result: "
},
{
"code": null,
"e": 8009,
"s": 8006,
"text": "a\n"
},
{
"code": null,
"e": 8122,
"s": 8009,
"text": "This matches a character whose octal ASCII value is \"nnn\". The following example matches only the character \"b\"."
},
{
"code": null,
"e": 8172,
"s": 8122,
"text": "[jerry]$ echo -e \"a\\nb\\nc\" | sed -n '/\\o142/ p' \n"
},
{
"code": null,
"e": 8231,
"s": 8172,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 8235,
"s": 8231,
"text": "b \n"
},
{
"code": null,
"e": 8354,
"s": 8235,
"text": "This matches a character whose hexadecimal ASCII value is \"nnn\". The following example matches only the character \"c\"."
},
{
"code": null,
"e": 8402,
"s": 8354,
"text": "[jerry]$ echo -e \"a\\nb\\nc\" | sed -n '/\\x63/ p'\n"
},
{
"code": null,
"e": 8461,
"s": 8402,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 8464,
"s": 8461,
"text": "c\n"
},
{
"code": null,
"e": 8661,
"s": 8464,
"text": "There are certain reserved words which have special meaning. These reserved words are referred to as POSIX classes of regular expression. This section describes the POSIX classes supported by SED."
},
{
"code": null,
"e": 8799,
"s": 8661,
"text": "It implies alphabetical and numeric characters. The following example matches only \"One\" and \"123\", but does not match the tab character."
},
{
"code": null,
"e": 8859,
"s": 8799,
"text": "[jerry]$ echo -e \"One\\n123\\n\\t\" | sed -n '/[[:alnum:]]/ p'\n"
},
{
"code": null,
"e": 8918,
"s": 8859,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 8928,
"s": 8918,
"text": "One \n123\n"
},
{
"code": null,
"e": 9020,
"s": 8928,
"text": "It implies alphabetical characters only. The following example matches only the word \"One\"."
},
{
"code": null,
"e": 9080,
"s": 9020,
"text": "[jerry]$ echo -e \"One\\n123\\n\\t\" | sed -n '/[[:alpha:]]/ p'\n"
},
{
"code": null,
"e": 9139,
"s": 9080,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 9145,
"s": 9139,
"text": "One \n"
},
{
"code": null,
"e": 9260,
"s": 9145,
"text": "It implies blank character which can be either space or tab. The following example matches only the tab character."
},
{
"code": null,
"e": 9331,
"s": 9260,
"text": "[jerry]$ echo -e \"One\\n123\\n\\t\" | sed -n '/[[:space:]]/ p' | cat -vte\n"
},
{
"code": null,
"e": 9390,
"s": 9331,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 9395,
"s": 9390,
"text": "^I$\n"
},
{
"code": null,
"e": 9465,
"s": 9395,
"text": "Note that the command \"cat -vte\" is used to show tab characters (^I)."
},
{
"code": null,
"e": 9546,
"s": 9465,
"text": "It implies decimal numbers only. The following example matches only digit \"123\"."
},
{
"code": null,
"e": 9607,
"s": 9546,
"text": "[jerry]$ echo -e \"abc\\n123\\n\\t\" | sed -n '/[[:digit:]]/ p' \n"
},
{
"code": null,
"e": 9666,
"s": 9607,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 9672,
"s": 9666,
"text": "123 \n"
},
{
"code": null,
"e": 9749,
"s": 9672,
"text": "It implies lowercase letters only. The following example matches only \"one\"."
},
{
"code": null,
"e": 9810,
"s": 9749,
"text": "[jerry]$ echo -e \"one\\nTWO\\n\\t\" | sed -n '/[[:lower:]]/ p' \n"
},
{
"code": null,
"e": 9869,
"s": 9810,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 9875,
"s": 9869,
"text": "one \n"
},
{
"code": null,
"e": 9952,
"s": 9875,
"text": "It implies uppercase letters only. The following example matches only \"TWO\"."
},
{
"code": null,
"e": 10012,
"s": 9952,
"text": "[jerry]$ echo -e \"one\\nTWO\\n\\t\" | sed -n '/[[:upper:]]/ p'\n"
},
{
"code": null,
"e": 10071,
"s": 10012,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 10076,
"s": 10071,
"text": "TWO\n"
},
{
"code": null,
"e": 10156,
"s": 10076,
"text": "It implies punctuation marks which include non-space or alphanumeric characters"
},
{
"code": null,
"e": 10224,
"s": 10156,
"text": "[jerry]$ echo -e \"One,Two\\nThree\\nFour\" | sed -n '/[[:punct:]]/ p'\n"
},
{
"code": null,
"e": 10283,
"s": 10224,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 10292,
"s": 10283,
"text": "One,Two\n"
},
{
"code": null,
"e": 10366,
"s": 10292,
"text": "It implies whitespace characters. The following example illustrates this."
},
{
"code": null,
"e": 10438,
"s": 10366,
"text": "[jerry]$ echo -e \"One\\n123\\f\\t\" | sed -n '/[[:space:]]/ p' | cat -vte \n"
},
{
"code": null,
"e": 10497,
"s": 10438,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 10508,
"s": 10497,
"text": "123^L^I$ \n"
},
{
"code": null,
"e": 10760,
"s": 10508,
"text": "Like traditional regular expressions, SED also supports metacharacters. These are Perl style regular expressions. Note that metacharacter support is GNU SED specific and may not work with other variants of SED. Let us discuss metacharacters in detail."
},
{
"code": null,
"e": 10957,
"s": 10760,
"text": "In regular expression terminology, \"\\b\" matches the word boundary. For example, \"\\bthe\\b\" matches \"the\" but not \"these\", \"there\", \"they\", \"then\", and so on. The following example illustrates this."
},
{
"code": null,
"e": 11023,
"s": 10957,
"text": "[jerry]$ echo -e \"these\\nthe\\nthey\\nthen\" | sed -n '/\\bthe\\b/ p'\n"
},
{
"code": null,
"e": 11082,
"s": 11023,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 11087,
"s": 11082,
"text": "the\n"
},
{
"code": null,
"e": 11257,
"s": 11087,
"text": "In regular expression terminology, \"\\B\" matches non-word boundary. For example, \"the\\B\" matches \"these\" and \"they\" but not \"the\". The following example illustrates this."
},
{
"code": null,
"e": 11315,
"s": 11257,
"text": "[jerry]$ echo -e \"these\\nthe\\nthey\" | sed -n '/the\\B/ p'\n"
},
{
"code": null,
"e": 11374,
"s": 11315,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 11387,
"s": 11374,
"text": "these \nthey\n"
},
{
"code": null,
"e": 11505,
"s": 11387,
"text": "In SED, \"\\s\" implies single whitespace character. The following example matches \"Line\\t1\" but does not match \"Line1\"."
},
{
"code": null,
"e": 11562,
"s": 11505,
"text": "[jerry]$ echo -e \"Line\\t1\\nLine2\" | sed -n '/Line\\s/ p'\n"
},
{
"code": null,
"e": 11621,
"s": 11562,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 11630,
"s": 11621,
"text": "Line 1 \n"
},
{
"code": null,
"e": 11748,
"s": 11630,
"text": "In SED, \"\\S\" implies single whitespace character. The following example matches \"Line2\" but does not match \"Line\\t1\"."
},
{
"code": null,
"e": 11806,
"s": 11748,
"text": "[jerry]$ echo -e \"Line\\t1\\nLine2\" | sed -n '/Line\\S/ p' \n"
},
{
"code": null,
"e": 11865,
"s": 11806,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 11872,
"s": 11865,
"text": "Line2\n"
},
{
"code": null,
"e": 12015,
"s": 11872,
"text": "In SED, \"\\w\" implies single word character, i.e., alphabetical characters, digits, and underscore (_). The following example illustrates this."
},
{
"code": null,
"e": 12072,
"s": 12015,
"text": "[jerry]$ echo -e \"One\\n123\\n1_2\\n&;#\" | sed -n '/\\w/ p'\n"
},
{
"code": null,
"e": 12131,
"s": 12072,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 12146,
"s": 12131,
"text": "One \n123 \n1_2\n"
},
{
"code": null,
"e": 12268,
"s": 12146,
"text": "In SED, \"\\W\" implies single non-word character which is exactly opposite to \"\\w\". The following example illustrates this."
},
{
"code": null,
"e": 12325,
"s": 12268,
"text": "[jerry]$ echo -e \"One\\n123\\n1_2\\n&;#\" | sed -n '/\\W/ p'\n"
},
{
"code": null,
"e": 12384,
"s": 12325,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 12389,
"s": 12384,
"text": "&;#\n"
},
{
"code": null,
"e": 12497,
"s": 12389,
"text": "In SED, \"\\`\" implies the beginning of the pattern space. The following example matches only the word \"One\"."
},
{
"code": null,
"e": 12552,
"s": 12497,
"text": "[jerry]$ echo -e \"One\\nTwo One\" | sed -n '/\\`One/ p' \n"
},
{
"code": null,
"e": 12611,
"s": 12552,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 12616,
"s": 12611,
"text": "One\n"
},
{
"code": null,
"e": 12651,
"s": 12616,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12663,
"s": 12651,
"text": " Senol Atac"
},
{
"code": null,
"e": 12695,
"s": 12663,
"text": "\n 14 Lectures \n 44 mins\n"
},
{
"code": null,
"e": 12708,
"s": 12695,
"text": " Zach Miller"
},
{
"code": null,
"e": 12741,
"s": 12708,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12762,
"s": 12741,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 12795,
"s": 12762,
"text": "\n 28 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12812,
"s": 12795,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 12847,
"s": 12812,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12870,
"s": 12847,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 12903,
"s": 12870,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12919,
"s": 12903,
"text": " Davida Shensky"
},
{
"code": null,
"e": 12926,
"s": 12919,
"text": " Print"
},
{
"code": null,
"e": 12937,
"s": 12926,
"text": " Add Notes"
}
] |
Largest Independent Set Problem | The Independent Set is the subset of all binary tree nodes when there is no edge between any two nodes in that subset.
Now from a set of elements, we will find the longest independent set. i.e. If the elements are used to form a binary tree, then all largest subset, where no elements in that subset are connected to each other.
Input:
A binary tree.
Output:
Size of the Largest Independent Set is: 5
longSetSize(root)
In this algorithm Binary tree will be formed, each node of that tree will hold data and setSize.
Input − Root node of the binary tree.
Output − Size of the longest set.
Begin
if root = φ, then
return 0
if setSize(root) ≠ 0, then
setSize(root)
if root has no child, then
setSize(root) := 1
return setSize(root)
setSizeEx := longSetSize(left(root)) + longSetSize(right(root)) //excluding root
setSizeIn := 1
if left child exists, then
setSizeIn := setSizeIn + longSetSize(left(left(root))) + longSetSize(left(right(root)))
if right child exists, then
setSizeIn := setSizeIn + longSetSize(right(left(root))) + longSetSize(right(right(root)))
if setSizeIn > setSizeEx, then
setSize(root) := setSizeIn
else
setSize(root) := setSizeEx
return setSize(root)
End
#include <iostream>
using namespace std;
struct node {
int data;
int setSize;
node *left, *right;
};
int longSetSize(node *root) {
if (root == NULL)
return 0;
if (root->setSize != 0)
return root->setSize;
if (root->left == NULL && root->right == NULL) //when there is no child
return (root->setSize = 1);
// set size exclusive root is set size of left and set size of right
int setSizeEx = longSetSize(root->left) + longSetSize(root->right);
int setSizeIn = 1; //inclusive root node
if (root->left) //if left sub tree is present
setSizeIn += longSetSize(root->left->left) + longSetSize(root->left->right);
if (root->right) //if right sub tree is present
setSizeIn += longSetSize(root->right->left) +longSetSize(root->right->right);
root->setSize = (setSizeIn>setSizeEx)?setSizeIn:setSizeEx;
return root->setSize;
}
struct node* getNode(int data) { //create a new node with given data
node* newNode = new node;
newNode->data = data;
newNode->left = newNode->right = NULL;
newNode->setSize = 0;
return newNode;
}
int main() {
node *root = getNode(20);
root->left = getNode(8);
root->left->left = getNode(4);
root->left->right = getNode(12);
root->left->right->left = getNode(10);
root->left->right->right = getNode(14);
root->right = getNode(22);
root->right->right = getNode(25);
cout << "Size of the Largest Independent Set is: " << longSetSize(root);
}
Size of the Largest Independent Set is − 5 | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "The Independent Set is the subset of all binary tree nodes when there is no edge between any two nodes in that subset. "
},
{
"code": null,
"e": 1392,
"s": 1182,
"text": "Now from a set of elements, we will find the longest independent set. i.e. If the elements are used to form a binary tree, then all largest subset, where no elements in that subset are connected to each other."
},
{
"code": null,
"e": 1465,
"s": 1392,
"text": "Input:\nA binary tree.\n\nOutput:\nSize of the Largest Independent Set is: 5"
},
{
"code": null,
"e": 1483,
"s": 1465,
"text": "longSetSize(root)"
},
{
"code": null,
"e": 1580,
"s": 1483,
"text": "In this algorithm Binary tree will be formed, each node of that tree will hold data and setSize."
},
{
"code": null,
"e": 1618,
"s": 1580,
"text": "Input − Root node of the binary tree."
},
{
"code": null,
"e": 1652,
"s": 1618,
"text": "Output − Size of the longest set."
},
{
"code": null,
"e": 2320,
"s": 1652,
"text": "Begin\n if root = φ, then\n return 0\n if setSize(root) ≠ 0, then\n setSize(root)\n if root has no child, then\n setSize(root) := 1\n return setSize(root)\n setSizeEx := longSetSize(left(root)) + longSetSize(right(root)) //excluding root\n setSizeIn := 1\n\n if left child exists, then\n setSizeIn := setSizeIn + longSetSize(left(left(root))) + longSetSize(left(right(root)))\n\n if right child exists, then\n setSizeIn := setSizeIn + longSetSize(right(left(root))) + longSetSize(right(right(root)))\n\n if setSizeIn > setSizeEx, then\n setSize(root) := setSizeIn\n else\n setSize(root) := setSizeEx\n\n return setSize(root)\nEnd"
},
{
"code": null,
"e": 3851,
"s": 2320,
"text": "#include <iostream>\nusing namespace std;\n\nstruct node {\n int data;\n int setSize;\n node *left, *right;\n};\n\nint longSetSize(node *root) {\n if (root == NULL)\n return 0;\n\n if (root->setSize != 0)\n return root->setSize;\n\n if (root->left == NULL && root->right == NULL) //when there is no child\n return (root->setSize = 1);\n\n // set size exclusive root is set size of left and set size of right\n\n int setSizeEx = longSetSize(root->left) + longSetSize(root->right);\n int setSizeIn = 1; //inclusive root node\n\n if (root->left) //if left sub tree is present\n setSizeIn += longSetSize(root->left->left) + longSetSize(root->left->right);\n\n if (root->right) //if right sub tree is present\n setSizeIn += longSetSize(root->right->left) +longSetSize(root->right->right);\n root->setSize = (setSizeIn>setSizeEx)?setSizeIn:setSizeEx;\n\n return root->setSize;\n}\n\nstruct node* getNode(int data) { //create a new node with given data\n node* newNode = new node;\n newNode->data = data;\n newNode->left = newNode->right = NULL;\n newNode->setSize = 0;\n\n return newNode;\n}\n\nint main() {\n node *root = getNode(20);\n root->left = getNode(8);\n root->left->left = getNode(4);\n root->left->right = getNode(12);\n root->left->right->left = getNode(10);\n root->left->right->right = getNode(14);\n root->right = getNode(22);\n\n root->right->right = getNode(25);\n cout << \"Size of the Largest Independent Set is: \" << longSetSize(root);\n}"
},
{
"code": null,
"e": 3894,
"s": 3851,
"text": "Size of the Largest Independent Set is − 5"
}
] |
PHP date_interval_create_from_date_string() Function | The date_interval_create_from_date_string() function is an alias of DateInterval::createFromDateString. This accepts a string specifying an interval and returns a DateInterval object.
date_interval_create_from_date_string($time)
time (Mandatory)
This is a string value specifying the date/interval in relative formats format in which you want the output date string to be.
PHP date_interval_create_from_date_string() returns a DateInterval object representing the given interval value.
This function was first introduced in PHP Version 5.3 and, works with all the later versions.
Following example demonstrates the usage of the date_interval_create_from_date_string() function −
<?php
$time = "3year + 3months + 26 day + 12 hours+ 30 minutes +23 seconds";
$interval = date_interval_create_from_date_string($time);
print_r($interval);
?>
This will produce following result −
DateInterval Object
(
[y] => 3
[m] => 3
[d] => 26
[h] => 12
[i] => 30
[s] => 23
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] =>
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
In this function you cannot use ISO8601 strings like "P12M" to parse such intervals you need to use the DateInterval constructor.
In the following example we are using the ISO8601 strings notations to create an interval −
<?php
$time1 = new DateInterval('P25DP8MP9Y');
print_r($time1);
$time2 = new DateInterval('PT10H');
print_r($time2);
?>
This will produce following result −
DateInterval Object
(
[y] => 9
[m] => 8
[d] => 25
[h] => 0
[i] => 0
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] =>
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 10
[i] => 0
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] =>
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
Following example adds an interval to the current date and prints the results. Here we are using the date_interval_create_from_date_string function to calculate the interval. −
<?php
$date = date_create();
$str = "12year 3months 14days";
$interval = date_interval_create_from_date_string($str);
$res1 = date_add($date, $interval);
print("Date after ".$str);
print(": ".date_format($res1, 'Y-m-d'));
?>
This will produce following result −
Date after 12year 3months 14days: 2032-08-28
following example creates date intervals using various ISO8601 strings and their respective normal strings −
<?php
print(new DateInterval('P12D')."\n");
print(DateInterval::createFromDateString('12 day')."\n");
print(new DateInterval('P7')."\n");
print(DateInterval::createFromDateString('7 months')."\n");
print(new DateInterval('P12Y')."\n");
print(DateInterval::createFromDateString('12 years')."\n");
print(new DateInterval('PT9H')."\n");
print(DateInterval::createFromDateString('9 hours')."\n");
print(new DateInterval('PT19i')."\n");
print(DateInterval::createFromDateString('19 minutes')."\n");
print(new DateInterval('PT45S')."\n");
print(DateInterval::createFromDateString('45 seconds')."\n");
?>
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2941,
"s": 2757,
"text": "The date_interval_create_from_date_string() function is an alias of DateInterval::createFromDateString. This accepts a string specifying an interval and returns a DateInterval object."
},
{
"code": null,
"e": 2987,
"s": 2941,
"text": "date_interval_create_from_date_string($time)\n"
},
{
"code": null,
"e": 3004,
"s": 2987,
"text": "time (Mandatory)"
},
{
"code": null,
"e": 3131,
"s": 3004,
"text": "This is a string value specifying the date/interval in relative formats format in which you want the output date string to be."
},
{
"code": null,
"e": 3244,
"s": 3131,
"text": "PHP date_interval_create_from_date_string() returns a DateInterval object representing the given interval value."
},
{
"code": null,
"e": 3338,
"s": 3244,
"text": "This function was first introduced in PHP Version 5.3 and, works with all the later versions."
},
{
"code": null,
"e": 3437,
"s": 3338,
"text": "Following example demonstrates the usage of the date_interval_create_from_date_string() function −"
},
{
"code": null,
"e": 3604,
"s": 3437,
"text": "<?php\n $time = \"3year + 3months + 26 day + 12 hours+ 30 minutes +23 seconds\";\n $interval = date_interval_create_from_date_string($time);\n print_r($interval);\n?>"
},
{
"code": null,
"e": 3641,
"s": 3604,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3985,
"s": 3641,
"text": "DateInterval Object\n(\n [y] => 3\n [m] => 3\n [d] => 26\n [h] => 12\n [i] => 30\n [s] => 23\n [f] => 0\n [weekday] => 0\n [weekday_behavior] => 0\n [first_last_day_of] => 0\n [invert] => 0\n [days] =>\n [special_type] => 0\n [special_amount] => 0\n [have_weekday_relative] => 0\n [have_special_relative] => 0\n)\n"
},
{
"code": null,
"e": 4115,
"s": 3985,
"text": "In this function you cannot use ISO8601 strings like \"P12M\" to parse such intervals you need to use the DateInterval constructor."
},
{
"code": null,
"e": 4207,
"s": 4115,
"text": "In the following example we are using the ISO8601 strings notations to create an interval −"
},
{
"code": null,
"e": 4338,
"s": 4207,
"text": "<?php\n $time1 = new DateInterval('P25DP8MP9Y');\n print_r($time1);\n $time2 = new DateInterval('PT10H');\n print_r($time2);\n?>"
},
{
"code": null,
"e": 4375,
"s": 4338,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5056,
"s": 4375,
"text": "DateInterval Object\n(\n [y] => 9\n [m] => 8\n [d] => 25\n [h] => 0\n [i] => 0\n [s] => 0\n [f] => 0\n [weekday] => 0\n [weekday_behavior] => 0\n [first_last_day_of] => 0\n [invert] => 0\n [days] =>\n [special_type] => 0\n [special_amount] => 0\n [have_weekday_relative] => 0\n [have_special_relative] => 0\n)\nDateInterval Object\n(\n [y] => 0\n [m] => 0\n [d] => 0\n [h] => 10\n [i] => 0\n [s] => 0\n [f] => 0\n [weekday] => 0\n [weekday_behavior] => 0\n [first_last_day_of] => 0\n [invert] => 0\n [days] =>\n [special_type] => 0\n [special_amount] => 0\n [have_weekday_relative] => 0\n [have_special_relative] => 0\n)\n"
},
{
"code": null,
"e": 5233,
"s": 5056,
"text": "Following example adds an interval to the current date and prints the results. Here we are using the date_interval_create_from_date_string function to calculate the interval. −"
},
{
"code": null,
"e": 5479,
"s": 5233,
"text": "<?php\n $date = date_create(); \n $str = \"12year 3months 14days\";\n $interval = date_interval_create_from_date_string($str);\n\n $res1 = date_add($date, $interval); \n print(\"Date after \".$str);\n print(\": \".date_format($res1, 'Y-m-d'));\n?>"
},
{
"code": null,
"e": 5516,
"s": 5479,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5562,
"s": 5516,
"text": "Date after 12year 3months 14days: 2032-08-28\n"
},
{
"code": null,
"e": 5671,
"s": 5562,
"text": "following example creates date intervals using various ISO8601 strings and their respective normal strings −"
},
{
"code": null,
"e": 6310,
"s": 5671,
"text": "<?php\n print(new DateInterval('P12D').\"\\n\");\n print(DateInterval::createFromDateString('12 day').\"\\n\");\n\n print(new DateInterval('P7').\"\\n\");\n print(DateInterval::createFromDateString('7 months').\"\\n\");\n\n print(new DateInterval('P12Y').\"\\n\");\n print(DateInterval::createFromDateString('12 years').\"\\n\");\n\n print(new DateInterval('PT9H').\"\\n\");\n print(DateInterval::createFromDateString('9 hours').\"\\n\");\n\n print(new DateInterval('PT19i').\"\\n\");\n print(DateInterval::createFromDateString('19 minutes').\"\\n\");\n\n print(new DateInterval('PT45S').\"\\n\");\n print(DateInterval::createFromDateString('45 seconds').\"\\n\");\n?>"
},
{
"code": null,
"e": 6343,
"s": 6310,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6359,
"s": 6343,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6392,
"s": 6359,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6403,
"s": 6392,
"text": " Syed Raza"
},
{
"code": null,
"e": 6438,
"s": 6403,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6455,
"s": 6438,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6488,
"s": 6455,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6503,
"s": 6488,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 6538,
"s": 6503,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 6550,
"s": 6538,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6585,
"s": 6550,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6613,
"s": 6585,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 6620,
"s": 6613,
"text": " Print"
},
{
"code": null,
"e": 6631,
"s": 6620,
"text": " Add Notes"
}
] |
Print with your own font using Python? | In this, we are going to see how differently we can display our text in a very unique way using python.
So let suppose I want to display “Hello, Python” and out many ways I could display my text/string (“Hello, Python”) like:
“Hello, Python”
___ ___ .__ .__
/ | \ ____ | | | | ____
/ ~ \_/ __ \| | | | / _ \
\ Y /\ ___/| |_| |_( <_> )
\___|_ / \___ >____/____/\____/ /\
\/ \/ )/
__________ __ .__
\______ \___.__._/ |_| |__ ____ ____
| ___< | |\ __\ | \ / _ \ / \
| | \___ | | | | Y ( <_> ) | \
|____| / ____| |__| |___| /\____/|___| /
\/ \/ \/
_ _ _____ _ _ ___ ______ _______ _ _ ___ _ _
| | | | ____| | | | / _ \ | _ \ \ / /_ _| | | |/ _ \| \ | |
| |_| | _| | | | | | | | | | |_) \ V / | | | |_| | | | | \| |
| _ | |___| |___| |__| |_| | | __/ | | | | | _ | |_| | |\ |
|_| |_|_____|_____|_____\___( ) |_| |_| |_| |_| |_|\___/|_| \_|
## ## # # #
## ## # # # ##
## ### # # # # # ###
####### # # ##### # ####
### ### # # # ##### #####
## ## # # # # # ######
## ### ## # # # # #######
# ## ## # # # # ########
###### ######## ### # # # # ### # # ##### #
####### # # # ## # ## ## # ### # # # # #######
## ## # # # ## # ### # #### # # # # # #####
## ## ## # ## # ## #### ##### # # # # #
#### # ## ## # ### # ##### # # # #
## # ## ## ## #
## ### ###
# ## ###
Above is just the tip of the ice-pack, you can use many others font style to display your text.
I am going to use python pyfiglet module which will convert my regular strings in to ASCII art fonts. To install pyfiglet,simply run:
$pip install pyfiglet
In your terminal window, that it.
>>> import pyfiglet
>>> ascii_banner = pyfiglet.figlet_format("HELLO, PYTHON")
>>> print(ascii_banner)
_ _ _____ _ _ ___ ______ _______ _ _ ___ _ _
| | | | ____| | | | / _ \ | _ \ \ / /_ _| | | |/ _ \| \ | |
| |_| | _| | | | | | | | | | |_) \ V / | | | |_| | | | | \| |
| _ | |___| |___| |__| |_| | | __/ | | | | | _ | |_| | |\ |
|_| |_|_____|_____|_____\___( ) |_| |_| |_| |_| |_|\___/|_| \_|
|/
>>> from pyfiglet import Figlet
>>> custom_fig = Figlet(font='graffiti')
>>> print(custom_fig.renderText('HELLO, PYTHON'))
___ ______________.____ .____ ________
/ | \_ _____/| | | | \_____ \
/ ~ \ __)_ | | | | / | \
\ Y / \| |___| |___/ | \
\___|_ /_______ /|_______ \_______ \_______ / /\
\/ \/ \/ \/ \/ )/
_______________.___.______________ ___ ________ _______
\______ \__ | |\__ ___/ | \\_____ \ \ \
| ___// | | | | / ~ \/ | \ / | \
| | \____ | | | \ Y / | \/ | \
|____| / ______| |____| \___|_ /\_______ /\____|__ /
\/ \/ \/ \/
>>> from pyfiglet import Figlet
>>> custom_fig = Figlet(font='bubble')
>>> print(custom_fig.renderText('Hello, Python'))
_ _ _ _ _ _ _ _ _ _ _ _
/ \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \
( H | e | l | l | o | , ) ( P | y | t | h | o | n )
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
>>> custom_fig = Figlet(font='speed')
>>> print(custom_fig.renderText('Hello, Python'))
______ __ ___________
___ / / /_______ /__ /_____
__ /_/ /_ _ \_ /__ /_ __ \
_ __ / / __/ / _ / / /_/ /__
/_/ /_/ \___//_/ /_/ \____/_( )
_|/
________ ___________
___ __ \____ ___ /___ /______________
__ /_/ /_ / / / __/_ __ \ __ \_ __ \
_ ____/_ /_/ // /_ _ / / / /_/ / / / /
/_/ _\__, / \__/ /_/ /_/\____//_/ /_/
/____/
So my guess is you’re quite comfortable in finding a font you like and generate an ASCII art banner using pyfiglet to enhance your application. | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "In this, we are going to see how differently we can display our text in a very unique way using python."
},
{
"code": null,
"e": 1288,
"s": 1166,
"text": "So let suppose I want to display “Hello, Python” and out many ways I could display my text/string (“Hello, Python”) like:"
},
{
"code": null,
"e": 1304,
"s": 1288,
"text": "“Hello, Python”"
},
{
"code": null,
"e": 1607,
"s": 1304,
"text": "___ ___ .__ .__\n/ | \\ ____ | | | | ____\n/ ~ \\_/ __ \\| | | | / _ \\\n\\ Y /\\ ___/| |_| |_( <_> )\n\\___|_ / \\___ >____/____/\\____/ /\\\n\\/ \\/ )/\n__________ __ .__\n\\______ \\___.__._/ |_| |__ ____ ____\n| ___< | |\\ __\\ | \\ / _ \\ / \\\n| | \\___ | | | | Y ( <_> ) | \\\n|____| / ____| |__| |___| /\\____/|___| /\n\\/ \\/ \\/"
},
{
"code": null,
"e": 1898,
"s": 1607,
"text": "_ _ _____ _ _ ___ ______ _______ _ _ ___ _ _\n| | | | ____| | | | / _ \\ | _ \\ \\ / /_ _| | | |/ _ \\| \\ | |\n| |_| | _| | | | | | | | | | |_) \\ V / | | | |_| | | | | \\| |\n| _ | |___| |___| |__| |_| | | __/ | | | | | _ | |_| | |\\ |\n|_| |_|_____|_____|_____\\___( ) |_| |_| |_| |_| |_|\\___/|_| \\_|"
},
{
"code": null,
"e": 2449,
"s": 1898,
"text": "## ## # # #\n## ## # # # ##\n## ### # # # # # ###\n####### # # ##### # ####\n### ### # # # ##### #####\n## ## # # # # # ######\n## ### ## # # # # #######\n # ## ## # # # # ########\n###### ######## ### # # # # ### # # ##### #\n####### # # # ## # ## ## # ### # # # # #######\n## ## # # # ## # ### # #### # # # # # #####\n## ## ## # ## # ## #### ##### # # # # #\n#### # ## ## # ### # ##### # # # #\n## # ## ## ## #\n## ### ###\n # ## ###"
},
{
"code": null,
"e": 2545,
"s": 2449,
"text": "Above is just the tip of the ice-pack, you can use many others font style to display your text."
},
{
"code": null,
"e": 2679,
"s": 2545,
"text": "I am going to use python pyfiglet module which will convert my regular strings in to ASCII art fonts. To install pyfiglet,simply run:"
},
{
"code": null,
"e": 2701,
"s": 2679,
"text": "$pip install pyfiglet"
},
{
"code": null,
"e": 2735,
"s": 2701,
"text": "In your terminal window, that it."
},
{
"code": null,
"e": 3132,
"s": 2735,
"text": ">>> import pyfiglet\n>>> ascii_banner = pyfiglet.figlet_format(\"HELLO, PYTHON\")\n>>> print(ascii_banner)\n_ _ _____ _ _ ___ ______ _______ _ _ ___ _ _\n| | | | ____| | | | / _ \\ | _ \\ \\ / /_ _| | | |/ _ \\| \\ | |\n| |_| | _| | | | | | | | | | |_) \\ V / | | | |_| | | | | \\| |\n| _ | |___| |___| |__| |_| | | __/ | | | | | _ | |_| | |\\ |\n|_| |_|_____|_____|_____\\___( ) |_| |_| |_| |_| |_|\\___/|_| \\_|\n|/"
},
{
"code": null,
"e": 3666,
"s": 3132,
"text": ">>> from pyfiglet import Figlet\n>>> custom_fig = Figlet(font='graffiti')\n>>> print(custom_fig.renderText('HELLO, PYTHON'))\n___ ______________.____ .____ ________\n/ | \\_ _____/| | | | \\_____ \\\n/ ~ \\ __)_ | | | | / | \\\n\\ Y / \\| |___| |___/ | \\\n\\___|_ /_______ /|_______ \\_______ \\_______ / /\\\n\\/ \\/ \\/ \\/ \\/ )/\n_______________.___.______________ ___ ________ _______\n\\______ \\__ | |\\__ ___/ | \\\\_____ \\ \\ \\\n| ___// | | | | / ~ \\/ | \\ / | \\\n| | \\____ | | | \\ Y / | \\/ | \\\n|____| / ______| |____| \\___|_ /\\_______ /\\____|__ /\n\\/ \\/ \\/ \\/"
},
{
"code": null,
"e": 3959,
"s": 3666,
"text": ">>> from pyfiglet import Figlet\n>>> custom_fig = Figlet(font='bubble')\n>>> print(custom_fig.renderText('Hello, Python'))\n_ _ _ _ _ _ _ _ _ _ _ _\n/ \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\\n( H | e | l | l | o | , ) ( P | y | t | h | o | n )\n\\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/"
},
{
"code": null,
"e": 4370,
"s": 3959,
"text": ">>> custom_fig = Figlet(font='speed')\n>>> print(custom_fig.renderText('Hello, Python'))\n\n______ __ ___________\n___ / / /_______ /__ /_____\n__ /_/ /_ _ \\_ /__ /_ __ \\\n_ __ / / __/ / _ / / /_/ /__\n/_/ /_/ \\___//_/ /_/ \\____/_( )\n_|/\n________ ___________\n___ __ \\____ ___ /___ /______________\n__ /_/ /_ / / / __/_ __ \\ __ \\_ __ \\\n_ ____/_ /_/ // /_ _ / / / /_/ / / / /\n/_/ _\\__, / \\__/ /_/ /_/\\____//_/ /_/\n/____/"
},
{
"code": null,
"e": 4514,
"s": 4370,
"text": "So my guess is you’re quite comfortable in finding a font you like and generate an ASCII art banner using pyfiglet to enhance your application."
}
] |
What are the differences between recursion and iteration in Java? | The Recursion and Iteration both repeatedly execute the set of instructions. Recursion is when a statement in a function calls itself repeatedly. The iteration is when a loop repeatedly executes until the controlling condition becomes false. The primary difference between recursion and iteration is that recursion is a process, always applied to a function and iteration is applied to the set of instructions which we want to get repeatedly executed.
Recursion uses selection structure.
Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on some condition (base case) and Infinite recursion can crash the system.
Recursion terminates when a base case is recognized.
Recursion is usually slower than iteration due to the overhead of maintaining the stack.
Recursion uses more memory than iteration.
Recursion makes the code smaller.
Live Demo
public class RecursionExample {
public static void main(String args[]) {
RecursionExample re = new RecursionExample();
int result = re.factorial(4);
System.out.println("Result:" + result);
}
public int factorial(int n) {
if (n==0) {
return 1;
}
else {
return n*factorial(n-1);
}
}
}
Result:24
Iteration uses repetition structure.
An infinite loop occurs with iteration if the loop condition test never becomes false and Infinite looping uses CPU cycles repeatedly.
An iteration terminates when the loop condition fails.
An iteration does not use the stack so it's faster than recursion.
Iteration consumes less memory.
Iteration makes the code longer.
Live Demo
public class IterationExample {
public static void main(String args[]) {
for(int i = 1; i <= 5; i++) {
System.out.println(i + " ");
}
}
}
1
2
3
4
5 | [
{
"code": null,
"e": 1514,
"s": 1062,
"text": "The Recursion and Iteration both repeatedly execute the set of instructions. Recursion is when a statement in a function calls itself repeatedly. The iteration is when a loop repeatedly executes until the controlling condition becomes false. The primary difference between recursion and iteration is that recursion is a process, always applied to a function and iteration is applied to the set of instructions which we want to get repeatedly executed."
},
{
"code": null,
"e": 1550,
"s": 1514,
"text": "Recursion uses selection structure."
},
{
"code": null,
"e": 1728,
"s": 1550,
"text": "Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on some condition (base case) and Infinite recursion can crash the system."
},
{
"code": null,
"e": 1781,
"s": 1728,
"text": "Recursion terminates when a base case is recognized."
},
{
"code": null,
"e": 1870,
"s": 1781,
"text": "Recursion is usually slower than iteration due to the overhead of maintaining the stack."
},
{
"code": null,
"e": 1913,
"s": 1870,
"text": "Recursion uses more memory than iteration."
},
{
"code": null,
"e": 1947,
"s": 1913,
"text": "Recursion makes the code smaller."
},
{
"code": null,
"e": 1957,
"s": 1947,
"text": "Live Demo"
},
{
"code": null,
"e": 2312,
"s": 1957,
"text": "public class RecursionExample {\n public static void main(String args[]) {\n RecursionExample re = new RecursionExample();\n int result = re.factorial(4);\n System.out.println(\"Result:\" + result);\n }\n public int factorial(int n) {\n if (n==0) {\n return 1;\n }\n else {\n return n*factorial(n-1);\n }\n }\n}"
},
{
"code": null,
"e": 2322,
"s": 2312,
"text": "Result:24"
},
{
"code": null,
"e": 2359,
"s": 2322,
"text": "Iteration uses repetition structure."
},
{
"code": null,
"e": 2494,
"s": 2359,
"text": "An infinite loop occurs with iteration if the loop condition test never becomes false and Infinite looping uses CPU cycles repeatedly."
},
{
"code": null,
"e": 2549,
"s": 2494,
"text": "An iteration terminates when the loop condition fails."
},
{
"code": null,
"e": 2616,
"s": 2549,
"text": "An iteration does not use the stack so it's faster than recursion."
},
{
"code": null,
"e": 2648,
"s": 2616,
"text": "Iteration consumes less memory."
},
{
"code": null,
"e": 2681,
"s": 2648,
"text": "Iteration makes the code longer."
},
{
"code": null,
"e": 2691,
"s": 2681,
"text": "Live Demo"
},
{
"code": null,
"e": 2856,
"s": 2691,
"text": "public class IterationExample {\n public static void main(String args[]) {\n for(int i = 1; i <= 5; i++) {\n System.out.println(i + \" \");\n }\n }\n}"
},
{
"code": null,
"e": 2866,
"s": 2856,
"text": "1\n2\n3\n4\n5"
}
] |
Go beyond the basics of the request package in python | by Aaron S | Towards Data Science | When you get used to the requests python package, it can be useful in command line applications to consider ways of validating files, resuming incomplete get requests and using progress bars. These go beyond the basic use of the request package. We will go through simple ways to do just that using the request package.
How to approach resuming downloads of incomplete binary filesHow to create a simple download validator for transferring files/backing up data.How to display a simple command-line progress bar.
How to approach resuming downloads of incomplete binary files
How to create a simple download validator for transferring files/backing up data.
How to display a simple command-line progress bar.
When you download large files, they can be interrupted for various reasons. We sometimes need a way to be able to resume at the last byte to re-establish a connection.
As part of an HTTP get request from a server, we will obtain a header and body of data. The HTTP headers for binary files gives a lot of information back about the file we request! One of the parts we will sometimes get depending on the server the request is made to is the accept-ranges header. This allows the client to download partially downloaded data.
See below for an example of the headers of a binary file that accepts downloading partial files.
{'Server': 'VK', 'Date': 'Wed, 29 Jan 2020 11:47:20 GMT', 'Content-Type': 'application/pdf', 'Content-Length': '9713036', 'Connection': 'keep-alive', 'Last-Modified': 'Mon, 20 Jan 2020 13:01:17 GMT', 'ETag': '"5e25a49d-94358c"', 'Accept-Ranges': 'bytes', 'Expires': 'Wed, 05 Feb 2020 11:47:20 GMT', 'Cache-Control': 'max-age=604800', 'X-Frontend': 'front632904', 'Access-Control-Expose-Headers': 'X-Frontend', 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=15768000'}
With this ability, we can also specify to the server the location in the file we request to download from. We can then start the requests of the binary data at that specific position and download from there going forward.
Now to download a small part of a binary file we have to be able to send headers with the request get HTTP method. The requests package enables us to do this with ease. We only want to get a certain amount of bytes, we do this by sending a range header to specify how many bytes to receive. We can then put this into a variable and pass this through the get request.
resume_headers = {'Range':'bytes=0-2000000'}r = request.get(url, stream=True, headers=resume_header)with open('filename.zip','wb') as f: for chunk in r.iter_content(chunk-size=1024) f.write(chunk)
Notes
1. We specify the stream = True in the request get method. This allows us to control when the body of the binary response is downloaded.
2. We use the headers argument in the requests.get() method to define the byte position from 0–2000000. The boundaries of the range header are inclusive. This means byte position 0 to 2000000 will be downloaded.
4. We use a with statement to write the file filename.zip. The r.iter_content method allows us to specify the size of data to download by defining the chunk-size in bytes. In this case, it’s set at 1024 bytes.
We’ve downloaded a partial file. How does this help our actual aim of resuming a partially downloaded file?
When we want to resume a partially downloaded file we specify the filesize in the headers. This is the next byte onwards that needs to be downloaded. This is the crux of being able to resume downloads in python.
We need to know the filesize of the partially downloaded size. There are a range of packages to do this in python and pathlib is a great package for this use case. Please see here for guidance on using pathlib.
We first import have to import the pathlib package
import pathlib
The method path.stat() returns information about the path (Similar to os.stat, if you’re familiar with os package). Now we call the st_size attribute of the path.stat() method to get the size of a file (also similar to the OS package).
Now we are ready to put this into use
resume_header = {'Range':f'bytes= {path('filename.zip').stat().st_size}-'}
Now, this needs to be unpacked. The f before the string is an f-string, this is a great way to format strings. As a use case the {path.stat().st_size} seen here in curly brackets is an expression. The string we are creating is modified by the meaning of that expression in the curly brackets. This could be a variable but in this case, we get the file size of the partial file we downloaded. The f-string interprets whatever is inside the {} and then displays the result as the string. In this case, it prints the filesize for us.
The hyphen in bold after {path.stat().st_size} in the string means we grab data from the partial filesize byte onwards till the end of the file.
So now that we understand this, we can put this all together in the code below
resume_header = {'Range':f'bytes={path('filename.zip').stat().st_size}-'}r = requests.get(url,stream=True, headers=resume_header)with open ('filename.zip','ab') as f: for chunk in r.iter_content(chunk-size=1024): f.write(chunk)
Notes
The ‘ab’ mode in the open function appends new content to the file. We don’t want to overwrite existing content this is instead of ‘wb’
The ‘ab’ mode in the open function appends new content to the file. We don’t want to overwrite existing content this is instead of ‘wb’
We need to be able to validate downloaded file sometimes. If you have resumed a file download or if this is important research data that you want to share with others. There is a python module called the hashlib module which creates a hash function. A hash function takes data and converts this into a unique string of numbers and letters. We call this the hash object. The computation of this string is by algorithms that we can specify as part of the module.
Let’s get down to how we would go about validating a downloaded file. We need to know what the hash value should be to be able to validate it. We will read the binary file and generate the hash, this then can be compared with the known hash value of the file. As hash files are unique we will be able to confirm that they are the same file.
To create a hash value we need to specify the algorithm that creates it. There are many to choose but in this example we use sha256(). Now to create a hash value we use the hashlib update()method which will only take ‘byte like’ data, such as bytes. To gain access to the hash value, we call upon the hexdigest() method. The hexdigest() takes the hash object and provides us with a string of hexadecimal only digits. This string defined by the algorithm we specified earlier.
Once you create the hash value, you can’t work backwards to get the original binary data. It only works one way. We can compare two files only by its unique hash value and makes it more secure in transferring to other people.
import hashlibwith open('research.zip', 'rb') as f: content = f.read()sha = hashlib.sha256()sha.update(content)print(sha.hexdigest())
Output:
42e53ea0f2fdc03e035eb2e967998da5cb8e2b1235dd2630ffc59e31af866372
Notes
The hashlib module is importedWe read the file using the with statement: this ensures we don’t have to use a close statement.We invoke the read()method to read all the content of the binary dataThe variable sha is created and creates a hash object using the SHA 256 algorithm to create the hash value.Using the update() method we pass the binary data into the hash object. By doing this we get a hash value.Using the hexdigest() method we can print out the hash value, the fixed string unique to that binary file.
The hashlib module is imported
We read the file using the with statement: this ensures we don’t have to use a close statement.
We invoke the read()method to read all the content of the binary data
The variable sha is created and creates a hash object using the SHA 256 algorithm to create the hash value.
Using the update() method we pass the binary data into the hash object. By doing this we get a hash value.
Using the hexdigest() method we can print out the hash value, the fixed string unique to that binary file.
So now we have a hash value whenever you want to validate a file. If you had to download it again or transfer the data to a colleague. You only need to compare the hash value you created. If a resumed download is complete and has the correct hash value, then we know it is the same data.
Let’s create a little script to confirm a file that your friend has transferred to you. You have the hash value to input for example.
user_hash = input('Please input hash please: ')sha = hashlib.sha256()with open('file.zip' as 'rb') as f: chunk = f.read() if not chunk: break sha.update(chunk)try: assert sha.hexdigest() == user_hashexcept AssertionError: print('File is corrupt, delete it and restart program'else: print('File is validated')
Notes
We ask the user to input a hash value and the value is assigned the variable user-hash.The variable sha is created and the hash object is created when we specify the algorithmWe open up the file we want to validate, using a with statement. We define the variable chunk and assign it the binary data using the read method.
We ask the user to input a hash value and the value is assigned the variable user-hash.
The variable sha is created and the hash object is created when we specify the algorithm
We open up the file we want to validate, using a with statement. We define the variable chunk and assign it the binary data using the read method.
4. We use hashlib update() method to create a hash object for that chunk.
5. We create a hash value for this chunk using sha.hexdigest().
6. We use the assert keyword, which evaluates an expression for truth. In this case, assess the data downloaded’s hash value against the hash value inputted.
7. We specify an exception AssertionError. This is called when an assert statement is false and specify an error message.
8. In an else statement, if the user_hash variable is the same as the file’s hash value, we print that the file is validated.
So here we have created a very simple validating tool for downloaded files.
There are many packages to display progress in your programming code. Here we will talk about a simple way to add a progress bar when downloading files! This may be useful if you are downloading in bulk and want to see the progress as you go. Progress bars can be useful in all sorts of ways not only for downloading files.
Tqdm is a third party python package that can deal with progress bars. To me, this is the best way to think about python, start with as little code as possible to get what you want.
First off you will want to install tqdm using pip.
pip install tqdm
Then we will want to import tqdm. Now it’s the tqdm method we want to use to display the progress of data. The tqdm module can interpret each chunk and display the progress of the file.
To incorporate the progress bar into downloading files. First, we have to create a few variables, the most important being the size of a file. We can use the request package to do this. We grab the binary headers and inside ‘content-length’. Scroll up at the binary headers in another section to see. Its associated value is how many bytes of data we have requested from the server. The response is a string and we have to convert this to number format when using it for the progress bar
The other important part is the filename. We can split the URL up into a list and choose the last item quite simply.
We then specify the tqdm module once we have all the variables set up.
A with statement means it closes once the operation is complete and the open function writes data. We then use the tqdm method and specify the arguments to display the data being downloaded. Be aware the arguments are are quite detailed! Let’s go through them one by one.
The total argument is the size of file, which we defined.The unit argument is the string we specify to define the unit of each iteration of the chunk of data. We specify B in this case for bytes.The desc argument displays the filenameThe initial argument specifies where to start the progress bar from in this case 0.The ascii argument is to specify what we use to fill the progress bar with. If set to false it assumes unicode to fill the progress bar instead.
The total argument is the size of file, which we defined.
The unit argument is the string we specify to define the unit of each iteration of the chunk of data. We specify B in this case for bytes.
The desc argument displays the filename
The initial argument specifies where to start the progress bar from in this case 0.
The ascii argument is to specify what we use to fill the progress bar with. If set to false it assumes unicode to fill the progress bar instead.
Let's look at the code now that we’ve explained what we’re doing:
from tqdm import tqdmurl = "insert here"file = url.split('/')[-1]r = requests.get(url, stream=True, allow_redirects=True)total_size = int(r.headers.get('content-length'))initial_pos = 0with open(file,'wb') as f: with tqdm(total=total_size, unit=B, unit_scale=True, desc=file,initial=initial_pos, ascii=True) as pbar: for ch in r.iter_content(chunk_size=1024), if ch: f.write(ch) pbar.update(len(ch))
Output:
filename.zip 100%|#################################################| 3.71M/3.71M [00:26<00:00, 254kB/s]
Notes
We import the tqdm method from the tqdm module.The variable url is defined.The file variable is defined, we use the split string method to split up url into a list. The (‘/’) argument is what tells the split method to split the string up between the /’s of the url. Here, we want to get the last index of the list as this will be the file name we desire.The variable r is used to specify an HTTP get request which we allow to have an open stream of data and allow redirects.The total_size variable is defined and use the request packge to get the binary headers. Using the get method we get the ‘content-length’ value which is the size of the binary files. Now, this returns a string and we make this into a number using int().The variable initial_pos is assigned as 0, which is important to specify for the tqdm method.We access the tqdm method using a with statement. We specify a few items within the arguments.The r.iter_content splits the data into chunks. We define ch as a chunk of 1024 bytes and if the chunk is available we write that chunk to the file.We call upon the update attribute of the tqdm method to update that chunk to the progress bar and display it for us.
We import the tqdm method from the tqdm module.
The variable url is defined.
The file variable is defined, we use the split string method to split up url into a list. The (‘/’) argument is what tells the split method to split the string up between the /’s of the url. Here, we want to get the last index of the list as this will be the file name we desire.
The variable r is used to specify an HTTP get request which we allow to have an open stream of data and allow redirects.
The total_size variable is defined and use the request packge to get the binary headers. Using the get method we get the ‘content-length’ value which is the size of the binary files. Now, this returns a string and we make this into a number using int().
The variable initial_pos is assigned as 0, which is important to specify for the tqdm method.
We access the tqdm method using a with statement. We specify a few items within the arguments.
The r.iter_content splits the data into chunks. We define ch as a chunk of 1024 bytes and if the chunk is available we write that chunk to the file.
We call upon the update attribute of the tqdm method to update that chunk to the progress bar and display it for us.
So after that, you should have a better idea of how to deal with progress bars, validating files and going beyond the basics of the request package.
Thanks for reading!
About the author
I am a medical doctor who has a keen interest in teaching, python, technology, and healthcare. I am based in the UK, I teach online clinical education as well as running the websites www.coding-medics.com.
You can contact me on [email protected] or on twitter here, all comments and recommendations welcome! If you want to chat about any projects or to collaborate that would be great.
For more tech/coding related content please sign up to my newsletter here. | [
{
"code": null,
"e": 492,
"s": 172,
"text": "When you get used to the requests python package, it can be useful in command line applications to consider ways of validating files, resuming incomplete get requests and using progress bars. These go beyond the basic use of the request package. We will go through simple ways to do just that using the request package."
},
{
"code": null,
"e": 685,
"s": 492,
"text": "How to approach resuming downloads of incomplete binary filesHow to create a simple download validator for transferring files/backing up data.How to display a simple command-line progress bar."
},
{
"code": null,
"e": 747,
"s": 685,
"text": "How to approach resuming downloads of incomplete binary files"
},
{
"code": null,
"e": 829,
"s": 747,
"text": "How to create a simple download validator for transferring files/backing up data."
},
{
"code": null,
"e": 880,
"s": 829,
"text": "How to display a simple command-line progress bar."
},
{
"code": null,
"e": 1048,
"s": 880,
"text": "When you download large files, they can be interrupted for various reasons. We sometimes need a way to be able to resume at the last byte to re-establish a connection."
},
{
"code": null,
"e": 1406,
"s": 1048,
"text": "As part of an HTTP get request from a server, we will obtain a header and body of data. The HTTP headers for binary files gives a lot of information back about the file we request! One of the parts we will sometimes get depending on the server the request is made to is the accept-ranges header. This allows the client to download partially downloaded data."
},
{
"code": null,
"e": 1503,
"s": 1406,
"text": "See below for an example of the headers of a binary file that accepts downloading partial files."
},
{
"code": null,
"e": 2052,
"s": 1503,
"text": "{'Server': 'VK', 'Date': 'Wed, 29 Jan 2020 11:47:20 GMT', 'Content-Type': 'application/pdf', 'Content-Length': '9713036', 'Connection': 'keep-alive', 'Last-Modified': 'Mon, 20 Jan 2020 13:01:17 GMT', 'ETag': '\"5e25a49d-94358c\"', 'Accept-Ranges': 'bytes', 'Expires': 'Wed, 05 Feb 2020 11:47:20 GMT', 'Cache-Control': 'max-age=604800', 'X-Frontend': 'front632904', 'Access-Control-Expose-Headers': 'X-Frontend', 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=15768000'}"
},
{
"code": null,
"e": 2274,
"s": 2052,
"text": "With this ability, we can also specify to the server the location in the file we request to download from. We can then start the requests of the binary data at that specific position and download from there going forward."
},
{
"code": null,
"e": 2641,
"s": 2274,
"text": "Now to download a small part of a binary file we have to be able to send headers with the request get HTTP method. The requests package enables us to do this with ease. We only want to get a certain amount of bytes, we do this by sending a range header to specify how many bytes to receive. We can then put this into a variable and pass this through the get request."
},
{
"code": null,
"e": 2844,
"s": 2641,
"text": "resume_headers = {'Range':'bytes=0-2000000'}r = request.get(url, stream=True, headers=resume_header)with open('filename.zip','wb') as f: for chunk in r.iter_content(chunk-size=1024) f.write(chunk)"
},
{
"code": null,
"e": 2850,
"s": 2844,
"text": "Notes"
},
{
"code": null,
"e": 2987,
"s": 2850,
"text": "1. We specify the stream = True in the request get method. This allows us to control when the body of the binary response is downloaded."
},
{
"code": null,
"e": 3199,
"s": 2987,
"text": "2. We use the headers argument in the requests.get() method to define the byte position from 0–2000000. The boundaries of the range header are inclusive. This means byte position 0 to 2000000 will be downloaded."
},
{
"code": null,
"e": 3409,
"s": 3199,
"text": "4. We use a with statement to write the file filename.zip. The r.iter_content method allows us to specify the size of data to download by defining the chunk-size in bytes. In this case, it’s set at 1024 bytes."
},
{
"code": null,
"e": 3517,
"s": 3409,
"text": "We’ve downloaded a partial file. How does this help our actual aim of resuming a partially downloaded file?"
},
{
"code": null,
"e": 3729,
"s": 3517,
"text": "When we want to resume a partially downloaded file we specify the filesize in the headers. This is the next byte onwards that needs to be downloaded. This is the crux of being able to resume downloads in python."
},
{
"code": null,
"e": 3940,
"s": 3729,
"text": "We need to know the filesize of the partially downloaded size. There are a range of packages to do this in python and pathlib is a great package for this use case. Please see here for guidance on using pathlib."
},
{
"code": null,
"e": 3991,
"s": 3940,
"text": "We first import have to import the pathlib package"
},
{
"code": null,
"e": 4006,
"s": 3991,
"text": "import pathlib"
},
{
"code": null,
"e": 4242,
"s": 4006,
"text": "The method path.stat() returns information about the path (Similar to os.stat, if you’re familiar with os package). Now we call the st_size attribute of the path.stat() method to get the size of a file (also similar to the OS package)."
},
{
"code": null,
"e": 4280,
"s": 4242,
"text": "Now we are ready to put this into use"
},
{
"code": null,
"e": 4355,
"s": 4280,
"text": "resume_header = {'Range':f'bytes= {path('filename.zip').stat().st_size}-'}"
},
{
"code": null,
"e": 4886,
"s": 4355,
"text": "Now, this needs to be unpacked. The f before the string is an f-string, this is a great way to format strings. As a use case the {path.stat().st_size} seen here in curly brackets is an expression. The string we are creating is modified by the meaning of that expression in the curly brackets. This could be a variable but in this case, we get the file size of the partial file we downloaded. The f-string interprets whatever is inside the {} and then displays the result as the string. In this case, it prints the filesize for us."
},
{
"code": null,
"e": 5031,
"s": 4886,
"text": "The hyphen in bold after {path.stat().st_size} in the string means we grab data from the partial filesize byte onwards till the end of the file."
},
{
"code": null,
"e": 5110,
"s": 5031,
"text": "So now that we understand this, we can put this all together in the code below"
},
{
"code": null,
"e": 5344,
"s": 5110,
"text": "resume_header = {'Range':f'bytes={path('filename.zip').stat().st_size}-'}r = requests.get(url,stream=True, headers=resume_header)with open ('filename.zip','ab') as f: for chunk in r.iter_content(chunk-size=1024): f.write(chunk)"
},
{
"code": null,
"e": 5350,
"s": 5344,
"text": "Notes"
},
{
"code": null,
"e": 5486,
"s": 5350,
"text": "The ‘ab’ mode in the open function appends new content to the file. We don’t want to overwrite existing content this is instead of ‘wb’"
},
{
"code": null,
"e": 5622,
"s": 5486,
"text": "The ‘ab’ mode in the open function appends new content to the file. We don’t want to overwrite existing content this is instead of ‘wb’"
},
{
"code": null,
"e": 6083,
"s": 5622,
"text": "We need to be able to validate downloaded file sometimes. If you have resumed a file download or if this is important research data that you want to share with others. There is a python module called the hashlib module which creates a hash function. A hash function takes data and converts this into a unique string of numbers and letters. We call this the hash object. The computation of this string is by algorithms that we can specify as part of the module."
},
{
"code": null,
"e": 6424,
"s": 6083,
"text": "Let’s get down to how we would go about validating a downloaded file. We need to know what the hash value should be to be able to validate it. We will read the binary file and generate the hash, this then can be compared with the known hash value of the file. As hash files are unique we will be able to confirm that they are the same file."
},
{
"code": null,
"e": 6900,
"s": 6424,
"text": "To create a hash value we need to specify the algorithm that creates it. There are many to choose but in this example we use sha256(). Now to create a hash value we use the hashlib update()method which will only take ‘byte like’ data, such as bytes. To gain access to the hash value, we call upon the hexdigest() method. The hexdigest() takes the hash object and provides us with a string of hexadecimal only digits. This string defined by the algorithm we specified earlier."
},
{
"code": null,
"e": 7126,
"s": 6900,
"text": "Once you create the hash value, you can’t work backwards to get the original binary data. It only works one way. We can compare two files only by its unique hash value and makes it more secure in transferring to other people."
},
{
"code": null,
"e": 7263,
"s": 7126,
"text": "import hashlibwith open('research.zip', 'rb') as f: content = f.read()sha = hashlib.sha256()sha.update(content)print(sha.hexdigest())"
},
{
"code": null,
"e": 7271,
"s": 7263,
"text": "Output:"
},
{
"code": null,
"e": 7336,
"s": 7271,
"text": "42e53ea0f2fdc03e035eb2e967998da5cb8e2b1235dd2630ffc59e31af866372"
},
{
"code": null,
"e": 7342,
"s": 7336,
"text": "Notes"
},
{
"code": null,
"e": 7856,
"s": 7342,
"text": "The hashlib module is importedWe read the file using the with statement: this ensures we don’t have to use a close statement.We invoke the read()method to read all the content of the binary dataThe variable sha is created and creates a hash object using the SHA 256 algorithm to create the hash value.Using the update() method we pass the binary data into the hash object. By doing this we get a hash value.Using the hexdigest() method we can print out the hash value, the fixed string unique to that binary file."
},
{
"code": null,
"e": 7887,
"s": 7856,
"text": "The hashlib module is imported"
},
{
"code": null,
"e": 7983,
"s": 7887,
"text": "We read the file using the with statement: this ensures we don’t have to use a close statement."
},
{
"code": null,
"e": 8053,
"s": 7983,
"text": "We invoke the read()method to read all the content of the binary data"
},
{
"code": null,
"e": 8161,
"s": 8053,
"text": "The variable sha is created and creates a hash object using the SHA 256 algorithm to create the hash value."
},
{
"code": null,
"e": 8268,
"s": 8161,
"text": "Using the update() method we pass the binary data into the hash object. By doing this we get a hash value."
},
{
"code": null,
"e": 8375,
"s": 8268,
"text": "Using the hexdigest() method we can print out the hash value, the fixed string unique to that binary file."
},
{
"code": null,
"e": 8663,
"s": 8375,
"text": "So now we have a hash value whenever you want to validate a file. If you had to download it again or transfer the data to a colleague. You only need to compare the hash value you created. If a resumed download is complete and has the correct hash value, then we know it is the same data."
},
{
"code": null,
"e": 8797,
"s": 8663,
"text": "Let’s create a little script to confirm a file that your friend has transferred to you. You have the hash value to input for example."
},
{
"code": null,
"e": 9127,
"s": 8797,
"text": "user_hash = input('Please input hash please: ')sha = hashlib.sha256()with open('file.zip' as 'rb') as f: chunk = f.read() if not chunk: break sha.update(chunk)try: assert sha.hexdigest() == user_hashexcept AssertionError: print('File is corrupt, delete it and restart program'else: print('File is validated')"
},
{
"code": null,
"e": 9133,
"s": 9127,
"text": "Notes"
},
{
"code": null,
"e": 9455,
"s": 9133,
"text": "We ask the user to input a hash value and the value is assigned the variable user-hash.The variable sha is created and the hash object is created when we specify the algorithmWe open up the file we want to validate, using a with statement. We define the variable chunk and assign it the binary data using the read method."
},
{
"code": null,
"e": 9543,
"s": 9455,
"text": "We ask the user to input a hash value and the value is assigned the variable user-hash."
},
{
"code": null,
"e": 9632,
"s": 9543,
"text": "The variable sha is created and the hash object is created when we specify the algorithm"
},
{
"code": null,
"e": 9779,
"s": 9632,
"text": "We open up the file we want to validate, using a with statement. We define the variable chunk and assign it the binary data using the read method."
},
{
"code": null,
"e": 9853,
"s": 9779,
"text": "4. We use hashlib update() method to create a hash object for that chunk."
},
{
"code": null,
"e": 9917,
"s": 9853,
"text": "5. We create a hash value for this chunk using sha.hexdigest()."
},
{
"code": null,
"e": 10075,
"s": 9917,
"text": "6. We use the assert keyword, which evaluates an expression for truth. In this case, assess the data downloaded’s hash value against the hash value inputted."
},
{
"code": null,
"e": 10197,
"s": 10075,
"text": "7. We specify an exception AssertionError. This is called when an assert statement is false and specify an error message."
},
{
"code": null,
"e": 10323,
"s": 10197,
"text": "8. In an else statement, if the user_hash variable is the same as the file’s hash value, we print that the file is validated."
},
{
"code": null,
"e": 10399,
"s": 10323,
"text": "So here we have created a very simple validating tool for downloaded files."
},
{
"code": null,
"e": 10723,
"s": 10399,
"text": "There are many packages to display progress in your programming code. Here we will talk about a simple way to add a progress bar when downloading files! This may be useful if you are downloading in bulk and want to see the progress as you go. Progress bars can be useful in all sorts of ways not only for downloading files."
},
{
"code": null,
"e": 10905,
"s": 10723,
"text": "Tqdm is a third party python package that can deal with progress bars. To me, this is the best way to think about python, start with as little code as possible to get what you want."
},
{
"code": null,
"e": 10956,
"s": 10905,
"text": "First off you will want to install tqdm using pip."
},
{
"code": null,
"e": 10973,
"s": 10956,
"text": "pip install tqdm"
},
{
"code": null,
"e": 11159,
"s": 10973,
"text": "Then we will want to import tqdm. Now it’s the tqdm method we want to use to display the progress of data. The tqdm module can interpret each chunk and display the progress of the file."
},
{
"code": null,
"e": 11647,
"s": 11159,
"text": "To incorporate the progress bar into downloading files. First, we have to create a few variables, the most important being the size of a file. We can use the request package to do this. We grab the binary headers and inside ‘content-length’. Scroll up at the binary headers in another section to see. Its associated value is how many bytes of data we have requested from the server. The response is a string and we have to convert this to number format when using it for the progress bar"
},
{
"code": null,
"e": 11764,
"s": 11647,
"text": "The other important part is the filename. We can split the URL up into a list and choose the last item quite simply."
},
{
"code": null,
"e": 11835,
"s": 11764,
"text": "We then specify the tqdm module once we have all the variables set up."
},
{
"code": null,
"e": 12107,
"s": 11835,
"text": "A with statement means it closes once the operation is complete and the open function writes data. We then use the tqdm method and specify the arguments to display the data being downloaded. Be aware the arguments are are quite detailed! Let’s go through them one by one."
},
{
"code": null,
"e": 12569,
"s": 12107,
"text": "The total argument is the size of file, which we defined.The unit argument is the string we specify to define the unit of each iteration of the chunk of data. We specify B in this case for bytes.The desc argument displays the filenameThe initial argument specifies where to start the progress bar from in this case 0.The ascii argument is to specify what we use to fill the progress bar with. If set to false it assumes unicode to fill the progress bar instead."
},
{
"code": null,
"e": 12627,
"s": 12569,
"text": "The total argument is the size of file, which we defined."
},
{
"code": null,
"e": 12766,
"s": 12627,
"text": "The unit argument is the string we specify to define the unit of each iteration of the chunk of data. We specify B in this case for bytes."
},
{
"code": null,
"e": 12806,
"s": 12766,
"text": "The desc argument displays the filename"
},
{
"code": null,
"e": 12890,
"s": 12806,
"text": "The initial argument specifies where to start the progress bar from in this case 0."
},
{
"code": null,
"e": 13035,
"s": 12890,
"text": "The ascii argument is to specify what we use to fill the progress bar with. If set to false it assumes unicode to fill the progress bar instead."
},
{
"code": null,
"e": 13101,
"s": 13035,
"text": "Let's look at the code now that we’ve explained what we’re doing:"
},
{
"code": null,
"e": 13623,
"s": 13101,
"text": "from tqdm import tqdmurl = \"insert here\"file = url.split('/')[-1]r = requests.get(url, stream=True, allow_redirects=True)total_size = int(r.headers.get('content-length'))initial_pos = 0with open(file,'wb') as f: with tqdm(total=total_size, unit=B, unit_scale=True, desc=file,initial=initial_pos, ascii=True) as pbar: for ch in r.iter_content(chunk_size=1024), if ch: f.write(ch) pbar.update(len(ch))"
},
{
"code": null,
"e": 13631,
"s": 13623,
"text": "Output:"
},
{
"code": null,
"e": 13735,
"s": 13631,
"text": "filename.zip 100%|#################################################| 3.71M/3.71M [00:26<00:00, 254kB/s]"
},
{
"code": null,
"e": 13741,
"s": 13735,
"text": "Notes"
},
{
"code": null,
"e": 14920,
"s": 13741,
"text": "We import the tqdm method from the tqdm module.The variable url is defined.The file variable is defined, we use the split string method to split up url into a list. The (‘/’) argument is what tells the split method to split the string up between the /’s of the url. Here, we want to get the last index of the list as this will be the file name we desire.The variable r is used to specify an HTTP get request which we allow to have an open stream of data and allow redirects.The total_size variable is defined and use the request packge to get the binary headers. Using the get method we get the ‘content-length’ value which is the size of the binary files. Now, this returns a string and we make this into a number using int().The variable initial_pos is assigned as 0, which is important to specify for the tqdm method.We access the tqdm method using a with statement. We specify a few items within the arguments.The r.iter_content splits the data into chunks. We define ch as a chunk of 1024 bytes and if the chunk is available we write that chunk to the file.We call upon the update attribute of the tqdm method to update that chunk to the progress bar and display it for us."
},
{
"code": null,
"e": 14968,
"s": 14920,
"text": "We import the tqdm method from the tqdm module."
},
{
"code": null,
"e": 14997,
"s": 14968,
"text": "The variable url is defined."
},
{
"code": null,
"e": 15277,
"s": 14997,
"text": "The file variable is defined, we use the split string method to split up url into a list. The (‘/’) argument is what tells the split method to split the string up between the /’s of the url. Here, we want to get the last index of the list as this will be the file name we desire."
},
{
"code": null,
"e": 15398,
"s": 15277,
"text": "The variable r is used to specify an HTTP get request which we allow to have an open stream of data and allow redirects."
},
{
"code": null,
"e": 15652,
"s": 15398,
"text": "The total_size variable is defined and use the request packge to get the binary headers. Using the get method we get the ‘content-length’ value which is the size of the binary files. Now, this returns a string and we make this into a number using int()."
},
{
"code": null,
"e": 15746,
"s": 15652,
"text": "The variable initial_pos is assigned as 0, which is important to specify for the tqdm method."
},
{
"code": null,
"e": 15841,
"s": 15746,
"text": "We access the tqdm method using a with statement. We specify a few items within the arguments."
},
{
"code": null,
"e": 15990,
"s": 15841,
"text": "The r.iter_content splits the data into chunks. We define ch as a chunk of 1024 bytes and if the chunk is available we write that chunk to the file."
},
{
"code": null,
"e": 16107,
"s": 15990,
"text": "We call upon the update attribute of the tqdm method to update that chunk to the progress bar and display it for us."
},
{
"code": null,
"e": 16256,
"s": 16107,
"text": "So after that, you should have a better idea of how to deal with progress bars, validating files and going beyond the basics of the request package."
},
{
"code": null,
"e": 16276,
"s": 16256,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 16293,
"s": 16276,
"text": "About the author"
},
{
"code": null,
"e": 16499,
"s": 16293,
"text": "I am a medical doctor who has a keen interest in teaching, python, technology, and healthcare. I am based in the UK, I teach online clinical education as well as running the websites www.coding-medics.com."
},
{
"code": null,
"e": 16679,
"s": 16499,
"text": "You can contact me on [email protected] or on twitter here, all comments and recommendations welcome! If you want to chat about any projects or to collaborate that would be great."
}
] |
Python program for removing nth character from a string | In this article, we will learn about the solution to the problem statement given below −
Problem statement − We are given a string, we have to remove the ith indexed character from the given string and display it.
In any string in Python, indexing always starts from 0. Suppose we have a string “tutorialspoint” then its indexing will be done as shown below −
T u t o r i a l s p o i n t
0 1 2 3 4 5 6 7 8 9 10 11 12 13
Now let’s see the Python script for solving the statement −
Live Demo
def remove(string, i):
# slicing till ith character
a = string[ : i]
# slicing from i+1th index
b = string[i + 1: ]
return a + b
# Driver Code
if __name__ == '__main__':
string = "Tutorialspoint"
# Remove nth index element
i = 8
print(remove(string, i))
Tutorialpoint
Algorithms − From the given input string, i-th indexed element has to be popped. So, Split the string into two parts, before indexed character, and after indexed character thereby leaving the ith character Return the merged string.
Here we have three variables declared in global scope as shown below −
In this article, we learned about the removal of ith character from a given input string in Python 3.x or earlier | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below −"
},
{
"code": null,
"e": 1276,
"s": 1151,
"text": "Problem statement − We are given a string, we have to remove the ith indexed character from the given string and display it."
},
{
"code": null,
"e": 1422,
"s": 1276,
"text": "In any string in Python, indexing always starts from 0. Suppose we have a string “tutorialspoint” then its indexing will be done as shown below −"
},
{
"code": null,
"e": 1486,
"s": 1422,
"text": "T u t o r i a l s p o i n t\n0 1 2 3 4 5 6 7 8 9 10 11 12 13"
},
{
"code": null,
"e": 1546,
"s": 1486,
"text": "Now let’s see the Python script for solving the statement −"
},
{
"code": null,
"e": 1557,
"s": 1546,
"text": " Live Demo"
},
{
"code": null,
"e": 1838,
"s": 1557,
"text": "def remove(string, i):\n # slicing till ith character\n a = string[ : i]\n # slicing from i+1th index\n b = string[i + 1: ]\n return a + b\n# Driver Code\nif __name__ == '__main__':\n string = \"Tutorialspoint\"\n # Remove nth index element\n i = 8\n print(remove(string, i))"
},
{
"code": null,
"e": 1852,
"s": 1838,
"text": "Tutorialpoint"
},
{
"code": null,
"e": 2084,
"s": 1852,
"text": "Algorithms − From the given input string, i-th indexed element has to be popped. So, Split the string into two parts, before indexed character, and after indexed character thereby leaving the ith character Return the merged string."
},
{
"code": null,
"e": 2155,
"s": 2084,
"text": "Here we have three variables declared in global scope as shown below −"
},
{
"code": null,
"e": 2269,
"s": 2155,
"text": "In this article, we learned about the removal of ith character from a given input string in Python 3.x or earlier"
}
] |
Hands-on Machine Learning Model Interpretation | by Dipanjan (DJ) Sarkar | Towards Data Science | Interpreting Machine Learning models is no longer a luxury but a necessity given the rapid adoption of AI in the industry. This article in a continuation in my series of articles aimed at ‘Explainable Artificial Intelligence (XAI)’. The idea here is to cut through the hype and enable you with the tools and techniques needed to start interpreting any black box machine learning model. Following are the previous articles in the series in case you want to give them a quick skim (but are not mandatory for this article).
Part 1 — The Importance of Human Interpretable Machine Learning’: which covers the what and why of human interpretable machine learning and the need and importance of model interpretation along with its scope and criteria
Part 2 —Model Interpretation Strategies’ which covers the how of human interpretable machine learning where we look at essential concepts pertaining to major strategies for model interpretation.
In this article we will give you hands-on guides which showcase various ways to explain potential black-box machine learning models in a model-agnostic way. We will be working on a real-world dataset on Census income, also known as the Adult dataset available in the UCI ML Repository where we will be predicting if the potential income of people is more than $50K/yr or not.
The purpose of this article is manifold. The first main objective is to familiarize ourselves with the major state-of-the-art model interpretation frameworks out there (a lot of them being extensions of LIME — the original framework and approach proposed for model interpretation which we have covered in detail in Part 2 of this series).
We cover usage of the following model interpretation frameworks in our tutorial.
ELI5
Skater
SHAP
The major model interpretation techniques we will be covering in this tutorial include the following.
Feature Importances
Partial Dependence Plots
Model Prediction Explanations with Local Interpretation
Building Interpretable Models with Surrogate Tree-based Models
Model Prediction Explanation with SHAP values
Dependence & Interaction Plots with SHAP
Without further ado let’s get started!
We will be using a lot of frameworks and tools in this article given it is a hands-on guide to model interpretation. We recommend you to load up the following dependencies to get the maximum out of this guide!
Rememeber to call the shap.initjs() function since a lot of the plots from shap require JavaScript.
You can actually get the census income dataset (popularly known as the adult dataset) from the UCI ML repository. Fortunately shap provides us an already cleaned up version of this dataset which we will be using here since the intent of this article is model interpretation.
Let’s take a look at the major features or attributes of our dataset.
((32561, 12), (32561,))
We will explain these features shortly.
Let’s view the distribution of people with <= $50K (False) and > $50K (True) income which are our class labels which we want to predict.
In [6]: Counter(labels)Out[6]: Counter({0: 24720, 1: 7841})
Definitely some class imbalance which is expected given that we should have less people having a higher income.
Let’s now take a look at our dataset attributes and understand their meaning and significance.
We have a total of 12 features and our objective is to predict if the income of a person will be more than $50K (True) or less than $50K (False). Hence we will be building and interpreting a classification model.
Here we convert the categorical columns with string values to numeric representations. Typically the XGBoost model can handle categorical data natively being a tree-based model so we don’t one-hot encode the features here.
Time to build our train and test datasets before we build our classification model.
For any machine learning model, we always need train and test datasets. We will be building the model on the train dataset and test the performance on the test dataset. We maintain two datasets (one with the encoded categorical values and one with the original values) so we can train with the encoded dataset but use the original dataset as needed later on for model interpretation.
((22792, 12), (9769, 12))
We also maintain our base dataset with the actual (not encoded) values also in a separate dataframe (useful for model interpretation later).
((22792, 12), (9769, 12))
We will now train and build a basic boosting classification model on our training data using the popular XGBoost framework, an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable.
Wall time: 8.16 s
Here we do the usual, use the trained model to make predictions on the test dataset.
array([0, 0, 1, 0, 0, 1, 1, 0, 0, 1])
Time to put the model to the test! Let’s evaluate how our model has performed with its predictions on the test data. We use my nifty model_evaluation_utils module for this which leverages scikit-learn internally to give us standard classification model evaluation metrics.
By default it is difficult to gauge on specific model interpretation methods for machine learning models out of the box. Parametric models like logistic regression are easier to interpret given that the total number of parameters of the model are fixed regardless of the volume of data and one can make some interpretation of the model’s prediction decisions leveraging the parameter coefficients.
Non-parametric models are harder to interpret given that the total number of parameters remain unbounded and increase with the increase in the data volume. Some non-parametric models like tree-based models do have some out of the box model interpretation methods like feature importance which helps us in understanding which features might be influential in the model making its prediction decisions.
Here we try out the global feature importance calcuations that come with XGBoost. The model enables us to view feature importances based on the following.
Feature Weights: This is based on the number of times a feature appears in a tree across the ensemble of trees
Gain: This is based on the average gain of splits which use the feature
Coverage: This is based on the average coverage (number of samples affected) of splits which use the feature
Note that they all contradict each other, which motivates the use of model interpretation frameworks like SHAP which uses something known as SHAP values, which claim to come with consistency guarantees (meaning they will typically order the features correctly).
ELI5 is a Python package which helps to debug machine learning classifiers and explain their predictions in an easy to understand an intuitive way. It is perhaps the easiest of the three machine learning frameworks to get started with since it involves minimal reading of documentation! However it doesn’t support true model-agnostic interpretations and support for models are mostly limited to tree-based and other parametric\linear models. Let’s look at some intuitive ways of model interpretation with ELI5 on our classification model.
We recommend installing this framework using pip install eli5 since the conda version appears to be a bit out-dated. Also feel free to check out the documentation as needed.
Typically for tree-based models ELI5 does nothing special but uses the out-of-the-box feature importance computation methods which we discussed in the previous section. By default, ‘gain’ is used, that is the average gain of the feature when it is used in trees.
eli5.show_weights(xgc.get_booster())
One of the best way to explain model prediction decisions to either a technical or a more business-oriented individual, is to examine individual data-point predictions. Typically, ELI5 does this by showing weights for each feature depicting how influential it might have been in contributing to the final prediction decision across all trees. The idea for weight calculation is described here; ELI5 provides an independent implementation of this algorithm for XGBoost and most scikit-learn tree ensembles which is definitely on the path towards model-agnostic interpretation but not purely model-agnostic like LIME.
Typically, the prediction can be defined as the sum of the feature contributions + the “bias” (i.e. the mean given by the topmost region that covers the entire training set)
Here we can see the most influential features being the Age, Hours per week, Marital Status, Occupation & Relationship
Here we can see the most influential features being the Education, Relationship, Occupation, Hours per week & Marital Status
It is definitely interesting to see how similar features play an influential role in explaining model prediction decisions for both classes!
Skater is a unified framework to enable Model Interpretation for all forms of models to help one build an Interpretable machine learning system often needed for real world use-cases using a model-agnostic approach. It is an open source python library designed to demystify the learned structures of a black box model both globally(inference on the basis of a complete data set) and locally(inference about an individual prediction).
Skater originally started off as a fork of LIME but then broke out as an independent framework of it’s own with a wide variety of feature and capabilities for model-agnostic interpretation for any black-box models. The project was started as a research idea to find ways to enable better interpretability(preferably human interpretability) to predictive “black boxes” both for researchers and practitioners.
You can typically install Skater using a simple pip install skater. For detailed information on the dependencies and installation instruction check out installing skater.
We recommend you to check out the detailed documentation of Skater.
Skater has a suite of model interpretation techniques some of which are mentioned below.
Since the project is under active development, the best way to understand usage would be to follow the examples mentioned in the Gallery of Interactive Notebook. But we will be showcasing its major capabilities using the model trained on our census dataset.
A predictive model is a mapping from an input space to an output space. Interpretation algorithms are divided into those that offer statistics and metrics on regions of the domain, such as the marginal distribution of a feature, or the joint distribution of the entire training set. In an ideal world there would exist some representation that would allow a human to interpret a decision function in any number of dimensions. Given that we generally can only intuit visualizations of a few dimensions at time, global interpretation algorithms either aggregate or subset the feature space.
Currently, model-agnostic global interpretation algorithms supported by skater include partial dependence and feature importance with a very new release of tree-surrogates also. We will be covering feature importance and partial dependence plots here.
The general workflow within the skater package is to create an interpretation, create a model, and run interpretation algorithms. Typically, an Interpretation consumes a dataset, and optionally some metadata like feature names and row ids. Internally, the Interpretation will generate a DataManager to handle data requests and sampling.
Local Models(InMemoryModel): To create a skater model based on a local function or method, pass in the predict function to an InMemoryModel. A user can optionally pass data samples to the examples keyword argument. This is only used to infer output types and formats. Out of the box, skater allows models return numpy arrays and pandas dataframes.
Operationalized Model(DeployedModel): If your model is accessible through an API, use a DeployedModel, which wraps the requests library. DeployedModels require two functions, an input formatter and an output formatter, which speak to the requests library for posting and parsing. The input formatter takes a pandas DataFrame or a numpy ndarray, and returns an object (such as a dict) that can be converted to JSON to be posted. The output formatter takes a requests.response as an input and returns a numpy ndarray or pandas DataFrame.
We will use the following workflow:
Build an interpretation object
Build an in-memory model
Perform interpretations
Feature importance is generic term for the degree to which a predictive model relies on a particular feature. The skater feature importance implementation is based on an information theoretic criteria, measuring the entropy in the change of predictions, given a perturbation of a given feature. The intuition is that the more a model’s decision criteria depend on a feature, the more we’ll see predictions change as a function of perturbing a feature. The default method used is prediction-variance which is the mean absolute value of changes in predictions, given perturbations in the data.
Partial Dependence describes the marginal impact of a feature on model prediction, holding other features in the model constant. The derivative of partial dependence describes the impact of a feature (analogous to a feature coefficient in a regression model). This has been adapted from T. Hastie, R. Tibshirani and J. Friedman, Elements of Statistical Learning Ed. 2, Springer. 2009.
The partial dependence plot (PDP or PD plot) shows the marginal effect of a feature on the predicted outcome of a previously fit model. PDPs can show if the relationship between the target and a feature is linear, monotonic or more complex. Skater can show 1-D as well as 2-D PDPs
Let’s take a look at how the Age feature affects model predictions.
Looks like the middle-aged people have a slightly higher chance of making more money as compared to younger or older people.
Let’s take a look at how the Education-Num feature affects model predictions.
Looks like higher the education level, the better the chance of making more money. Not surprising!
Let’s take a look at how the Capital Gain feature affects model predictions.
Unsurprisingly higher the capital gain, the more chance of making money, there is a steep rise in around $5K — $8K.
Remember that relationship is coded as a categorical variable with numeric representations. Let’s first look at how it is represented.
Let’s now take a look at how the Relationship feature affects model predictions.
Interesting definitely that married folks (husband-wife) have a higher chance of making more money than others!
We run a deeper model interpretation here over all the data samples, trying to see interactions between Age and Education-Numand also their effect on the probability of the model predicting if the person will make more money, with the help of a two-way partial dependence plot.
Interesting to see higher the education level and the middle-aged folks (30–50) having the highest chance of making more money!
We run a deeper model interpretation here over all the data samples, trying to see interactions between Education-Num and Capital Gain and also their effect on the probability of the model predicting if the person will make more money, with the help of a two-way partial dependence plot.
Basically having a better education and more capital gain leads to you making more money!
Local Interpretation could be possibly be achieved in two ways. Firstly, one could possibly approximate the behavior of a complex predictive model in the vicinity of a single input using a simple interpretable auxiliary or surrogate model (e.g. Linear Regressor). Secondly, one could use the base estimator to understand the behavior of a single prediction using intuitive approximate functions based on inputs and outputs.
LIME is a novel algorithm designed by Riberio Marco, Singh Sameer, Guestrin Carlos to access the behavior of the any base estimator(model) using interpretable surrogate models (e.g. linear classifier/regressor). Such form of comprehensive evaluation helps in generating explanations which are locally faithful but may not align with the global behavior. Basically, LIME explanations are based on local surrogate models. These, surrogate models are interpretable models (like a linear model or decision tree) that are learned on the predictions of the original black box model. But instead of trying to fit a global surrogate model, LIME focuses on fitting local surrogate models to explain why single predictions were made.
The idea is very intuitive. To start with, just try and unlearn what you have done so far! Forget about the training data, forget about how your model works! Think that your model is a black box model with some magic happening inside, where you can input data points and get the models predicted outcomes. You can probe this magic black box as often as you want with inputs and get output predictions.
Now, you main objective is to understand why the machine learning model which you are treating as a magic black box, gave the outcome it produced. LIME tries to do this for you! It tests out what happens to you black box model’s predictions when you feed variations or perturbations of your dataset into the black box model. Typically, LIME generates a new dataset consisting of perturbed samples and the associated black box model’s predictions. On this dataset LIME then trains an interpretable model weighted by the proximity of the sampled instances to the instance of interest. Following is a standard high-level workflow for this.
Choose your instance of interest for which you want to have an explanation of the predictions of your black box model.
Perturb your dataset and get the black box predictions for these new points.
Weight the new samples by their proximity to the instance of interest.
Fit a weighted, interpretable (surrogate) model on the dataset with the variations.
Explain prediction by interpreting the local model.
We recommend you to read the LIME chapter in Christoph Molnar’s excellent book on Model Interpretation which talks about this in detail.
Skater can leverage LIME to explain model predictions. Typically, its LimeTabularExplainer class helps in explaining predictions on tabular (i.e. matrix) data. For numerical features, it perturbs them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, it perturbs by sampling according to the training distribution, and making a binary feature that is 1 when the value is the same as the instance being explained. The explain_instance() function generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance. We then learn locally weighted linear (surrogate) models on this neighborhood data to explain each of the classes in an interpretable way.
Since XGBoost has some issues with feature name ordering when building models with dataframes, we will build our same model with numpy arrays to make LIME work without additional hassles of feature re-ordering. Remember the model being built is the same ensemble model which we treat as our black box machine learning model.
XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=5, min_child_weight=1, missing=None, n_estimators=500, n_jobs=1, nthread=None, objective='binary:logistic', random_state=42, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=1)
Skater gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as below $50K.
Skater gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as above $50K.
We have see various ways to interpret machine learning models with features, dependence plots and even LIME. But can we build an approximation or a surrogate model which is more interpretable from a really complex black box model like our XGBoost model having hundreds of decision trees?
Here in, we introduce the novel idea of using TreeSurrogates as means for explaining a model's learned decision policies (for inductive learning tasks), which is inspired by the work of Mark W. Craven described as the TREPAN algorithm.
We recommend checking out the following excellent papers on the TREPAN algorithm to build surrogate trees.
Mark W. Craven(1996) EXTRACTING COMPREHENSIBLE MODELS FROM TRAINED NEURAL NETWORKS
Mark W. Craven and Jude W. Shavlik(NIPS, 96). Extracting Thee-Structured Representations of Thained Networks
Briefly, Trepan constructs a decision tree in a best-first manner. It maintains a queue of leaves which are expanded into subtrees as they are removed from the queue. With each node in the queue, Trepan stores,
A subset of the training examples,
Another set of instances (query instances),
A set of constraints.
The stored subset of training examples consists simply of those examples that reach the node. The query instances are used, along with the training examples, to select the splitting test if the node is an internal node or to determine the class label if it is a leaf. The constraint set describes the conditions that instances must satisfy in order to reach the node; this information is used when drawing a set of query instances for a newly created node. The process of expanding a node in Trepan is much like it is in conventional decision tree algorithms: a splitting test is selected for the node, and a child is created for each outcome of the test. Each child is either made a leaf of the tree or put into the queue for future expansion.
For Skater’s implementation, for building explainable surrogate models, the base estimator(Oracle) could be any form of a supervised learning predictive model — our black box model. The explanations are approximated using Decision Trees(both for Classification/Regression) by learning decision boundaries similar to that learned by the Oracle (predictions from the base model are used for learning the Decision Tree representation). The implementation also generates a fidelity score to quantify tree based surrogate model’s approximation to the Oracle. Ideally, the score should be 0 for truthful explanation both globally and locally. Let’s check this out in action!
NOTE: The implementation is currently experimental and might change in future.
We can use the Interpretation object we instantiated earlier to invoke a call to the TreeSurrogate capability.
We can now fit this surrogate model on our dataset to learn the decision boundaries of our base estimator.
Reports the fidelity value when compared to the base estimator (closer to 0 is better)
Learner uses F1-score as the default metric of choice for classification.
0.009
We do this since the feature names in the surrogate tree are not displayed (but are present in the model)
We can now visualize our surrogate tree model using the following code.
Here are some interesting rules you can observe from the above tree.
If Relationship < 0.5 (means 0) and Education-num <= 9.5 and Capital Gain <= 4225 → 70% chance of person making <= $50K
If Relationship < 0.5 (means 0) and Education-num <= 9.5 and Capital Gain >= 4225 → 94.5% chance of person making > $50K
If Relationship < 0.5 (means 0) and Education-num >= 9.5 and Education-num is also >= 12.5 → 94.7% chance of person making > $50K
Feel free to derive more interesting rules from this and also your own models! Let’s look at how our surrogate model performs on the test dataset now.
Let’s check the performance of our surrogate model now on the test data.
Just as expected, the model performance drops a fair bit but still we get an overall F1-score of 83% as compared to our boosted model’s score of 87% which is quite good!
SHAP (SHapley Additive exPlanations) is a unified approach to explain the output of any machine learning model. SHAP connects game theory with local explanations, uniting several previous methods and representing the only possible consistent and locally accurate additive feature attribution method based on what they claim! (do check out the SHAP NIPS paper for details). We have also covered this in detail in Part 2 of this series.
SHAP can be installed from PyPI
pip install shap
or conda-forge
conda install -c conda-forge shap
The really awesome aspect about this framework is while SHAP values can explain the output of any machine learning model, for really complex ensemble models it can be slow. But they have developed a high-speed exact algorithm for tree ensemble methods (Tree SHAP arXiv paper). Fast C++ implementations are supported for XGBoost, LightGBM, CatBoost, and scikit-learn tree models!
SHAP (SHapley Additive exPlanations) assigns each feature an importance value for a particular prediction. Its novel components include: the identification of a new class of additive feature importance measures, and theoretical results showing there is a unique solution in this class with a set of desirable properties. Typically, SHAP values try to explain the output of a model (function) as a sum of the effects of each feature being introduced into a conditional expectation. Importantly, for non-linear functions the order in which features are introduced matters. The SHAP values result from averaging over all possible orderings. Proofs from game theory show this is the only possible consistent approach.
An intuitive way to understand the Shapley value is the following: The feature values enter a room in random order. All feature values in the room participate in the game (= contribute to the prediction). The Shapley value φij is the average marginal contribution of feature value xij by joining whatever features already entered the room before, i.e.
The following figure from the KDD 18 paper, Consistent Individualized Feature Attribution for Tree Ensembles summarizes this in a nice way!
Let’s now dive into SHAP and leverage it for interpreting our model!
Here we use the Tree SHAP implementation integrated into XGBoost to explain the test dataset! Remember that there are a variety of explainer methods based on the type of models you are building. We estimate the SHAP values for a set of samples (test data)
Expected Value: -1.3625857
This returns a matrix of SHAP values (# samples, # features). Each row sums to the difference between the model output for that sample and the expected value of the model output (which is stored as expected_value attribute of the explainer). Typically this difference helps us in explaining why the model is inclined on predicting a specific class outcome.
SHAP gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as below $50K. The below explanation shows features each contributing to push the model output from the base value (the average model output over the training dataset we passed) to the actual model output. Features pushing the prediction higher are shown in red, those pushing the prediction lower are in blue.
Similarly, SHAP gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as greater than $50K.
One of the key advantages of SHAP is it can build beautiful interactive plots which can visualize and explain multiple predictions at once. Here we visualize model prediction decisions for the first 1000 test data samples.
The above visualization can be interacted with in multiple ways. The default visualization shows some interesting model prediction pattern decisions.
The first 100 test samples all probably earn more than $50K and they are married or\and have a good capital gain or\and have a higher education level!
The next 170+ test samples all probably earn less than or equal to $50K and they are mostly un-married and\or are very young in age or divorced!
The next 310+ test samples have an inclination towards mostly earning more than $50K and they are of diverse profiles including married folks, people with different age and education levels and occupation. Most dominant features pushing the model towards making a prediction for higher income is the person being married i.e. relationship: husband or wife!
The remaining 400+ test samples have an inclination towards mostly earning less than $50K and they are of diverse profiles however dominant patterns include relationship: either unmarried or divorced and very young in age!
Definitely interesting how we can find out patterns which lead to the model making specific decisions and being able to provide explanations for them.
This basically takes the average of the SHAP value magnitudes across the dataset and plots it as a simple bar chart.
Besides a typical feature importance bar chart, SHAP also enables us to use a density scatter plot of SHAP values for each feature to identify how much impact each feature has on the model output for individuals in the validation dataset. Features are sorted by the sum of the SHAP value magnitudes across all samples. Note that when the scatter points don’t fit on a line they pile up to show density, and the color of each point represents the feature value of that individual.
It is interesting to note that the age and marital status feature has more total model impact than the capital gain feature, but for those samples where capital gain matters it has more impact than age or marital status. In other words, capital gain affects a few predictions by a large amount, while age or marital status affects all predictions by a smaller amount.
SHAP dependence plots show the effect of a single (or two) feature across the whole dataset. They plot a feature’s value vs. the SHAP value of that feature across many samples. SHAP dependence plots are similar to partial dependence plots, but account for the interaction effects present in the features, and are only defined in regions of the input space supported by data. The vertical dispersion of SHAP values at a single feature value is driven by interaction effects, and another feature can be chosen for coloring to highlight possible interactions.
You will also notice its similarity with Skater’s Partial Dependence Plots!
Let’s take a look at how the Age feature affects model predictions.
Just like we observed before. the middle-aged people have a slightly higher shap value, pushing the model’s prediction decisions to say that these individuals make more money as compared to younger or older people
Let’s take a look at how the Education-Num feature affects model predictions.
Higher education levels have higher shap values, pushing the model’s prediction decisions to say that these individuals make more money as compared to people with lower education levels.
Let’s take a look at how the Relationship feature affects model predictions.
Just like we observed during the model prediction explanations, married people (husband or wife) have a slightly higher shap value, pushing the model’s prediction decisions to say that these individuals make more money as compared to other folks!
Let’s take a look at how the Capital Gain feature affects model predictions.
The vertical dispersion of SHAP values at a single feature value is driven by interaction effects, and another feature is chosen for coloring to highlight possible interactions. Here we are trying to see interactions between Age and Capital Gainand also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot.
Interesting to see higher the higher capital gain and the middle-aged folks (30–50) having the highest chance of making more money!
Here we are trying to see interactions between Education-Num and Relationship and also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot.
This is interesting because both the features are similar in some context, we can see typically married people with relationship status of either husband or wife having the highest chance of making more money!
Here we are trying to see interactions between Marital Status and Relationship and also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot.
Interesting to see higher the higher education level and the husband or wife (married) folks having the highest chance of making more money!
Here we are trying to see interactions between Age and Hours per week and also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot.
Nothing extra-ordinary here, middle-aged people working the most make the most money!
If you are reading this, I would like to really commend your efforts on going through this huge and comprehensive tutorial on machine learning model interpretation. This article should help you leverage the state-of-the-art tools and techniques which should help you in your journey on the road towards Explanable AI (XAI). Based on the concepts and techniques we learnt in Part 2, in this article, we actually implemented them all on a complex machine learning ensemble model trained on a real-world dataset. I encourage you to try out some of these frameworks with your own models and datasets and explore the world of model interpretation!
In Part 4 of this series, we will be looking at a comprehensive guide to building interpreting models on unstructured data like text and maybe even deep learning models!
Hands-on Model Interpretation on Unstructured Datasets
Advanced Model Interpretation on Deep Learning Models
Stay tuned for some interesting content!
Note: There are a lot of rapid developments in this area including a lot of new tools and frameworks being released over time. In case you want me to cover any other popular frameworks, feel free to reach out to me. I’m definitely interested and will be starting by taking a look into H2O’s model interpretation capabilities some time in the future.
The code used in this article is available on my GitHub and also as an interactive Jupyter Notebook.
Check out ‘Part 1 — The Importance of Human Interpretable Machine Learning’ which covers the what and why of human interpretable machine learning and the need and importance of model interpretation along with its scope and criteria in case you haven’t!
Also Part 2 — Model Interpretation Strategies’ which covers the how of human interpretable machine learning where we look at essential concepts pertaining to major strategies for model interpretation.
Have feedback for me? Or interested in working with me on research, data science, artificial intelligence or even publishing an article on TDS? You can reach out to me on LinkedIn. | [
{
"code": null,
"e": 693,
"s": 172,
"text": "Interpreting Machine Learning models is no longer a luxury but a necessity given the rapid adoption of AI in the industry. This article in a continuation in my series of articles aimed at ‘Explainable Artificial Intelligence (XAI)’. The idea here is to cut through the hype and enable you with the tools and techniques needed to start interpreting any black box machine learning model. Following are the previous articles in the series in case you want to give them a quick skim (but are not mandatory for this article)."
},
{
"code": null,
"e": 915,
"s": 693,
"text": "Part 1 — The Importance of Human Interpretable Machine Learning’: which covers the what and why of human interpretable machine learning and the need and importance of model interpretation along with its scope and criteria"
},
{
"code": null,
"e": 1110,
"s": 915,
"text": "Part 2 —Model Interpretation Strategies’ which covers the how of human interpretable machine learning where we look at essential concepts pertaining to major strategies for model interpretation."
},
{
"code": null,
"e": 1486,
"s": 1110,
"text": "In this article we will give you hands-on guides which showcase various ways to explain potential black-box machine learning models in a model-agnostic way. We will be working on a real-world dataset on Census income, also known as the Adult dataset available in the UCI ML Repository where we will be predicting if the potential income of people is more than $50K/yr or not."
},
{
"code": null,
"e": 1825,
"s": 1486,
"text": "The purpose of this article is manifold. The first main objective is to familiarize ourselves with the major state-of-the-art model interpretation frameworks out there (a lot of them being extensions of LIME — the original framework and approach proposed for model interpretation which we have covered in detail in Part 2 of this series)."
},
{
"code": null,
"e": 1906,
"s": 1825,
"text": "We cover usage of the following model interpretation frameworks in our tutorial."
},
{
"code": null,
"e": 1911,
"s": 1906,
"text": "ELI5"
},
{
"code": null,
"e": 1918,
"s": 1911,
"text": "Skater"
},
{
"code": null,
"e": 1923,
"s": 1918,
"text": "SHAP"
},
{
"code": null,
"e": 2025,
"s": 1923,
"text": "The major model interpretation techniques we will be covering in this tutorial include the following."
},
{
"code": null,
"e": 2045,
"s": 2025,
"text": "Feature Importances"
},
{
"code": null,
"e": 2070,
"s": 2045,
"text": "Partial Dependence Plots"
},
{
"code": null,
"e": 2126,
"s": 2070,
"text": "Model Prediction Explanations with Local Interpretation"
},
{
"code": null,
"e": 2189,
"s": 2126,
"text": "Building Interpretable Models with Surrogate Tree-based Models"
},
{
"code": null,
"e": 2235,
"s": 2189,
"text": "Model Prediction Explanation with SHAP values"
},
{
"code": null,
"e": 2276,
"s": 2235,
"text": "Dependence & Interaction Plots with SHAP"
},
{
"code": null,
"e": 2315,
"s": 2276,
"text": "Without further ado let’s get started!"
},
{
"code": null,
"e": 2525,
"s": 2315,
"text": "We will be using a lot of frameworks and tools in this article given it is a hands-on guide to model interpretation. We recommend you to load up the following dependencies to get the maximum out of this guide!"
},
{
"code": null,
"e": 2625,
"s": 2525,
"text": "Rememeber to call the shap.initjs() function since a lot of the plots from shap require JavaScript."
},
{
"code": null,
"e": 2900,
"s": 2625,
"text": "You can actually get the census income dataset (popularly known as the adult dataset) from the UCI ML repository. Fortunately shap provides us an already cleaned up version of this dataset which we will be using here since the intent of this article is model interpretation."
},
{
"code": null,
"e": 2970,
"s": 2900,
"text": "Let’s take a look at the major features or attributes of our dataset."
},
{
"code": null,
"e": 2994,
"s": 2970,
"text": "((32561, 12), (32561,))"
},
{
"code": null,
"e": 3034,
"s": 2994,
"text": "We will explain these features shortly."
},
{
"code": null,
"e": 3171,
"s": 3034,
"text": "Let’s view the distribution of people with <= $50K (False) and > $50K (True) income which are our class labels which we want to predict."
},
{
"code": null,
"e": 3231,
"s": 3171,
"text": "In [6]: Counter(labels)Out[6]: Counter({0: 24720, 1: 7841})"
},
{
"code": null,
"e": 3343,
"s": 3231,
"text": "Definitely some class imbalance which is expected given that we should have less people having a higher income."
},
{
"code": null,
"e": 3438,
"s": 3343,
"text": "Let’s now take a look at our dataset attributes and understand their meaning and significance."
},
{
"code": null,
"e": 3651,
"s": 3438,
"text": "We have a total of 12 features and our objective is to predict if the income of a person will be more than $50K (True) or less than $50K (False). Hence we will be building and interpreting a classification model."
},
{
"code": null,
"e": 3874,
"s": 3651,
"text": "Here we convert the categorical columns with string values to numeric representations. Typically the XGBoost model can handle categorical data natively being a tree-based model so we don’t one-hot encode the features here."
},
{
"code": null,
"e": 3958,
"s": 3874,
"text": "Time to build our train and test datasets before we build our classification model."
},
{
"code": null,
"e": 4342,
"s": 3958,
"text": "For any machine learning model, we always need train and test datasets. We will be building the model on the train dataset and test the performance on the test dataset. We maintain two datasets (one with the encoded categorical values and one with the original values) so we can train with the encoded dataset but use the original dataset as needed later on for model interpretation."
},
{
"code": null,
"e": 4368,
"s": 4342,
"text": "((22792, 12), (9769, 12))"
},
{
"code": null,
"e": 4509,
"s": 4368,
"text": "We also maintain our base dataset with the actual (not encoded) values also in a separate dataframe (useful for model interpretation later)."
},
{
"code": null,
"e": 4535,
"s": 4509,
"text": "((22792, 12), (9769, 12))"
},
{
"code": null,
"e": 4766,
"s": 4535,
"text": "We will now train and build a basic boosting classification model on our training data using the popular XGBoost framework, an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable."
},
{
"code": null,
"e": 4784,
"s": 4766,
"text": "Wall time: 8.16 s"
},
{
"code": null,
"e": 4869,
"s": 4784,
"text": "Here we do the usual, use the trained model to make predictions on the test dataset."
},
{
"code": null,
"e": 4907,
"s": 4869,
"text": "array([0, 0, 1, 0, 0, 1, 1, 0, 0, 1])"
},
{
"code": null,
"e": 5180,
"s": 4907,
"text": "Time to put the model to the test! Let’s evaluate how our model has performed with its predictions on the test data. We use my nifty model_evaluation_utils module for this which leverages scikit-learn internally to give us standard classification model evaluation metrics."
},
{
"code": null,
"e": 5578,
"s": 5180,
"text": "By default it is difficult to gauge on specific model interpretation methods for machine learning models out of the box. Parametric models like logistic regression are easier to interpret given that the total number of parameters of the model are fixed regardless of the volume of data and one can make some interpretation of the model’s prediction decisions leveraging the parameter coefficients."
},
{
"code": null,
"e": 5979,
"s": 5578,
"text": "Non-parametric models are harder to interpret given that the total number of parameters remain unbounded and increase with the increase in the data volume. Some non-parametric models like tree-based models do have some out of the box model interpretation methods like feature importance which helps us in understanding which features might be influential in the model making its prediction decisions."
},
{
"code": null,
"e": 6134,
"s": 5979,
"text": "Here we try out the global feature importance calcuations that come with XGBoost. The model enables us to view feature importances based on the following."
},
{
"code": null,
"e": 6245,
"s": 6134,
"text": "Feature Weights: This is based on the number of times a feature appears in a tree across the ensemble of trees"
},
{
"code": null,
"e": 6317,
"s": 6245,
"text": "Gain: This is based on the average gain of splits which use the feature"
},
{
"code": null,
"e": 6426,
"s": 6317,
"text": "Coverage: This is based on the average coverage (number of samples affected) of splits which use the feature"
},
{
"code": null,
"e": 6688,
"s": 6426,
"text": "Note that they all contradict each other, which motivates the use of model interpretation frameworks like SHAP which uses something known as SHAP values, which claim to come with consistency guarantees (meaning they will typically order the features correctly)."
},
{
"code": null,
"e": 7227,
"s": 6688,
"text": "ELI5 is a Python package which helps to debug machine learning classifiers and explain their predictions in an easy to understand an intuitive way. It is perhaps the easiest of the three machine learning frameworks to get started with since it involves minimal reading of documentation! However it doesn’t support true model-agnostic interpretations and support for models are mostly limited to tree-based and other parametric\\linear models. Let’s look at some intuitive ways of model interpretation with ELI5 on our classification model."
},
{
"code": null,
"e": 7401,
"s": 7227,
"text": "We recommend installing this framework using pip install eli5 since the conda version appears to be a bit out-dated. Also feel free to check out the documentation as needed."
},
{
"code": null,
"e": 7664,
"s": 7401,
"text": "Typically for tree-based models ELI5 does nothing special but uses the out-of-the-box feature importance computation methods which we discussed in the previous section. By default, ‘gain’ is used, that is the average gain of the feature when it is used in trees."
},
{
"code": null,
"e": 7701,
"s": 7664,
"text": "eli5.show_weights(xgc.get_booster())"
},
{
"code": null,
"e": 8317,
"s": 7701,
"text": "One of the best way to explain model prediction decisions to either a technical or a more business-oriented individual, is to examine individual data-point predictions. Typically, ELI5 does this by showing weights for each feature depicting how influential it might have been in contributing to the final prediction decision across all trees. The idea for weight calculation is described here; ELI5 provides an independent implementation of this algorithm for XGBoost and most scikit-learn tree ensembles which is definitely on the path towards model-agnostic interpretation but not purely model-agnostic like LIME."
},
{
"code": null,
"e": 8491,
"s": 8317,
"text": "Typically, the prediction can be defined as the sum of the feature contributions + the “bias” (i.e. the mean given by the topmost region that covers the entire training set)"
},
{
"code": null,
"e": 8610,
"s": 8491,
"text": "Here we can see the most influential features being the Age, Hours per week, Marital Status, Occupation & Relationship"
},
{
"code": null,
"e": 8735,
"s": 8610,
"text": "Here we can see the most influential features being the Education, Relationship, Occupation, Hours per week & Marital Status"
},
{
"code": null,
"e": 8876,
"s": 8735,
"text": "It is definitely interesting to see how similar features play an influential role in explaining model prediction decisions for both classes!"
},
{
"code": null,
"e": 9309,
"s": 8876,
"text": "Skater is a unified framework to enable Model Interpretation for all forms of models to help one build an Interpretable machine learning system often needed for real world use-cases using a model-agnostic approach. It is an open source python library designed to demystify the learned structures of a black box model both globally(inference on the basis of a complete data set) and locally(inference about an individual prediction)."
},
{
"code": null,
"e": 9717,
"s": 9309,
"text": "Skater originally started off as a fork of LIME but then broke out as an independent framework of it’s own with a wide variety of feature and capabilities for model-agnostic interpretation for any black-box models. The project was started as a research idea to find ways to enable better interpretability(preferably human interpretability) to predictive “black boxes” both for researchers and practitioners."
},
{
"code": null,
"e": 9888,
"s": 9717,
"text": "You can typically install Skater using a simple pip install skater. For detailed information on the dependencies and installation instruction check out installing skater."
},
{
"code": null,
"e": 9956,
"s": 9888,
"text": "We recommend you to check out the detailed documentation of Skater."
},
{
"code": null,
"e": 10045,
"s": 9956,
"text": "Skater has a suite of model interpretation techniques some of which are mentioned below."
},
{
"code": null,
"e": 10303,
"s": 10045,
"text": "Since the project is under active development, the best way to understand usage would be to follow the examples mentioned in the Gallery of Interactive Notebook. But we will be showcasing its major capabilities using the model trained on our census dataset."
},
{
"code": null,
"e": 10892,
"s": 10303,
"text": "A predictive model is a mapping from an input space to an output space. Interpretation algorithms are divided into those that offer statistics and metrics on regions of the domain, such as the marginal distribution of a feature, or the joint distribution of the entire training set. In an ideal world there would exist some representation that would allow a human to interpret a decision function in any number of dimensions. Given that we generally can only intuit visualizations of a few dimensions at time, global interpretation algorithms either aggregate or subset the feature space."
},
{
"code": null,
"e": 11144,
"s": 10892,
"text": "Currently, model-agnostic global interpretation algorithms supported by skater include partial dependence and feature importance with a very new release of tree-surrogates also. We will be covering feature importance and partial dependence plots here."
},
{
"code": null,
"e": 11481,
"s": 11144,
"text": "The general workflow within the skater package is to create an interpretation, create a model, and run interpretation algorithms. Typically, an Interpretation consumes a dataset, and optionally some metadata like feature names and row ids. Internally, the Interpretation will generate a DataManager to handle data requests and sampling."
},
{
"code": null,
"e": 11829,
"s": 11481,
"text": "Local Models(InMemoryModel): To create a skater model based on a local function or method, pass in the predict function to an InMemoryModel. A user can optionally pass data samples to the examples keyword argument. This is only used to infer output types and formats. Out of the box, skater allows models return numpy arrays and pandas dataframes."
},
{
"code": null,
"e": 12365,
"s": 11829,
"text": "Operationalized Model(DeployedModel): If your model is accessible through an API, use a DeployedModel, which wraps the requests library. DeployedModels require two functions, an input formatter and an output formatter, which speak to the requests library for posting and parsing. The input formatter takes a pandas DataFrame or a numpy ndarray, and returns an object (such as a dict) that can be converted to JSON to be posted. The output formatter takes a requests.response as an input and returns a numpy ndarray or pandas DataFrame."
},
{
"code": null,
"e": 12401,
"s": 12365,
"text": "We will use the following workflow:"
},
{
"code": null,
"e": 12432,
"s": 12401,
"text": "Build an interpretation object"
},
{
"code": null,
"e": 12457,
"s": 12432,
"text": "Build an in-memory model"
},
{
"code": null,
"e": 12481,
"s": 12457,
"text": "Perform interpretations"
},
{
"code": null,
"e": 13073,
"s": 12481,
"text": "Feature importance is generic term for the degree to which a predictive model relies on a particular feature. The skater feature importance implementation is based on an information theoretic criteria, measuring the entropy in the change of predictions, given a perturbation of a given feature. The intuition is that the more a model’s decision criteria depend on a feature, the more we’ll see predictions change as a function of perturbing a feature. The default method used is prediction-variance which is the mean absolute value of changes in predictions, given perturbations in the data."
},
{
"code": null,
"e": 13458,
"s": 13073,
"text": "Partial Dependence describes the marginal impact of a feature on model prediction, holding other features in the model constant. The derivative of partial dependence describes the impact of a feature (analogous to a feature coefficient in a regression model). This has been adapted from T. Hastie, R. Tibshirani and J. Friedman, Elements of Statistical Learning Ed. 2, Springer. 2009."
},
{
"code": null,
"e": 13739,
"s": 13458,
"text": "The partial dependence plot (PDP or PD plot) shows the marginal effect of a feature on the predicted outcome of a previously fit model. PDPs can show if the relationship between the target and a feature is linear, monotonic or more complex. Skater can show 1-D as well as 2-D PDPs"
},
{
"code": null,
"e": 13807,
"s": 13739,
"text": "Let’s take a look at how the Age feature affects model predictions."
},
{
"code": null,
"e": 13932,
"s": 13807,
"text": "Looks like the middle-aged people have a slightly higher chance of making more money as compared to younger or older people."
},
{
"code": null,
"e": 14010,
"s": 13932,
"text": "Let’s take a look at how the Education-Num feature affects model predictions."
},
{
"code": null,
"e": 14109,
"s": 14010,
"text": "Looks like higher the education level, the better the chance of making more money. Not surprising!"
},
{
"code": null,
"e": 14186,
"s": 14109,
"text": "Let’s take a look at how the Capital Gain feature affects model predictions."
},
{
"code": null,
"e": 14302,
"s": 14186,
"text": "Unsurprisingly higher the capital gain, the more chance of making money, there is a steep rise in around $5K — $8K."
},
{
"code": null,
"e": 14437,
"s": 14302,
"text": "Remember that relationship is coded as a categorical variable with numeric representations. Let’s first look at how it is represented."
},
{
"code": null,
"e": 14518,
"s": 14437,
"text": "Let’s now take a look at how the Relationship feature affects model predictions."
},
{
"code": null,
"e": 14630,
"s": 14518,
"text": "Interesting definitely that married folks (husband-wife) have a higher chance of making more money than others!"
},
{
"code": null,
"e": 14908,
"s": 14630,
"text": "We run a deeper model interpretation here over all the data samples, trying to see interactions between Age and Education-Numand also their effect on the probability of the model predicting if the person will make more money, with the help of a two-way partial dependence plot."
},
{
"code": null,
"e": 15036,
"s": 14908,
"text": "Interesting to see higher the education level and the middle-aged folks (30–50) having the highest chance of making more money!"
},
{
"code": null,
"e": 15324,
"s": 15036,
"text": "We run a deeper model interpretation here over all the data samples, trying to see interactions between Education-Num and Capital Gain and also their effect on the probability of the model predicting if the person will make more money, with the help of a two-way partial dependence plot."
},
{
"code": null,
"e": 15414,
"s": 15324,
"text": "Basically having a better education and more capital gain leads to you making more money!"
},
{
"code": null,
"e": 15838,
"s": 15414,
"text": "Local Interpretation could be possibly be achieved in two ways. Firstly, one could possibly approximate the behavior of a complex predictive model in the vicinity of a single input using a simple interpretable auxiliary or surrogate model (e.g. Linear Regressor). Secondly, one could use the base estimator to understand the behavior of a single prediction using intuitive approximate functions based on inputs and outputs."
},
{
"code": null,
"e": 16562,
"s": 15838,
"text": "LIME is a novel algorithm designed by Riberio Marco, Singh Sameer, Guestrin Carlos to access the behavior of the any base estimator(model) using interpretable surrogate models (e.g. linear classifier/regressor). Such form of comprehensive evaluation helps in generating explanations which are locally faithful but may not align with the global behavior. Basically, LIME explanations are based on local surrogate models. These, surrogate models are interpretable models (like a linear model or decision tree) that are learned on the predictions of the original black box model. But instead of trying to fit a global surrogate model, LIME focuses on fitting local surrogate models to explain why single predictions were made."
},
{
"code": null,
"e": 16964,
"s": 16562,
"text": "The idea is very intuitive. To start with, just try and unlearn what you have done so far! Forget about the training data, forget about how your model works! Think that your model is a black box model with some magic happening inside, where you can input data points and get the models predicted outcomes. You can probe this magic black box as often as you want with inputs and get output predictions."
},
{
"code": null,
"e": 17601,
"s": 16964,
"text": "Now, you main objective is to understand why the machine learning model which you are treating as a magic black box, gave the outcome it produced. LIME tries to do this for you! It tests out what happens to you black box model’s predictions when you feed variations or perturbations of your dataset into the black box model. Typically, LIME generates a new dataset consisting of perturbed samples and the associated black box model’s predictions. On this dataset LIME then trains an interpretable model weighted by the proximity of the sampled instances to the instance of interest. Following is a standard high-level workflow for this."
},
{
"code": null,
"e": 17720,
"s": 17601,
"text": "Choose your instance of interest for which you want to have an explanation of the predictions of your black box model."
},
{
"code": null,
"e": 17797,
"s": 17720,
"text": "Perturb your dataset and get the black box predictions for these new points."
},
{
"code": null,
"e": 17868,
"s": 17797,
"text": "Weight the new samples by their proximity to the instance of interest."
},
{
"code": null,
"e": 17952,
"s": 17868,
"text": "Fit a weighted, interpretable (surrogate) model on the dataset with the variations."
},
{
"code": null,
"e": 18004,
"s": 17952,
"text": "Explain prediction by interpreting the local model."
},
{
"code": null,
"e": 18141,
"s": 18004,
"text": "We recommend you to read the LIME chapter in Christoph Molnar’s excellent book on Model Interpretation which talks about this in detail."
},
{
"code": null,
"e": 18978,
"s": 18141,
"text": "Skater can leverage LIME to explain model predictions. Typically, its LimeTabularExplainer class helps in explaining predictions on tabular (i.e. matrix) data. For numerical features, it perturbs them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, it perturbs by sampling according to the training distribution, and making a binary feature that is 1 when the value is the same as the instance being explained. The explain_instance() function generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance. We then learn locally weighted linear (surrogate) models on this neighborhood data to explain each of the classes in an interpretable way."
},
{
"code": null,
"e": 19303,
"s": 18978,
"text": "Since XGBoost has some issues with feature name ordering when building models with dataframes, we will build our same model with numpy arrays to make LIME work without additional hassles of feature re-ordering. Remember the model being built is the same ensemble model which we treat as our black box machine learning model."
},
{
"code": null,
"e": 19768,
"s": 19303,
"text": "XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=5, min_child_weight=1, missing=None, n_estimators=500, n_jobs=1, nthread=None, objective='binary:logistic', random_state=42, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=1)"
},
{
"code": null,
"e": 19943,
"s": 19768,
"text": "Skater gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as below $50K."
},
{
"code": null,
"e": 20118,
"s": 19943,
"text": "Skater gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as above $50K."
},
{
"code": null,
"e": 20406,
"s": 20118,
"text": "We have see various ways to interpret machine learning models with features, dependence plots and even LIME. But can we build an approximation or a surrogate model which is more interpretable from a really complex black box model like our XGBoost model having hundreds of decision trees?"
},
{
"code": null,
"e": 20642,
"s": 20406,
"text": "Here in, we introduce the novel idea of using TreeSurrogates as means for explaining a model's learned decision policies (for inductive learning tasks), which is inspired by the work of Mark W. Craven described as the TREPAN algorithm."
},
{
"code": null,
"e": 20749,
"s": 20642,
"text": "We recommend checking out the following excellent papers on the TREPAN algorithm to build surrogate trees."
},
{
"code": null,
"e": 20832,
"s": 20749,
"text": "Mark W. Craven(1996) EXTRACTING COMPREHENSIBLE MODELS FROM TRAINED NEURAL NETWORKS"
},
{
"code": null,
"e": 20941,
"s": 20832,
"text": "Mark W. Craven and Jude W. Shavlik(NIPS, 96). Extracting Thee-Structured Representations of Thained Networks"
},
{
"code": null,
"e": 21152,
"s": 20941,
"text": "Briefly, Trepan constructs a decision tree in a best-first manner. It maintains a queue of leaves which are expanded into subtrees as they are removed from the queue. With each node in the queue, Trepan stores,"
},
{
"code": null,
"e": 21187,
"s": 21152,
"text": "A subset of the training examples,"
},
{
"code": null,
"e": 21231,
"s": 21187,
"text": "Another set of instances (query instances),"
},
{
"code": null,
"e": 21253,
"s": 21231,
"text": "A set of constraints."
},
{
"code": null,
"e": 21998,
"s": 21253,
"text": "The stored subset of training examples consists simply of those examples that reach the node. The query instances are used, along with the training examples, to select the splitting test if the node is an internal node or to determine the class label if it is a leaf. The constraint set describes the conditions that instances must satisfy in order to reach the node; this information is used when drawing a set of query instances for a newly created node. The process of expanding a node in Trepan is much like it is in conventional decision tree algorithms: a splitting test is selected for the node, and a child is created for each outcome of the test. Each child is either made a leaf of the tree or put into the queue for future expansion."
},
{
"code": null,
"e": 22667,
"s": 21998,
"text": "For Skater’s implementation, for building explainable surrogate models, the base estimator(Oracle) could be any form of a supervised learning predictive model — our black box model. The explanations are approximated using Decision Trees(both for Classification/Regression) by learning decision boundaries similar to that learned by the Oracle (predictions from the base model are used for learning the Decision Tree representation). The implementation also generates a fidelity score to quantify tree based surrogate model’s approximation to the Oracle. Ideally, the score should be 0 for truthful explanation both globally and locally. Let’s check this out in action!"
},
{
"code": null,
"e": 22746,
"s": 22667,
"text": "NOTE: The implementation is currently experimental and might change in future."
},
{
"code": null,
"e": 22857,
"s": 22746,
"text": "We can use the Interpretation object we instantiated earlier to invoke a call to the TreeSurrogate capability."
},
{
"code": null,
"e": 22964,
"s": 22857,
"text": "We can now fit this surrogate model on our dataset to learn the decision boundaries of our base estimator."
},
{
"code": null,
"e": 23051,
"s": 22964,
"text": "Reports the fidelity value when compared to the base estimator (closer to 0 is better)"
},
{
"code": null,
"e": 23125,
"s": 23051,
"text": "Learner uses F1-score as the default metric of choice for classification."
},
{
"code": null,
"e": 23131,
"s": 23125,
"text": "0.009"
},
{
"code": null,
"e": 23237,
"s": 23131,
"text": "We do this since the feature names in the surrogate tree are not displayed (but are present in the model)"
},
{
"code": null,
"e": 23309,
"s": 23237,
"text": "We can now visualize our surrogate tree model using the following code."
},
{
"code": null,
"e": 23378,
"s": 23309,
"text": "Here are some interesting rules you can observe from the above tree."
},
{
"code": null,
"e": 23498,
"s": 23378,
"text": "If Relationship < 0.5 (means 0) and Education-num <= 9.5 and Capital Gain <= 4225 → 70% chance of person making <= $50K"
},
{
"code": null,
"e": 23619,
"s": 23498,
"text": "If Relationship < 0.5 (means 0) and Education-num <= 9.5 and Capital Gain >= 4225 → 94.5% chance of person making > $50K"
},
{
"code": null,
"e": 23749,
"s": 23619,
"text": "If Relationship < 0.5 (means 0) and Education-num >= 9.5 and Education-num is also >= 12.5 → 94.7% chance of person making > $50K"
},
{
"code": null,
"e": 23900,
"s": 23749,
"text": "Feel free to derive more interesting rules from this and also your own models! Let’s look at how our surrogate model performs on the test dataset now."
},
{
"code": null,
"e": 23973,
"s": 23900,
"text": "Let’s check the performance of our surrogate model now on the test data."
},
{
"code": null,
"e": 24143,
"s": 23973,
"text": "Just as expected, the model performance drops a fair bit but still we get an overall F1-score of 83% as compared to our boosted model’s score of 87% which is quite good!"
},
{
"code": null,
"e": 24578,
"s": 24143,
"text": "SHAP (SHapley Additive exPlanations) is a unified approach to explain the output of any machine learning model. SHAP connects game theory with local explanations, uniting several previous methods and representing the only possible consistent and locally accurate additive feature attribution method based on what they claim! (do check out the SHAP NIPS paper for details). We have also covered this in detail in Part 2 of this series."
},
{
"code": null,
"e": 24610,
"s": 24578,
"text": "SHAP can be installed from PyPI"
},
{
"code": null,
"e": 24627,
"s": 24610,
"text": "pip install shap"
},
{
"code": null,
"e": 24642,
"s": 24627,
"text": "or conda-forge"
},
{
"code": null,
"e": 24676,
"s": 24642,
"text": "conda install -c conda-forge shap"
},
{
"code": null,
"e": 25055,
"s": 24676,
"text": "The really awesome aspect about this framework is while SHAP values can explain the output of any machine learning model, for really complex ensemble models it can be slow. But they have developed a high-speed exact algorithm for tree ensemble methods (Tree SHAP arXiv paper). Fast C++ implementations are supported for XGBoost, LightGBM, CatBoost, and scikit-learn tree models!"
},
{
"code": null,
"e": 25769,
"s": 25055,
"text": "SHAP (SHapley Additive exPlanations) assigns each feature an importance value for a particular prediction. Its novel components include: the identification of a new class of additive feature importance measures, and theoretical results showing there is a unique solution in this class with a set of desirable properties. Typically, SHAP values try to explain the output of a model (function) as a sum of the effects of each feature being introduced into a conditional expectation. Importantly, for non-linear functions the order in which features are introduced matters. The SHAP values result from averaging over all possible orderings. Proofs from game theory show this is the only possible consistent approach."
},
{
"code": null,
"e": 26121,
"s": 25769,
"text": "An intuitive way to understand the Shapley value is the following: The feature values enter a room in random order. All feature values in the room participate in the game (= contribute to the prediction). The Shapley value φij is the average marginal contribution of feature value xij by joining whatever features already entered the room before, i.e."
},
{
"code": null,
"e": 26261,
"s": 26121,
"text": "The following figure from the KDD 18 paper, Consistent Individualized Feature Attribution for Tree Ensembles summarizes this in a nice way!"
},
{
"code": null,
"e": 26330,
"s": 26261,
"text": "Let’s now dive into SHAP and leverage it for interpreting our model!"
},
{
"code": null,
"e": 26586,
"s": 26330,
"text": "Here we use the Tree SHAP implementation integrated into XGBoost to explain the test dataset! Remember that there are a variety of explainer methods based on the type of models you are building. We estimate the SHAP values for a set of samples (test data)"
},
{
"code": null,
"e": 26613,
"s": 26586,
"text": "Expected Value: -1.3625857"
},
{
"code": null,
"e": 26970,
"s": 26613,
"text": "This returns a matrix of SHAP values (# samples, # features). Each row sums to the difference between the model output for that sample and the expected value of the model output (which is stored as expected_value attribute of the explainer). Typically this difference helps us in explaining why the model is inclined on predicting a specific class outcome."
},
{
"code": null,
"e": 27439,
"s": 26970,
"text": "SHAP gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as below $50K. The below explanation shows features each contributing to push the model output from the base value (the average model output over the training dataset we passed) to the actual model output. Features pushing the prediction higher are shown in red, those pushing the prediction lower are in blue."
},
{
"code": null,
"e": 27630,
"s": 27439,
"text": "Similarly, SHAP gives a nice reasoning below showing which features were the most influential in the model taking the correct decision of predicting the person’s income as greater than $50K."
},
{
"code": null,
"e": 27853,
"s": 27630,
"text": "One of the key advantages of SHAP is it can build beautiful interactive plots which can visualize and explain multiple predictions at once. Here we visualize model prediction decisions for the first 1000 test data samples."
},
{
"code": null,
"e": 28003,
"s": 27853,
"text": "The above visualization can be interacted with in multiple ways. The default visualization shows some interesting model prediction pattern decisions."
},
{
"code": null,
"e": 28154,
"s": 28003,
"text": "The first 100 test samples all probably earn more than $50K and they are married or\\and have a good capital gain or\\and have a higher education level!"
},
{
"code": null,
"e": 28299,
"s": 28154,
"text": "The next 170+ test samples all probably earn less than or equal to $50K and they are mostly un-married and\\or are very young in age or divorced!"
},
{
"code": null,
"e": 28656,
"s": 28299,
"text": "The next 310+ test samples have an inclination towards mostly earning more than $50K and they are of diverse profiles including married folks, people with different age and education levels and occupation. Most dominant features pushing the model towards making a prediction for higher income is the person being married i.e. relationship: husband or wife!"
},
{
"code": null,
"e": 28879,
"s": 28656,
"text": "The remaining 400+ test samples have an inclination towards mostly earning less than $50K and they are of diverse profiles however dominant patterns include relationship: either unmarried or divorced and very young in age!"
},
{
"code": null,
"e": 29030,
"s": 28879,
"text": "Definitely interesting how we can find out patterns which lead to the model making specific decisions and being able to provide explanations for them."
},
{
"code": null,
"e": 29147,
"s": 29030,
"text": "This basically takes the average of the SHAP value magnitudes across the dataset and plots it as a simple bar chart."
},
{
"code": null,
"e": 29627,
"s": 29147,
"text": "Besides a typical feature importance bar chart, SHAP also enables us to use a density scatter plot of SHAP values for each feature to identify how much impact each feature has on the model output for individuals in the validation dataset. Features are sorted by the sum of the SHAP value magnitudes across all samples. Note that when the scatter points don’t fit on a line they pile up to show density, and the color of each point represents the feature value of that individual."
},
{
"code": null,
"e": 29995,
"s": 29627,
"text": "It is interesting to note that the age and marital status feature has more total model impact than the capital gain feature, but for those samples where capital gain matters it has more impact than age or marital status. In other words, capital gain affects a few predictions by a large amount, while age or marital status affects all predictions by a smaller amount."
},
{
"code": null,
"e": 30552,
"s": 29995,
"text": "SHAP dependence plots show the effect of a single (or two) feature across the whole dataset. They plot a feature’s value vs. the SHAP value of that feature across many samples. SHAP dependence plots are similar to partial dependence plots, but account for the interaction effects present in the features, and are only defined in regions of the input space supported by data. The vertical dispersion of SHAP values at a single feature value is driven by interaction effects, and another feature can be chosen for coloring to highlight possible interactions."
},
{
"code": null,
"e": 30628,
"s": 30552,
"text": "You will also notice its similarity with Skater’s Partial Dependence Plots!"
},
{
"code": null,
"e": 30696,
"s": 30628,
"text": "Let’s take a look at how the Age feature affects model predictions."
},
{
"code": null,
"e": 30910,
"s": 30696,
"text": "Just like we observed before. the middle-aged people have a slightly higher shap value, pushing the model’s prediction decisions to say that these individuals make more money as compared to younger or older people"
},
{
"code": null,
"e": 30988,
"s": 30910,
"text": "Let’s take a look at how the Education-Num feature affects model predictions."
},
{
"code": null,
"e": 31175,
"s": 30988,
"text": "Higher education levels have higher shap values, pushing the model’s prediction decisions to say that these individuals make more money as compared to people with lower education levels."
},
{
"code": null,
"e": 31252,
"s": 31175,
"text": "Let’s take a look at how the Relationship feature affects model predictions."
},
{
"code": null,
"e": 31499,
"s": 31252,
"text": "Just like we observed during the model prediction explanations, married people (husband or wife) have a slightly higher shap value, pushing the model’s prediction decisions to say that these individuals make more money as compared to other folks!"
},
{
"code": null,
"e": 31576,
"s": 31499,
"text": "Let’s take a look at how the Capital Gain feature affects model predictions."
},
{
"code": null,
"e": 31992,
"s": 31576,
"text": "The vertical dispersion of SHAP values at a single feature value is driven by interaction effects, and another feature is chosen for coloring to highlight possible interactions. Here we are trying to see interactions between Age and Capital Gainand also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot."
},
{
"code": null,
"e": 32124,
"s": 31992,
"text": "Interesting to see higher the higher capital gain and the middle-aged folks (30–50) having the highest chance of making more money!"
},
{
"code": null,
"e": 32373,
"s": 32124,
"text": "Here we are trying to see interactions between Education-Num and Relationship and also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot."
},
{
"code": null,
"e": 32583,
"s": 32373,
"text": "This is interesting because both the features are similar in some context, we can see typically married people with relationship status of either husband or wife having the highest chance of making more money!"
},
{
"code": null,
"e": 32833,
"s": 32583,
"text": "Here we are trying to see interactions between Marital Status and Relationship and also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot."
},
{
"code": null,
"e": 32974,
"s": 32833,
"text": "Interesting to see higher the higher education level and the husband or wife (married) folks having the highest chance of making more money!"
},
{
"code": null,
"e": 33215,
"s": 32974,
"text": "Here we are trying to see interactions between Age and Hours per week and also their effect on the SHAP values which lead to the model predicting if the person will make more money or not, with the help of a two-way partial dependence plot."
},
{
"code": null,
"e": 33301,
"s": 33215,
"text": "Nothing extra-ordinary here, middle-aged people working the most make the most money!"
},
{
"code": null,
"e": 33944,
"s": 33301,
"text": "If you are reading this, I would like to really commend your efforts on going through this huge and comprehensive tutorial on machine learning model interpretation. This article should help you leverage the state-of-the-art tools and techniques which should help you in your journey on the road towards Explanable AI (XAI). Based on the concepts and techniques we learnt in Part 2, in this article, we actually implemented them all on a complex machine learning ensemble model trained on a real-world dataset. I encourage you to try out some of these frameworks with your own models and datasets and explore the world of model interpretation!"
},
{
"code": null,
"e": 34114,
"s": 33944,
"text": "In Part 4 of this series, we will be looking at a comprehensive guide to building interpreting models on unstructured data like text and maybe even deep learning models!"
},
{
"code": null,
"e": 34169,
"s": 34114,
"text": "Hands-on Model Interpretation on Unstructured Datasets"
},
{
"code": null,
"e": 34223,
"s": 34169,
"text": "Advanced Model Interpretation on Deep Learning Models"
},
{
"code": null,
"e": 34264,
"s": 34223,
"text": "Stay tuned for some interesting content!"
},
{
"code": null,
"e": 34614,
"s": 34264,
"text": "Note: There are a lot of rapid developments in this area including a lot of new tools and frameworks being released over time. In case you want me to cover any other popular frameworks, feel free to reach out to me. I’m definitely interested and will be starting by taking a look into H2O’s model interpretation capabilities some time in the future."
},
{
"code": null,
"e": 34715,
"s": 34614,
"text": "The code used in this article is available on my GitHub and also as an interactive Jupyter Notebook."
},
{
"code": null,
"e": 34968,
"s": 34715,
"text": "Check out ‘Part 1 — The Importance of Human Interpretable Machine Learning’ which covers the what and why of human interpretable machine learning and the need and importance of model interpretation along with its scope and criteria in case you haven’t!"
},
{
"code": null,
"e": 35169,
"s": 34968,
"text": "Also Part 2 — Model Interpretation Strategies’ which covers the how of human interpretable machine learning where we look at essential concepts pertaining to major strategies for model interpretation."
}
] |
Django - Upload files with FileSystemStorage - GeeksforGeeks | 21 Jan, 2022
Django ships with the FileSystemStorage class that helps to store files locally so that these files can be served as media in development. In this article, we will see how to implement a file upload system using FileSystemStorage API to store the files locally. Note:This method should only be used in development and not in production.
Step 1: We will start off by making a template form to upload files.Template
HTML
<form method = 'POST' class="col s12" enctype="multipart/form-data"> {% csrf_token %} {{new_form.as_p}} <!--Below is our main file upload input --> <input type = "file" name = 'document'> <p><button type = "submit" class = "waves-effect waves-light btn" style = "background-color: teal">Publish</button></p></form>
Here, note that the input(through which the user may input a file) has the name ‘document’.
Step 2: Now, we will write the view for the same in the `views.py` fileView First, import the FileSystemStorage class on the top of the file using
from django.core.files.storage import FileSystemStorage
Python3
if request.method == "POST": # if the post request has a file under the input name 'document', then save the file. request_file = request.FILES['document'] if 'document' in request.FILES else None if request_file: # save attached file # create a new instance of FileSystemStorage fs = FileSystemStorage() file = fs.save(request_file.name, request_file) # the fileurl variable now contains the url to the file. This can be used to serve the file when needed. fileurl = fs.url(file) return render(request, "template.html")
Here, the FileSystemStorage class’ constructor takes the parameter ‘location’ which is the path to the directory where you want to store the files. By default, it is the path in the variable ‘settings.MEDIA_ROOT’. It also takes the parameter ‘base_url’ which is the url you would want the media to correspond to. By default, it is set to the value of the variable ‘settings.MEDIA_URL’ (make sure you have those constants set in the settings.py file).The function FileSystemStorage.save takes in 3 arguments; name, content(the file itself) and max_length(default value = None). This function stores the file – ‘content’ under the name ‘name’. If a file with the same name exists, then it modifies the file name a little to generate a unique name.Read about more constructor parameters and methods of the FileSystemStorage class in the django documentation for the same
Step 3: Define MEDIA_ROOT and MEDIA_URL if not already defined. Settings Make sure you configure the MEDIA_ROOT and MEDIA_URL in settings.py.
Python3
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # media directory in the root directoryMEDIA_URL = '/media/'
Step 4: Finally, we add a route to MEDIA_URL. URLs In urls.py, import
from django.conf.urls.static import static
from django.conf import settings
and add the following at the end of the file
Python3
# only in developmentif settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
This will add a route to the MEDIA_URL and serve the file from MEDIA_ROOT when a user makes a GET request to MEDIA_URL/(file name). Once all this is done, the files uploaded should show up in the directory specified in the MEDIA_ROOT constant.
Output – The frontend should look something like this
As mentioned earlier, this method should only be used to serve media in development and not in production. You might want to use something like nginx in production.
kk9826225
Python Django
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24440,
"s": 24412,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 24778,
"s": 24440,
"text": "Django ships with the FileSystemStorage class that helps to store files locally so that these files can be served as media in development. In this article, we will see how to implement a file upload system using FileSystemStorage API to store the files locally. Note:This method should only be used in development and not in production. "
},
{
"code": null,
"e": 24856,
"s": 24778,
"text": "Step 1: We will start off by making a template form to upload files.Template "
},
{
"code": null,
"e": 24861,
"s": 24856,
"text": "HTML"
},
{
"code": "<form method = 'POST' class=\"col s12\" enctype=\"multipart/form-data\"> {% csrf_token %} {{new_form.as_p}} <!--Below is our main file upload input --> <input type = \"file\" name = 'document'> <p><button type = \"submit\" class = \"waves-effect waves-light btn\" style = \"background-color: teal\">Publish</button></p></form>",
"e": 25210,
"s": 24861,
"text": null
},
{
"code": null,
"e": 25304,
"s": 25210,
"text": "Here, note that the input(through which the user may input a file) has the name ‘document’. "
},
{
"code": null,
"e": 25452,
"s": 25304,
"text": "Step 2: Now, we will write the view for the same in the `views.py` fileView First, import the FileSystemStorage class on the top of the file using "
},
{
"code": null,
"e": 25508,
"s": 25452,
"text": "from django.core.files.storage import FileSystemStorage"
},
{
"code": null,
"e": 25516,
"s": 25508,
"text": "Python3"
},
{
"code": "if request.method == \"POST\": # if the post request has a file under the input name 'document', then save the file. request_file = request.FILES['document'] if 'document' in request.FILES else None if request_file: # save attached file # create a new instance of FileSystemStorage fs = FileSystemStorage() file = fs.save(request_file.name, request_file) # the fileurl variable now contains the url to the file. This can be used to serve the file when needed. fileurl = fs.url(file) return render(request, \"template.html\")",
"e": 26113,
"s": 25516,
"text": null
},
{
"code": null,
"e": 26983,
"s": 26113,
"text": "Here, the FileSystemStorage class’ constructor takes the parameter ‘location’ which is the path to the directory where you want to store the files. By default, it is the path in the variable ‘settings.MEDIA_ROOT’. It also takes the parameter ‘base_url’ which is the url you would want the media to correspond to. By default, it is set to the value of the variable ‘settings.MEDIA_URL’ (make sure you have those constants set in the settings.py file).The function FileSystemStorage.save takes in 3 arguments; name, content(the file itself) and max_length(default value = None). This function stores the file – ‘content’ under the name ‘name’. If a file with the same name exists, then it modifies the file name a little to generate a unique name.Read about more constructor parameters and methods of the FileSystemStorage class in the django documentation for the same "
},
{
"code": null,
"e": 27126,
"s": 26983,
"text": "Step 3: Define MEDIA_ROOT and MEDIA_URL if not already defined. Settings Make sure you configure the MEDIA_ROOT and MEDIA_URL in settings.py. "
},
{
"code": null,
"e": 27134,
"s": 27126,
"text": "Python3"
},
{
"code": "MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # media directory in the root directoryMEDIA_URL = '/media/'",
"e": 27240,
"s": 27134,
"text": null
},
{
"code": null,
"e": 27311,
"s": 27240,
"text": "Step 4: Finally, we add a route to MEDIA_URL. URLs In urls.py, import "
},
{
"code": null,
"e": 27387,
"s": 27311,
"text": "from django.conf.urls.static import static\nfrom django.conf import settings"
},
{
"code": null,
"e": 27433,
"s": 27387,
"text": "and add the following at the end of the file "
},
{
"code": null,
"e": 27441,
"s": 27433,
"text": "Python3"
},
{
"code": "# only in developmentif settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)",
"e": 27563,
"s": 27441,
"text": null
},
{
"code": null,
"e": 27807,
"s": 27563,
"text": "This will add a route to the MEDIA_URL and serve the file from MEDIA_ROOT when a user makes a GET request to MEDIA_URL/(file name). Once all this is done, the files uploaded should show up in the directory specified in the MEDIA_ROOT constant."
},
{
"code": null,
"e": 27862,
"s": 27807,
"text": "Output – The frontend should look something like this "
},
{
"code": null,
"e": 28027,
"s": 27862,
"text": "As mentioned earlier, this method should only be used to serve media in development and not in production. You might want to use something like nginx in production."
},
{
"code": null,
"e": 28037,
"s": 28027,
"text": "kk9826225"
},
{
"code": null,
"e": 28051,
"s": 28037,
"text": "Python Django"
},
{
"code": null,
"e": 28058,
"s": 28051,
"text": "Python"
},
{
"code": null,
"e": 28075,
"s": 28058,
"text": "Web Technologies"
},
{
"code": null,
"e": 28173,
"s": 28075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28191,
"s": 28173,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28226,
"s": 28191,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28248,
"s": 28226,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28280,
"s": 28248,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28310,
"s": 28280,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28352,
"s": 28310,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28385,
"s": 28352,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28428,
"s": 28385,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28490,
"s": 28428,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Order MySQL records randomly and display name in Ascending order | You can use subquery to order randomly and display name in asending order. The rand() is used for random, whereas ORDER BY is used to display name records in ascending order. The syntax is as follows −
select *from
(
select *from yourTableName order by rand() limit anyIntegerValue;
) anyVariableName
order by yourColumnName;
To understand the above concept, let us create a table. We have an ID as sell as Name, which we want in Ascending order. The query to create a table is as follows −
mysql> create table OrderByRandName
−> (
−> Id int,
−> Name varchar(100)
−> );
Query OK, 0 rows affected (0.96 sec)
Display all records from the table using insert command. The query is as follows −
mysql> insert into OrderByRandName values(100,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into OrderByRandName values(101,'Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into OrderByRandName values(102,'Johnson');
Query OK, 1 row affected (0.19 sec)
mysql> insert into OrderByRandName values(103,'David');
Query OK, 1 row affected (0.22 sec)
mysql> insert into OrderByRandName values(104,'Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into OrderByRandName values(105,'Taylor');
Query OK, 1 row affected (0.20 sec)
mysql> insert into OrderByRandName values(106,'Sam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into OrderByRandName values(107,'Robert');
Query OK, 1 row affected (0.22 sec)
mysql> insert into OrderByRandName values(108,'Michael');
Query OK, 1 row affected (0.16 sec)
mysql> insert into OrderByRandName values(109,'Mark');
Query OK, 1 row affected (0.17 sec)
Display all records using select statement. The query is as follows −
mysql> select *from OrderByRandName;
The following is the output −
+------+---------+
| Id | Name |
+------+---------+
| 100 | John |
| 101 | Bob |
| 102 | Johnson |
| 103 | David |
| 104 | Smith |
| 105 | Taylor |
| 106 | Sam |
| 107 | Robert |
| 108 | Michael |
| 109 | Mark |
+------+---------+
10 rows in set (0.00 sec)
Here is the query that order by rand() and display name in ascending order −
mysql> select *from
−> (
−> select *from OrderByRandName order by rand() limit 10
−> )tbl1
−> order by Name;
The following is the output −
+------+---------+
| Id | Name |
+------+---------+
| 101 | Bob |
| 103 | David |
| 100 | John |
| 102 | Johnson |
| 109 | Mark |
| 108 | Michael |
| 107 | Robert |
| 106 | Sam |
| 104 | Smith |
| 105 | Taylor |
+------+---------+
10 rows in set (0.39 sec) | [
{
"code": null,
"e": 1264,
"s": 1062,
"text": "You can use subquery to order randomly and display name in asending order. The rand() is used for random, whereas ORDER BY is used to display name records in ascending order. The syntax is as follows −"
},
{
"code": null,
"e": 1391,
"s": 1264,
"text": "select *from\n(\n select *from yourTableName order by rand() limit anyIntegerValue;\n) anyVariableName\norder by yourColumnName;"
},
{
"code": null,
"e": 1556,
"s": 1391,
"text": "To understand the above concept, let us create a table. We have an ID as sell as Name, which we want in Ascending order. The query to create a table is as follows −"
},
{
"code": null,
"e": 1684,
"s": 1556,
"text": "mysql> create table OrderByRandName\n −> (\n −> Id int,\n −> Name varchar(100)\n −> );\nQuery OK, 0 rows affected (0.96 sec)"
},
{
"code": null,
"e": 1767,
"s": 1684,
"text": "Display all records from the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2696,
"s": 1767,
"text": "mysql> insert into OrderByRandName values(100,'John');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into OrderByRandName values(101,'Bob');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into OrderByRandName values(102,'Johnson');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into OrderByRandName values(103,'David');\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into OrderByRandName values(104,'Smith');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into OrderByRandName values(105,'Taylor');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into OrderByRandName values(106,'Sam');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into OrderByRandName values(107,'Robert');\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into OrderByRandName values(108,'Michael');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into OrderByRandName values(109,'Mark');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 2766,
"s": 2696,
"text": "Display all records using select statement. The query is as follows −"
},
{
"code": null,
"e": 2803,
"s": 2766,
"text": "mysql> select *from OrderByRandName;"
},
{
"code": null,
"e": 2833,
"s": 2803,
"text": "The following is the output −"
},
{
"code": null,
"e": 3125,
"s": 2833,
"text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 100 | John |\n| 101 | Bob |\n| 102 | Johnson |\n| 103 | David |\n| 104 | Smith |\n| 105 | Taylor |\n| 106 | Sam |\n| 107 | Robert |\n| 108 | Michael |\n| 109 | Mark |\n+------+---------+\n10 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3202,
"s": 3125,
"text": "Here is the query that order by rand() and display name in ascending order −"
},
{
"code": null,
"e": 3323,
"s": 3202,
"text": "mysql> select *from\n −> (\n −> select *from OrderByRandName order by rand() limit 10\n −> )tbl1\n −> order by Name;"
},
{
"code": null,
"e": 3353,
"s": 3323,
"text": "The following is the output −"
},
{
"code": null,
"e": 3645,
"s": 3353,
"text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 101 | Bob |\n| 103 | David |\n| 100 | John |\n| 102 | Johnson |\n| 109 | Mark |\n| 108 | Michael |\n| 107 | Robert |\n| 106 | Sam |\n| 104 | Smith |\n| 105 | Taylor |\n+------+---------+\n10 rows in set (0.39 sec)"
}
] |
Difference between DBMS and DSMS - GeeksforGeeks | 13 Oct, 2020
1. DBMS :In DBMS the nature of data is non-volatile and random data access is performed using DBMS. It operates on one time queries and gives the exact output for that query. DBMS uses unlimited secondary storage to store the data and also here in DBMS the data update rate is very low. DBMS is used when there is little or no time requirement.
Application of DBMS :
University records
Supply Chain Management
HR Management
Telecommunication records
Railway Reservation System
The below query is an example of DBMS query which is a one time query and gives the exact answer.
SELECT Name, Role, City
FROM Employees
WHERE City = 'Bhubaneswar'
ORDER BY Name
The above query is a very simple query which shows Name, Role, City of the company employees whose city belongs to Bhubaneswar and the output/result will be ordered by name of the employees.
2. DSMS :In DSMS the nature of data is volatile data stream and sequential data access is performed using DSMS. It operates on continuous queries and gives the exact/approximate output for that query. DBMS uses limited main memory to store the data and also here in DSMS the data update rate is very high. DSMS is used when there is real time requirement.
Application of DSMS :
Sensor Network
Network Traffic Analysis
Financial Tickers
Online Auctions
Transaction Log Analysis
The below query is an example of DSMS query which is a continuous query and gives the exact/approximate answer.
SELECT Stream
Rowtime
MIN(Temp) Over W1 as Wmin_temp,
MAX(Temp) Over W1 as Wmax_temp,
AVG(Temp) Over W1 as Wavg_temp,
FROM Wheatherstream
Window W1 as (RANGE INTERVAL '2' SECOND PRECEDING);
The above query aggregates a sensor stream from a weather monitoring system. Then it aggregates the collected minimum, maximum and average temperature values. Window clause creates a window of 2 seconds duration (refers to delay, which can be changed) showing a stream of incrementally updated results with zero result latency.
Difference between DBMS and DSMS :
DBMS
Difference Between
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java | [
{
"code": null,
"e": 24304,
"s": 24276,
"text": "\n13 Oct, 2020"
},
{
"code": null,
"e": 24649,
"s": 24304,
"text": "1. DBMS :In DBMS the nature of data is non-volatile and random data access is performed using DBMS. It operates on one time queries and gives the exact output for that query. DBMS uses unlimited secondary storage to store the data and also here in DBMS the data update rate is very low. DBMS is used when there is little or no time requirement."
},
{
"code": null,
"e": 24671,
"s": 24649,
"text": "Application of DBMS :"
},
{
"code": null,
"e": 24690,
"s": 24671,
"text": "University records"
},
{
"code": null,
"e": 24714,
"s": 24690,
"text": "Supply Chain Management"
},
{
"code": null,
"e": 24728,
"s": 24714,
"text": "HR Management"
},
{
"code": null,
"e": 24754,
"s": 24728,
"text": "Telecommunication records"
},
{
"code": null,
"e": 24781,
"s": 24754,
"text": "Railway Reservation System"
},
{
"code": null,
"e": 24879,
"s": 24781,
"text": "The below query is an example of DBMS query which is a one time query and gives the exact answer."
},
{
"code": null,
"e": 24960,
"s": 24879,
"text": "SELECT Name, Role, City\nFROM Employees\nWHERE City = 'Bhubaneswar'\nORDER BY Name\n"
},
{
"code": null,
"e": 25151,
"s": 24960,
"text": "The above query is a very simple query which shows Name, Role, City of the company employees whose city belongs to Bhubaneswar and the output/result will be ordered by name of the employees."
},
{
"code": null,
"e": 25507,
"s": 25151,
"text": "2. DSMS :In DSMS the nature of data is volatile data stream and sequential data access is performed using DSMS. It operates on continuous queries and gives the exact/approximate output for that query. DBMS uses limited main memory to store the data and also here in DSMS the data update rate is very high. DSMS is used when there is real time requirement."
},
{
"code": null,
"e": 25529,
"s": 25507,
"text": "Application of DSMS :"
},
{
"code": null,
"e": 25544,
"s": 25529,
"text": "Sensor Network"
},
{
"code": null,
"e": 25569,
"s": 25544,
"text": "Network Traffic Analysis"
},
{
"code": null,
"e": 25587,
"s": 25569,
"text": "Financial Tickers"
},
{
"code": null,
"e": 25603,
"s": 25587,
"text": "Online Auctions"
},
{
"code": null,
"e": 25628,
"s": 25603,
"text": "Transaction Log Analysis"
},
{
"code": null,
"e": 25740,
"s": 25628,
"text": "The below query is an example of DSMS query which is a continuous query and gives the exact/approximate answer."
},
{
"code": null,
"e": 25931,
"s": 25740,
"text": "SELECT Stream\nRowtime\nMIN(Temp) Over W1 as Wmin_temp,\nMAX(Temp) Over W1 as Wmax_temp,\nAVG(Temp) Over W1 as Wavg_temp,\nFROM Wheatherstream\nWindow W1 as (RANGE INTERVAL '2' SECOND PRECEDING);\n"
},
{
"code": null,
"e": 26259,
"s": 25931,
"text": "The above query aggregates a sensor stream from a weather monitoring system. Then it aggregates the collected minimum, maximum and average temperature values. Window clause creates a window of 2 seconds duration (refers to delay, which can be changed) showing a stream of incrementally updated results with zero result latency."
},
{
"code": null,
"e": 26294,
"s": 26259,
"text": "Difference between DBMS and DSMS :"
},
{
"code": null,
"e": 26299,
"s": 26294,
"text": "DBMS"
},
{
"code": null,
"e": 26318,
"s": 26299,
"text": "Difference Between"
},
{
"code": null,
"e": 26323,
"s": 26318,
"text": "DBMS"
},
{
"code": null,
"e": 26421,
"s": 26323,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26462,
"s": 26421,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 26505,
"s": 26462,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 26537,
"s": 26505,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26564,
"s": 26537,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 26591,
"s": 26564,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 26622,
"s": 26591,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 26662,
"s": 26622,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 26694,
"s": 26662,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 26755,
"s": 26694,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Sort a K sorted Doubly Linked List | Set 2 (Using Shell Sort) - GeeksforGeeks | 12 Jan, 2022
Given a doubly-linked list containing N nodes, where each node is at most K away from its target position in the list, the task is to sort the given doubly linked list.
Examples:
Input: DLL: 3<->6<->2<->12<->56<->8, K = 2Output: 2<->3<->6<->8<->12<->56
Input: DLL: 3<->2<->1<->5<->4Output:1<->2<->3<->4<->5
Note: Approaches using Insertion sort and using Min Heap Data structure have been discussed here.
Approach: Shell sort, which is a variation of Insertion sort can be used to solve this problem as well, by initializing the gap with K instead of N, as the list is already K-sorted.
Below is an implementation of the above approach:
Java
C#
Javascript
// Java implementation to sort a k sorted doubly
import java.util.*;
class DoublyLinkedList {
static Node head;
static class Node {
int data;
Node next, prev;
Node(int d)
{
data = d;
next = prev = null;
}
}
// this method returns
// the ceiling value of gap/2
int nextGap(double gap)
{
if (gap < 2)
return 0;
return (int)Math.ceil(gap / 2);
}
// Sort a k sorted Doubly Linked List
// Time Complexity: O(n*log k)
// Space Complexity: O(1)
Node sortAKSortedDLL(Node head, int k)
{
if (head == null || head.next == null)
return head;
// for all gaps
for (int gap = k; gap > 0; gap = nextGap(gap)) {
Node i = head, j = head;
int count = gap;
while (count-- > 0)
j = j.next;
for (; j != null; i = i.next, j = j.next) {
// if data at jth node is less than
// data at ith node
if (i.data > j.data) {
// if i is head
// then replace head with j
if (i == head)
head = j;
// swap i & j pointers
Node iTemp = i;
i = j;
j = iTemp;
// i & j pointers are swapped because
// below code only swaps nodes by
// swapping their associated
// pointers(i.e. prev & next pointers)
// Now, swap both the
// nodes in linked list
Node iPrev = i.prev, iNext = i.next;
if (iPrev != null)
iPrev.next = j;
if (iNext != null)
iNext.prev = j;
i.prev = j.prev;
i.next = j.next;
if (j.prev != null)
j.prev.next = i;
if (j.next != null)
j.next.prev = i;
j.prev = iPrev;
j.next = iNext;
}
}
}
return head;
}
/* UTILITY FUNCTIONS */
// Function to insert a node
// at the beginning of the
// Doubly Linked List
void push(int new_data)
{
// allocate node
Node new_node = new Node(new_data);
// since we are adding at the beginning,
// prev is always NULL
new_node.prev = null;
// link the old list off the new node
new_node.next = head;
// change prev of head node to new node
if (head != null) {
head.prev = new_node;
}
// move the head to point
// to the new node
head = new_node;
}
// Function to print nodes
// in a given doubly linked list
// This function is same as
// printList() of singly linked list
void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
// Driver code
public static void main(String[] args)
{
DoublyLinkedList list = new DoublyLinkedList();
// 3<->6<->2<->12<->56<->8
list.push(8);
list.push(56);
list.push(12);
list.push(2);
list.push(6);
list.push(3);
int k = 2;
System.out.println("Original Doubly linked list:");
list.printList(head);
Node sortedDLL = list.sortAKSortedDLL(head, k);
System.out.println("");
System.out.println(
"Doubly Linked List after sorting:");
list.printList(sortedDLL);
}
}
// C# implementation to sort a k sorted doubly
using System;
public class DoublyList {
public static Node head;
public class Node {
public int data;
public Node next, prev;
public Node(int d)
{
data = d;
next = prev = null;
}
}
// this method returns
// the ceiling value of gap/2
int nextGap(double gap)
{
if (gap < 2)
return 0;
return (int)Math.Ceiling(gap / 2);
}
// Sort a k sorted Doubly Linked List
// Time Complexity: O(n*log k)
// Space Complexity: O(1)
Node sortAKSortedDLL(Node head, int k)
{
if (head == null || head.next == null)
return head;
// for all gaps
for (int gap = k; gap > 0; gap = nextGap(gap)) {
Node i = head, j = head;
int count = gap;
while (count-- > 0)
j = j.next;
for (; j != null; i = i.next, j = j.next) {
// if data at jth node is less than
// data at ith node
if (i.data > j.data) {
// if i is head
// then replace head with j
if (i == head)
head = j;
// swap i & j pointers
Node iTemp = i;
i = j;
j = iTemp;
// i & j pointers are swapped because
// below code only swaps nodes by
// swapping their associated
// pointers(i.e. prev & next pointers)
// Now, swap both the
// nodes in linked list
Node iPrev = i.prev, iNext = i.next;
if (iPrev != null)
iPrev.next = j;
if (iNext != null)
iNext.prev = j;
i.prev = j.prev;
i.next = j.next;
if (j.prev != null)
j.prev.next = i;
if (j.next != null)
j.next.prev = i;
j.prev = iPrev;
j.next = iNext;
}
}
}
return head;
}
/* UTILITY FUNCTIONS */
// Function to insert a node
// at the beginning of the
// Doubly Linked List
void Push(int new_data)
{
// allocate node
Node new_node = new Node(new_data);
// since we are adding at the beginning,
// prev is always NULL
new_node.prev = null;
// link the old list off the new node
new_node.next = head;
// change prev of head node to new node
if (head != null) {
head.prev = new_node;
}
// move the head to point
// to the new node
head = new_node;
}
// Function to print nodes
// in a given doubly linked list
// This function is same as
// printList() of singly linked list
void printList(Node node)
{
while (node != null) {
Console.Write(node.data + " ");
node = node.next;
}
}
// Driver code
public static void Main(String[] args)
{
DoublyList list = new DoublyList();
// 3<->6<->2<->12<->56<->8
list.Push(8);
list.Push(56);
list.Push(12);
list.Push(2);
list.Push(6);
list.Push(3);
int k = 2;
Console.WriteLine("Original Doubly linked list:");
list.printList(head);
Node sortedDLL = list.sortAKSortedDLL(head, k);
Console.WriteLine("");
Console.WriteLine(
"Doubly Linked List after sorting:");
list.printList(sortedDLL);
}
}
// This code is contributed by umadevi9616
<script>
// javascript implementation to sort a k sorted doubly
var head;
class Node {
constructor(val) {
this.data = val;
this.prev = null;
this.next = null;
}
}
// this method returns
// the ceiling value of gap/2
function nextGap(gap) {
if (gap < 2)
return 0;
return parseInt( Math.ceil(gap / 2));
}
// Sort a k sorted Doubly Linked List
// Time Complexity: O(n*log k)
// Space Complexity: O(1)
function sortAKSortedDLL(head , k) {
if (head == null || head.next == null)
return head;
// for all gaps
for (var gap = k; gap > 0; gap = nextGap(gap)) {
var i = head, j = head;
var count = gap;
while (count-- > 0)
j = j.next;
for (; j != null; i = i.next, j = j.next) {
// if data at jth node is less than
// data at ith node
if (i.data > j.data) {
// if i is head
// then replace head with j
if (i == head)
head = j;
// swap i & j pointers
var iTemp = i;
i = j;
j = iTemp;
// i & j pointers are swapped because
// below code only swaps nodes by
// swapping their associated
// pointers(i.e. prev & next pointers)
// Now, swap both the
// nodes in linked list
var iPrev = i.prev, iNext = i.next;
if (iPrev != null)
iPrev.next = j;
if (iNext != null)
iNext.prev = j;
i.prev = j.prev;
i.next = j.next;
if (j.prev != null)
j.prev.next = i;
if (j.next != null)
j.next.prev = i;
j.prev = iPrev;
j.next = iNext;
}
}
}
return head;
}
/* UTILITY FUNCTIONS */
// Function to insert a node
// at the beginning of the
// Doubly Linked List
function push(new_data) {
// allocate node
var new_node = new Node(new_data);
// since we are adding at the beginning,
// prev is always NULL
new_node.prev = null;
// link the old list off the new node
new_node.next = head;
// change prev of head node to new node
if (head != null) {
head.prev = new_node;
}
// move the head to point
// to the new node
head = new_node;
}
// Function to print nodes
// in a given doubly linked list
// This function is same as
// printList() of singly linked list
function printList(node) {
while (node != null) {
document.write(node.data + " ");
node = node.next;
}
}
// Driver code
// 3<->6<->2<->12<->56<->8
push(8);
push(56);
push(12);
push(2);
push(6);
push(3);
var k = 2;
document.write("Original Doubly linked list:<br/>");
printList(head);
var sortedDLL = sortAKSortedDLL(head, k);
document.write("<br/>");
document.write("Doubly Linked List after sorting:<br/>");
printList(sortedDLL);
// This code contributed by umadevi9616
</script>
Original Doubly linked list:
3 6 2 12 56 8
Doubly Linked List after sorting:
2 3 6 8 12 56
Time Complexity: O(N*log K) gap is initialized with k and reduced to the ceiling value of gap/2 after each iteration. Hence, log k gaps will be calculated, and for each gap, the list will be iterated.
Space Complexity: O(1)
umadevi9616
adnanirshad158
doubly linked list
Linked-List-Sorting
ShellSort
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Linked List vs Array
Detect loop in a linked list
Delete a Linked List node at a given position
Merge two sorted linked lists
Find the middle of a given linked list
Bubble Sort
Selection Sort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Merge two sorted arrays | [
{
"code": null,
"e": 24126,
"s": 24095,
"text": " \n12 Jan, 2022\n"
},
{
"code": null,
"e": 24296,
"s": 24126,
"text": "Given a doubly-linked list containing N nodes, where each node is at most K away from its target position in the list, the task is to sort the given doubly linked list. "
},
{
"code": null,
"e": 24306,
"s": 24296,
"text": "Examples:"
},
{
"code": null,
"e": 24380,
"s": 24306,
"text": "Input: DLL: 3<->6<->2<->12<->56<->8, K = 2Output: 2<->3<->6<->8<->12<->56"
},
{
"code": null,
"e": 24434,
"s": 24380,
"text": "Input: DLL: 3<->2<->1<->5<->4Output:1<->2<->3<->4<->5"
},
{
"code": null,
"e": 24532,
"s": 24434,
"text": "Note: Approaches using Insertion sort and using Min Heap Data structure have been discussed here."
},
{
"code": null,
"e": 24714,
"s": 24532,
"text": "Approach: Shell sort, which is a variation of Insertion sort can be used to solve this problem as well, by initializing the gap with K instead of N, as the list is already K-sorted."
},
{
"code": null,
"e": 24764,
"s": 24714,
"text": "Below is an implementation of the above approach:"
},
{
"code": null,
"e": 24769,
"s": 24764,
"text": "Java"
},
{
"code": null,
"e": 24772,
"s": 24769,
"text": "C#"
},
{
"code": null,
"e": 24783,
"s": 24772,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// Java implementation to sort a k sorted doubly\n \nimport java.util.*;\n \nclass DoublyLinkedList {\n static Node head;\n static class Node {\n int data;\n Node next, prev;\n Node(int d)\n {\n data = d;\n next = prev = null;\n }\n }\n \n // this method returns\n // the ceiling value of gap/2\n int nextGap(double gap)\n {\n if (gap < 2)\n return 0;\n return (int)Math.ceil(gap / 2);\n }\n \n // Sort a k sorted Doubly Linked List\n // Time Complexity: O(n*log k)\n // Space Complexity: O(1)\n Node sortAKSortedDLL(Node head, int k)\n {\n if (head == null || head.next == null)\n return head;\n \n // for all gaps\n for (int gap = k; gap > 0; gap = nextGap(gap)) {\n \n Node i = head, j = head;\n int count = gap;\n \n while (count-- > 0)\n j = j.next;\n \n for (; j != null; i = i.next, j = j.next) {\n \n // if data at jth node is less than\n // data at ith node\n if (i.data > j.data) {\n \n // if i is head\n // then replace head with j\n if (i == head)\n head = j;\n \n // swap i & j pointers\n Node iTemp = i;\n i = j;\n j = iTemp;\n \n // i & j pointers are swapped because\n // below code only swaps nodes by\n // swapping their associated\n // pointers(i.e. prev & next pointers)\n \n // Now, swap both the\n // nodes in linked list\n Node iPrev = i.prev, iNext = i.next;\n if (iPrev != null)\n iPrev.next = j;\n if (iNext != null)\n iNext.prev = j;\n i.prev = j.prev;\n i.next = j.next;\n if (j.prev != null)\n j.prev.next = i;\n if (j.next != null)\n j.next.prev = i;\n j.prev = iPrev;\n j.next = iNext;\n }\n }\n }\n return head;\n }\n \n /* UTILITY FUNCTIONS */\n // Function to insert a node\n // at the beginning of the\n // Doubly Linked List\n void push(int new_data)\n {\n // allocate node\n Node new_node = new Node(new_data);\n \n // since we are adding at the beginning,\n // prev is always NULL\n new_node.prev = null;\n \n // link the old list off the new node\n new_node.next = head;\n \n // change prev of head node to new node\n if (head != null) {\n head.prev = new_node;\n }\n \n // move the head to point\n // to the new node\n head = new_node;\n }\n \n // Function to print nodes\n // in a given doubly linked list\n \n // This function is same as\n // printList() of singly linked list\n void printList(Node node)\n {\n while (node != null) {\n System.out.print(node.data + \" \");\n node = node.next;\n }\n }\n \n // Driver code\n public static void main(String[] args)\n {\n DoublyLinkedList list = new DoublyLinkedList();\n \n // 3<->6<->2<->12<->56<->8\n list.push(8);\n list.push(56);\n list.push(12);\n list.push(2);\n list.push(6);\n list.push(3);\n \n int k = 2;\n \n System.out.println(\"Original Doubly linked list:\");\n list.printList(head);\n \n Node sortedDLL = list.sortAKSortedDLL(head, k);\n System.out.println(\"\");\n System.out.println(\n \"Doubly Linked List after sorting:\");\n list.printList(sortedDLL);\n }\n}\n\n\n\n\n\n",
"e": 28660,
"s": 24793,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# implementation to sort a k sorted doubly\nusing System;\n \npublic class DoublyList {\n public static Node head;\n public class Node {\n public int data;\n public Node next, prev;\n public Node(int d)\n {\n data = d;\n next = prev = null;\n }\n }\n \n // this method returns\n // the ceiling value of gap/2\n int nextGap(double gap)\n {\n if (gap < 2)\n return 0;\n return (int)Math.Ceiling(gap / 2);\n }\n \n // Sort a k sorted Doubly Linked List\n // Time Complexity: O(n*log k)\n // Space Complexity: O(1)\n Node sortAKSortedDLL(Node head, int k)\n {\n if (head == null || head.next == null)\n return head;\n \n // for all gaps\n for (int gap = k; gap > 0; gap = nextGap(gap)) {\n \n Node i = head, j = head;\n int count = gap;\n \n while (count-- > 0)\n j = j.next;\n \n for (; j != null; i = i.next, j = j.next) {\n \n // if data at jth node is less than\n // data at ith node\n if (i.data > j.data) {\n \n // if i is head\n // then replace head with j\n if (i == head)\n head = j;\n \n // swap i & j pointers\n Node iTemp = i;\n i = j;\n j = iTemp;\n \n // i & j pointers are swapped because\n // below code only swaps nodes by\n // swapping their associated\n // pointers(i.e. prev & next pointers)\n \n // Now, swap both the\n // nodes in linked list\n Node iPrev = i.prev, iNext = i.next;\n if (iPrev != null)\n iPrev.next = j;\n if (iNext != null)\n iNext.prev = j;\n i.prev = j.prev;\n i.next = j.next;\n if (j.prev != null)\n j.prev.next = i;\n if (j.next != null)\n j.next.prev = i;\n j.prev = iPrev;\n j.next = iNext;\n }\n }\n }\n return head;\n }\n \n /* UTILITY FUNCTIONS */\n // Function to insert a node\n // at the beginning of the\n // Doubly Linked List\n void Push(int new_data)\n {\n // allocate node\n Node new_node = new Node(new_data);\n \n // since we are adding at the beginning,\n // prev is always NULL\n new_node.prev = null;\n \n // link the old list off the new node\n new_node.next = head;\n \n // change prev of head node to new node\n if (head != null) {\n head.prev = new_node;\n }\n \n // move the head to point\n // to the new node\n head = new_node;\n }\n \n // Function to print nodes\n // in a given doubly linked list\n \n // This function is same as\n // printList() of singly linked list\n void printList(Node node)\n {\n while (node != null) {\n Console.Write(node.data + \" \");\n node = node.next;\n }\n }\n \n // Driver code\n public static void Main(String[] args)\n {\n DoublyList list = new DoublyList();\n \n // 3<->6<->2<->12<->56<->8\n list.Push(8);\n list.Push(56);\n list.Push(12);\n list.Push(2);\n list.Push(6);\n list.Push(3);\n \n int k = 2;\n \n Console.WriteLine(\"Original Doubly linked list:\");\n list.printList(head);\n \n Node sortedDLL = list.sortAKSortedDLL(head, k);\n Console.WriteLine(\"\");\n Console.WriteLine(\n \"Doubly Linked List after sorting:\");\n list.printList(sortedDLL);\n }\n}\n \n// This code is contributed by umadevi9616\n\n\n\n\n\n",
"e": 32586,
"s": 28670,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n// javascript implementation to sort a k sorted doubly\nvar head;\n \n class Node {\n constructor(val) {\n this.data = val;\n this.prev = null;\n this.next = null;\n }\n }\n \n // this method returns\n // the ceiling value of gap/2\n function nextGap(gap) {\n if (gap < 2)\n return 0;\n return parseInt( Math.ceil(gap / 2));\n }\n \n // Sort a k sorted Doubly Linked List\n // Time Complexity: O(n*log k)\n // Space Complexity: O(1)\n function sortAKSortedDLL(head , k) {\n if (head == null || head.next == null)\n return head;\n \n // for all gaps\n for (var gap = k; gap > 0; gap = nextGap(gap)) {\n \n var i = head, j = head;\n var count = gap;\n \n while (count-- > 0)\n j = j.next;\n \n for (; j != null; i = i.next, j = j.next) {\n \n // if data at jth node is less than\n // data at ith node\n if (i.data > j.data) {\n \n // if i is head\n // then replace head with j\n if (i == head)\n head = j;\n \n // swap i & j pointers\n var iTemp = i;\n i = j;\n j = iTemp;\n \n // i & j pointers are swapped because\n // below code only swaps nodes by\n // swapping their associated\n // pointers(i.e. prev & next pointers)\n \n // Now, swap both the\n // nodes in linked list\n var iPrev = i.prev, iNext = i.next;\n if (iPrev != null)\n iPrev.next = j;\n if (iNext != null)\n iNext.prev = j;\n i.prev = j.prev;\n i.next = j.next;\n if (j.prev != null)\n j.prev.next = i;\n if (j.next != null)\n j.next.prev = i;\n j.prev = iPrev;\n j.next = iNext;\n }\n }\n }\n return head;\n }\n \n /* UTILITY FUNCTIONS */\n // Function to insert a node\n // at the beginning of the\n // Doubly Linked List\n function push(new_data) {\n // allocate node\nvar new_node = new Node(new_data);\n \n // since we are adding at the beginning,\n // prev is always NULL\n new_node.prev = null;\n \n // link the old list off the new node\n new_node.next = head;\n \n // change prev of head node to new node\n if (head != null) {\n head.prev = new_node;\n }\n \n // move the head to point\n // to the new node\n head = new_node;\n }\n \n // Function to print nodes\n // in a given doubly linked list\n \n // This function is same as\n // printList() of singly linked list\n function printList(node) {\n while (node != null) {\n document.write(node.data + \" \");\n node = node.next;\n }\n }\n \n // Driver code\n \n \n // 3<->6<->2<->12<->56<->8\n push(8);\n push(56);\n push(12);\n push(2);\n push(6);\n push(3);\n \n var k = 2;\n \n document.write(\"Original Doubly linked list:<br/>\");\n printList(head);\n \nvar sortedDLL = sortAKSortedDLL(head, k);\n document.write(\"<br/>\");\n document.write(\"Doubly Linked List after sorting:<br/>\");\n printList(sortedDLL);\n// This code contributed by umadevi9616 \n</script>\n\n\n\n\n\n",
"e": 36231,
"s": 32596,
"text": null
},
{
"code": null,
"e": 36323,
"s": 36231,
"text": "Original Doubly linked list:\n3 6 2 12 56 8 \nDoubly Linked List after sorting:\n2 3 6 8 12 56"
},
{
"code": null,
"e": 36526,
"s": 36325,
"text": "Time Complexity: O(N*log K) gap is initialized with k and reduced to the ceiling value of gap/2 after each iteration. Hence, log k gaps will be calculated, and for each gap, the list will be iterated."
},
{
"code": null,
"e": 36549,
"s": 36526,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 36561,
"s": 36549,
"text": "umadevi9616"
},
{
"code": null,
"e": 36576,
"s": 36561,
"text": "adnanirshad158"
},
{
"code": null,
"e": 36597,
"s": 36576,
"text": "\ndoubly linked list\n"
},
{
"code": null,
"e": 36619,
"s": 36597,
"text": "\nLinked-List-Sorting\n"
},
{
"code": null,
"e": 36631,
"s": 36619,
"text": "\nShellSort\n"
},
{
"code": null,
"e": 36645,
"s": 36631,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 36655,
"s": 36645,
"text": "\nSorting\n"
},
{
"code": null,
"e": 36860,
"s": 36655,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 36881,
"s": 36860,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 36910,
"s": 36881,
"text": "Detect loop in a linked list"
},
{
"code": null,
"e": 36956,
"s": 36910,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 36986,
"s": 36956,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 37025,
"s": 36986,
"text": "Find the middle of a given linked list"
},
{
"code": null,
"e": 37037,
"s": 37025,
"text": "Bubble Sort"
},
{
"code": null,
"e": 37052,
"s": 37037,
"text": "Selection Sort"
},
{
"code": null,
"e": 37075,
"s": 37052,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 37119,
"s": 37075,
"text": "Time Complexities of all Sorting Algorithms"
}
] |
SQL - Alias Syntax | You can rename a table or a column temporarily by giving another name known as Alias. The use of table aliases is to rename a table in a specific SQL statement. The renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular SQL query.
The basic syntax of a table alias is as follows.
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
The basic syntax of a column alias is as follows.
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2 − ORDERS Table is as follows.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, the following code block shows the usage of a table alias.
SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT
FROM CUSTOMERS AS C, ORDERS AS O
WHERE C.ID = O.CUSTOMER_ID;
This would produce the following result.
+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Following is the usage of a column alias.
SQL> SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
This would produce the following result.
+-------------+---------------+
| CUSTOMER_ID | CUSTOMER_NAME |
+-------------+---------------+
| 1 | Ramesh |
| 2 | Khilan |
| 3 | kaushik |
| 4 | Chaitali |
| 5 | Hardik |
| 6 | Komal |
| 7 | Muffy |
+-------------+---------------+
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2807,
"s": 2453,
"text": "You can rename a table or a column temporarily by giving another name known as Alias. The use of table aliases is to rename a table in a specific SQL statement. The renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular SQL query."
},
{
"code": null,
"e": 2856,
"s": 2807,
"text": "The basic syntax of a table alias is as follows."
},
{
"code": null,
"e": 2934,
"s": 2856,
"text": "SELECT column1, column2....\nFROM table_name AS alias_name\nWHERE [condition];\n"
},
{
"code": null,
"e": 2984,
"s": 2934,
"text": "The basic syntax of a column alias is as follows."
},
{
"code": null,
"e": 3053,
"s": 2984,
"text": "SELECT column_name AS alias_name\nFROM table_name\nWHERE [condition];\n"
},
{
"code": null,
"e": 3088,
"s": 3053,
"text": "Consider the following two tables."
},
{
"code": null,
"e": 3129,
"s": 3088,
"text": "Table 1 − CUSTOMERS Table is as follows."
},
{
"code": null,
"e": 3646,
"s": 3129,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 3684,
"s": 3646,
"text": "Table 2 − ORDERS Table is as follows."
},
{
"code": null,
"e": 4108,
"s": 3684,
"text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+"
},
{
"code": null,
"e": 4172,
"s": 4108,
"text": "Now, the following code block shows the usage of a table alias."
},
{
"code": null,
"e": 4283,
"s": 4172,
"text": "SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT \n FROM CUSTOMERS AS C, ORDERS AS O\n WHERE C.ID = O.CUSTOMER_ID;"
},
{
"code": null,
"e": 4324,
"s": 4283,
"text": "This would produce the following result."
},
{
"code": null,
"e": 4589,
"s": 4324,
"text": "+----+----------+-----+--------+\n| ID | NAME | AGE | AMOUNT |\n+----+----------+-----+--------+\n| 3 | kaushik | 23 | 3000 |\n| 3 | kaushik | 23 | 1500 |\n| 2 | Khilan | 25 | 1560 |\n| 4 | Chaitali | 25 | 2060 |\n+----+----------+-----+--------+\n"
},
{
"code": null,
"e": 4631,
"s": 4589,
"text": "Following is the usage of a column alias."
},
{
"code": null,
"e": 4732,
"s": 4631,
"text": "SQL> SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME\n FROM CUSTOMERS\n WHERE SALARY IS NOT NULL;"
},
{
"code": null,
"e": 4773,
"s": 4732,
"text": "This would produce the following result."
},
{
"code": null,
"e": 5126,
"s": 4773,
"text": "+-------------+---------------+\n| CUSTOMER_ID | CUSTOMER_NAME |\n+-------------+---------------+\n| 1 | Ramesh |\n| 2 | Khilan |\n| 3 | kaushik |\n| 4 | Chaitali |\n| 5 | Hardik |\n| 6 | Komal |\n| 7 | Muffy |\n+-------------+---------------+\n"
},
{
"code": null,
"e": 5159,
"s": 5126,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5173,
"s": 5159,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5206,
"s": 5173,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5220,
"s": 5206,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5255,
"s": 5220,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5269,
"s": 5255,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5302,
"s": 5269,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5324,
"s": 5302,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5359,
"s": 5324,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5413,
"s": 5359,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 5446,
"s": 5413,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5474,
"s": 5446,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5481,
"s": 5474,
"text": " Print"
},
{
"code": null,
"e": 5492,
"s": 5481,
"text": " Add Notes"
}
] |
spaCy - Models and Languages | Let us learn about the languages supported by spaCy and its statistical models.
Currently, spaCy supports the following languages −
spaCy’s statistical models
As we know that spaCy’s models can be installed as Python packages, which means like any other module, they are a component of our application. These modules can be versioned and defined in requirement.txt file.
The installation of spaCy’s statistical models is explained below −
Using spaCy’s download command is one of the easiest ways to download a model because, it will automatically find the best-matching model compatible with our spaCy version.
You can use the download command in the following ways −
The following command will download best-matching version of specific model for your spaCy version −
python -m spacy download en_core_web_sm
The following command will download best-matching default model and will also create a shortcut link −
python -m spacy download en
The following command will download the exact model version and does not create any shortcut link −
python -m spacy download en_core_web_sm-2.2.0 --direct
We can also download and install a model directly via pip. For this, you need to use pip install with the URL or local path of the archive file. In case if you do not have the direct link of a model, go to model release, and copy from there.
For example,
The command for installing model using pip with external URL is as follows −
pip install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz
The command for installing model using pip with local file is as follows −
pip install /Users/you/en_core_web_sm-2.2.0.tar.gz
The above commands will install the particular model into your site-packages directory. Once done, we can use spacy.load() to load it via its package name.
You can also download the data manually and place in into a custom directory of your choice.
Use any of the following ways to download the data manually −
Download the model via your browser from the latest release.
Download the model via your browser from the latest release.
You can configure your own download script by using the URL (Uniform Resource Locator) of the archive file.
You can configure your own download script by using the URL (Uniform Resource Locator) of the archive file.
Once done with downloading, we can place the model package directory anywhere on our local file system. Now to use it with spaCy, we can create a shortcut link for the data directory.
Here, how to use models with spaCy is explained.
We can download all the spaCy models manually, as discussed above, and put them in our local directory. Now whenever the spaCy project needs any model, we can create a shortcut link so that spaCy can load the model from there. With this you will not end up with duplicate data.
For this purpose, spaCy provide us the link command which can be used as follows −
python -m spacy link [package name or path] [shortcut] [--force]
In the above command, the first argument is the package name or local path. If you have installed the model via pip, you can use the package name here. Or else, you have a local path to the model package.
The second argument is the internal name. This is the name you want to use for the model. The –-force flag in the above command will overwrite any existing links.
The examples are given below for both the cases.
Example
Given below is an example for setting up shortcut link to load installed package as “default_model” −
python -m spacy link en_core_web_md en_default
An example for setting up shortcut link to load local model as “my_default_model” is as follows −
python -m spacy link /Users/Leekha/model my_default_en
We can also import an installed model, which can call its load() method with no arguments as shown below −
import spaCy
import en_core_web_sm
nlp_example = en_core_web_sm.load()
my_doc = nlp_example("This is my first example.")
my_doc
Output
This is my first example.
You can also use your trained model. For this, you need to save the state of your trained model using Language.to_disk() method. For more convenience in deploying, you can also wrap it as a Python package.
Generally, the naming convention of [lang_[name]] is one such convention that spaCy expected all its model packages to be followed.
The name of spaCy’s model can be further divided into following three components −
Type − It reflects the capabilities of model. For example, core is used for general-purpose model with vocabulary, syntax, entities. Similarly, depent is used for only vocab, syntax, and entities.
Type − It reflects the capabilities of model. For example, core is used for general-purpose model with vocabulary, syntax, entities. Similarly, depent is used for only vocab, syntax, and entities.
Genre − It shows the type of text on which the model is trained. For example, web or news.
Genre − It shows the type of text on which the model is trained. For example, web or news.
Size − As name implies, it is the model size indicator. For example, sm (for small), md (For medium), or lg (for large).
Size − As name implies, it is the model size indicator. For example, sm (for small), md (For medium), or lg (for large).
The model versioning reflects the following −
Compatibility with spaCy.
Compatibility with spaCy.
Major and minor model version.
Major and minor model version.
For example, a model version r.s.t translates to the following −
r − spaCy major version. For example, 1 for spaCy v1.x.
r − spaCy major version. For example, 1 for spaCy v1.x.
s − Model major version. It restricts the users to load different major versions by the same code.
s − Model major version. It restricts the users to load different major versions by the same code.
t − Model minor version. It shows the same model structure but, different parameter values. For example, trained on different data for different number of iterations.
t − Model minor version. It shows the same model structure but, different parameter values. For example, trained on different data for different number of iterations.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2152,
"s": 2072,
"text": "Let us learn about the languages supported by spaCy and its statistical models."
},
{
"code": null,
"e": 2204,
"s": 2152,
"text": "Currently, spaCy supports the following languages −"
},
{
"code": null,
"e": 2231,
"s": 2204,
"text": "spaCy’s statistical models"
},
{
"code": null,
"e": 2443,
"s": 2231,
"text": "As we know that spaCy’s models can be installed as Python packages, which means like any other module, they are a component of our application. These modules can be versioned and defined in requirement.txt file."
},
{
"code": null,
"e": 2511,
"s": 2443,
"text": "The installation of spaCy’s statistical models is explained below −"
},
{
"code": null,
"e": 2684,
"s": 2511,
"text": "Using spaCy’s download command is one of the easiest ways to download a model because, it will automatically find the best-matching model compatible with our spaCy version."
},
{
"code": null,
"e": 2741,
"s": 2684,
"text": "You can use the download command in the following ways −"
},
{
"code": null,
"e": 2842,
"s": 2741,
"text": "The following command will download best-matching version of specific model for your spaCy version −"
},
{
"code": null,
"e": 2883,
"s": 2842,
"text": "python -m spacy download en_core_web_sm\n"
},
{
"code": null,
"e": 2986,
"s": 2883,
"text": "The following command will download best-matching default model and will also create a shortcut link −"
},
{
"code": null,
"e": 3015,
"s": 2986,
"text": "python -m spacy download en\n"
},
{
"code": null,
"e": 3115,
"s": 3015,
"text": "The following command will download the exact model version and does not create any shortcut link −"
},
{
"code": null,
"e": 3171,
"s": 3115,
"text": "python -m spacy download en_core_web_sm-2.2.0 --direct\n"
},
{
"code": null,
"e": 3413,
"s": 3171,
"text": "We can also download and install a model directly via pip. For this, you need to use pip install with the URL or local path of the archive file. In case if you do not have the direct link of a model, go to model release, and copy from there."
},
{
"code": null,
"e": 3426,
"s": 3413,
"text": "For example,"
},
{
"code": null,
"e": 3503,
"s": 3426,
"text": "The command for installing model using pip with external URL is as follows −"
},
{
"code": null,
"e": 3625,
"s": 3503,
"text": "pip install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz\n"
},
{
"code": null,
"e": 3700,
"s": 3625,
"text": "The command for installing model using pip with local file is as follows −"
},
{
"code": null,
"e": 3752,
"s": 3700,
"text": "pip install /Users/you/en_core_web_sm-2.2.0.tar.gz\n"
},
{
"code": null,
"e": 3908,
"s": 3752,
"text": "The above commands will install the particular model into your site-packages directory. Once done, we can use spacy.load() to load it via its package name."
},
{
"code": null,
"e": 4001,
"s": 3908,
"text": "You can also download the data manually and place in into a custom directory of your choice."
},
{
"code": null,
"e": 4063,
"s": 4001,
"text": "Use any of the following ways to download the data manually −"
},
{
"code": null,
"e": 4124,
"s": 4063,
"text": "Download the model via your browser from the latest release."
},
{
"code": null,
"e": 4185,
"s": 4124,
"text": "Download the model via your browser from the latest release."
},
{
"code": null,
"e": 4293,
"s": 4185,
"text": "You can configure your own download script by using the URL (Uniform Resource Locator) of the archive file."
},
{
"code": null,
"e": 4401,
"s": 4293,
"text": "You can configure your own download script by using the URL (Uniform Resource Locator) of the archive file."
},
{
"code": null,
"e": 4585,
"s": 4401,
"text": "Once done with downloading, we can place the model package directory anywhere on our local file system. Now to use it with spaCy, we can create a shortcut link for the data directory."
},
{
"code": null,
"e": 4634,
"s": 4585,
"text": "Here, how to use models with spaCy is explained."
},
{
"code": null,
"e": 4912,
"s": 4634,
"text": "We can download all the spaCy models manually, as discussed above, and put them in our local directory. Now whenever the spaCy project needs any model, we can create a shortcut link so that spaCy can load the model from there. With this you will not end up with duplicate data."
},
{
"code": null,
"e": 4995,
"s": 4912,
"text": "For this purpose, spaCy provide us the link command which can be used as follows −"
},
{
"code": null,
"e": 5061,
"s": 4995,
"text": "python -m spacy link [package name or path] [shortcut] [--force]\n"
},
{
"code": null,
"e": 5266,
"s": 5061,
"text": "In the above command, the first argument is the package name or local path. If you have installed the model via pip, you can use the package name here. Or else, you have a local path to the model package."
},
{
"code": null,
"e": 5429,
"s": 5266,
"text": "The second argument is the internal name. This is the name you want to use for the model. The –-force flag in the above command will overwrite any existing links."
},
{
"code": null,
"e": 5478,
"s": 5429,
"text": "The examples are given below for both the cases."
},
{
"code": null,
"e": 5486,
"s": 5478,
"text": "Example"
},
{
"code": null,
"e": 5588,
"s": 5486,
"text": "Given below is an example for setting up shortcut link to load installed package as “default_model” −"
},
{
"code": null,
"e": 5636,
"s": 5588,
"text": "python -m spacy link en_core_web_md en_default\n"
},
{
"code": null,
"e": 5734,
"s": 5636,
"text": "An example for setting up shortcut link to load local model as “my_default_model” is as follows −"
},
{
"code": null,
"e": 5790,
"s": 5734,
"text": "python -m spacy link /Users/Leekha/model my_default_en\n"
},
{
"code": null,
"e": 5897,
"s": 5790,
"text": "We can also import an installed model, which can call its load() method with no arguments as shown below −"
},
{
"code": null,
"e": 6025,
"s": 5897,
"text": "import spaCy\nimport en_core_web_sm\nnlp_example = en_core_web_sm.load()\nmy_doc = nlp_example(\"This is my first example.\")\nmy_doc"
},
{
"code": null,
"e": 6032,
"s": 6025,
"text": "Output"
},
{
"code": null,
"e": 6059,
"s": 6032,
"text": "This is my first example.\n"
},
{
"code": null,
"e": 6265,
"s": 6059,
"text": "You can also use your trained model. For this, you need to save the state of your trained model using Language.to_disk() method. For more convenience in deploying, you can also wrap it as a Python package."
},
{
"code": null,
"e": 6397,
"s": 6265,
"text": "Generally, the naming convention of [lang_[name]] is one such convention that spaCy expected all its model packages to be followed."
},
{
"code": null,
"e": 6480,
"s": 6397,
"text": "The name of spaCy’s model can be further divided into following three components −"
},
{
"code": null,
"e": 6677,
"s": 6480,
"text": "Type − It reflects the capabilities of model. For example, core is used for general-purpose model with vocabulary, syntax, entities. Similarly, depent is used for only vocab, syntax, and entities."
},
{
"code": null,
"e": 6874,
"s": 6677,
"text": "Type − It reflects the capabilities of model. For example, core is used for general-purpose model with vocabulary, syntax, entities. Similarly, depent is used for only vocab, syntax, and entities."
},
{
"code": null,
"e": 6965,
"s": 6874,
"text": "Genre − It shows the type of text on which the model is trained. For example, web or news."
},
{
"code": null,
"e": 7056,
"s": 6965,
"text": "Genre − It shows the type of text on which the model is trained. For example, web or news."
},
{
"code": null,
"e": 7177,
"s": 7056,
"text": "Size − As name implies, it is the model size indicator. For example, sm (for small), md (For medium), or lg (for large)."
},
{
"code": null,
"e": 7298,
"s": 7177,
"text": "Size − As name implies, it is the model size indicator. For example, sm (for small), md (For medium), or lg (for large)."
},
{
"code": null,
"e": 7344,
"s": 7298,
"text": "The model versioning reflects the following −"
},
{
"code": null,
"e": 7370,
"s": 7344,
"text": "Compatibility with spaCy."
},
{
"code": null,
"e": 7396,
"s": 7370,
"text": "Compatibility with spaCy."
},
{
"code": null,
"e": 7427,
"s": 7396,
"text": "Major and minor model version."
},
{
"code": null,
"e": 7458,
"s": 7427,
"text": "Major and minor model version."
},
{
"code": null,
"e": 7523,
"s": 7458,
"text": "For example, a model version r.s.t translates to the following −"
},
{
"code": null,
"e": 7579,
"s": 7523,
"text": "r − spaCy major version. For example, 1 for spaCy v1.x."
},
{
"code": null,
"e": 7635,
"s": 7579,
"text": "r − spaCy major version. For example, 1 for spaCy v1.x."
},
{
"code": null,
"e": 7734,
"s": 7635,
"text": "s − Model major version. It restricts the users to load different major versions by the same code."
},
{
"code": null,
"e": 7833,
"s": 7734,
"text": "s − Model major version. It restricts the users to load different major versions by the same code."
},
{
"code": null,
"e": 8000,
"s": 7833,
"text": "t − Model minor version. It shows the same model structure but, different parameter values. For example, trained on different data for different number of iterations."
},
{
"code": null,
"e": 8167,
"s": 8000,
"text": "t − Model minor version. It shows the same model structure but, different parameter values. For example, trained on different data for different number of iterations."
},
{
"code": null,
"e": 8174,
"s": 8167,
"text": " Print"
},
{
"code": null,
"e": 8185,
"s": 8174,
"text": " Add Notes"
}
] |
MySQL Tryit Editor v1.0 | SELECT * FROM Customers;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 25,
"s": 0,
"text": "SELECT * FROM Customers;"
},
{
"code": null,
"e": 27,
"s": 25,
"text": ""
},
{
"code": null,
"e": 99,
"s": 36,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 159,
"s": 99,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 227,
"s": 159,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 265,
"s": 227,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 350,
"s": 265,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 524,
"s": 350,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 575,
"s": 524,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 643,
"s": 575,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 814,
"s": 643,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 914,
"s": 814,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 964,
"s": 914,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
Swap two Strings without using temp variable in C# | To swap two strings without using a temp variable, you can try the following code and logic.
Append the second string with the first.
str1 = str1 + str2;
Set the str1 in str2.
str2 = str1.Substring(0, str1.Length - str2.Length);
Now, the final step is to set str2 in str1 −
str1 = str1.Substring(str2.Length);
using System;
class Demo {
public static void Main(String[] args) {
String str1 = "Brad";
String str2 = "Pitt";
Console.WriteLine("Strings before swap");
Console.WriteLine(str1);
Console.WriteLine(str2);
str1 = str1 + str2;
str2 = str1.Substring(0, str1.Length - str2.Length);
str1 = str1.Substring(str2.Length);
Console.WriteLine("Strings after swap");
Console.WriteLine(str1);
Console.WriteLine(str2);
}
} | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To swap two strings without using a temp variable, you can try the following code and logic."
},
{
"code": null,
"e": 1196,
"s": 1155,
"text": "Append the second string with the first."
},
{
"code": null,
"e": 1216,
"s": 1196,
"text": "str1 = str1 + str2;"
},
{
"code": null,
"e": 1238,
"s": 1216,
"text": "Set the str1 in str2."
},
{
"code": null,
"e": 1291,
"s": 1238,
"text": "str2 = str1.Substring(0, str1.Length - str2.Length);"
},
{
"code": null,
"e": 1336,
"s": 1291,
"text": "Now, the final step is to set str2 in str1 −"
},
{
"code": null,
"e": 1372,
"s": 1336,
"text": "str1 = str1.Substring(str2.Length);"
},
{
"code": null,
"e": 1858,
"s": 1372,
"text": "using System;\n\nclass Demo {\n\n public static void Main(String[] args) {\n String str1 = \"Brad\";\n String str2 = \"Pitt\";\n\n Console.WriteLine(\"Strings before swap\");\n Console.WriteLine(str1);\n Console.WriteLine(str2);\n\n str1 = str1 + str2;\n\n str2 = str1.Substring(0, str1.Length - str2.Length);\n str1 = str1.Substring(str2.Length);\n\n Console.WriteLine(\"Strings after swap\");\n Console.WriteLine(str1);\n Console.WriteLine(str2);\n }\n}"
}
] |
Express.js – app.delete() Method | The app.delete() method routes all the HTTP DELETE requests to the specified path with the specified callback functions.
app.delete(path, callback, [callback])
path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression, or an array of all these.
callback − These are the middleware functions or a series of middleware functions that act like a middleware except that these callbacks can invoke next (route).
Create a file "appDelete.js" and copy the following code snippet. After creating the file, use the command "node appDelete.js" to run this code.
// app.delete() Method Demo Example
// Importing the express module
const express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Creating a DELETE request
app.delete('/api', (req, res) => {
console.log("DELETE Request Called for /api endpoint")
res.send("DELETE Request Called")
})
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Hit the following Endpoint with a DELETE request
http://localhost:3000/api
C:\home\node>> node appDelete.js
Server listening on PORT 3000
DELETE Request Called for /api endpoint
Let’s take a look at one more example.
// app.delete() Method Demo Example
// Importing the express module
const express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Creating a DELETE request
app.delete('/api', (req, res) => {
console.log("Method called is -- ", req.method)
res.end()
})
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Hit the following Endpoint with a DELETE request
http://localhost:3000/api
C:\home\node>> node appDelete.js
Server listening on PORT 3000
Method called is -- DELETE | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "The app.delete() method routes all the HTTP DELETE requests to the specified path with the specified callback functions."
},
{
"code": null,
"e": 1222,
"s": 1183,
"text": "app.delete(path, callback, [callback])"
},
{
"code": null,
"e": 1378,
"s": 1222,
"text": "path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression, or an array of all these."
},
{
"code": null,
"e": 1540,
"s": 1378,
"text": "callback − These are the middleware functions or a series of middleware functions that act like a middleware except that these callbacks can invoke next (route)."
},
{
"code": null,
"e": 1685,
"s": 1540,
"text": "Create a file \"appDelete.js\" and copy the following code snippet. After creating the file, use the command \"node appDelete.js\" to run this code."
},
{
"code": null,
"e": 2259,
"s": 1685,
"text": "// app.delete() Method Demo Example\n\n// Importing the express module\nconst express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n// Initializing the router from express\nvar router = express.Router();\nvar PORT = 3000;\n\n// Creating a DELETE request\napp.delete('/api', (req, res) => {\n console.log(\"DELETE Request Called for /api endpoint\")\n res.send(\"DELETE Request Called\")\n})\n\n// App listening on the below port\napp.listen(PORT, function(err){\n if (err) console.log(err);\n console.log(\"Server listening on PORT\", PORT);\n});"
},
{
"code": null,
"e": 2308,
"s": 2259,
"text": "Hit the following Endpoint with a DELETE request"
},
{
"code": null,
"e": 2336,
"s": 2308,
"text": " http://localhost:3000/api "
},
{
"code": null,
"e": 2439,
"s": 2336,
"text": "C:\\home\\node>> node appDelete.js\nServer listening on PORT 3000\nDELETE Request Called for /api endpoint"
},
{
"code": null,
"e": 2478,
"s": 2439,
"text": "Let’s take a look at one more example."
},
{
"code": null,
"e": 3021,
"s": 2478,
"text": "// app.delete() Method Demo Example\n\n// Importing the express module\nconst express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n// Initializing the router from express\nvar router = express.Router();\nvar PORT = 3000;\n\n// Creating a DELETE request\napp.delete('/api', (req, res) => {\n console.log(\"Method called is -- \", req.method)\n res.end()\n})\n\n// App listening on the below port\napp.listen(PORT, function(err){\n if (err) console.log(err);\n console.log(\"Server listening on PORT\", PORT);\n});"
},
{
"code": null,
"e": 3070,
"s": 3021,
"text": "Hit the following Endpoint with a DELETE request"
},
{
"code": null,
"e": 3096,
"s": 3070,
"text": "http://localhost:3000/api"
},
{
"code": null,
"e": 3186,
"s": 3096,
"text": "C:\\home\\node>> node appDelete.js\nServer listening on PORT 3000\nMethod called is -- DELETE"
}
] |
Video analytics at the edge. Use Raspberry PI and Intel NCS to... | by Aby Varghese | Towards Data Science | I have recently installed a CCTV system at my home. It consisted of 4 IP cameras. I wanted them to be a bit more smarter. Instead of looking at the CCTV footage always, it would be good to get a notification if there is human detected by any of the cameras. This is a really cool stuff. I thought it would be really good if I get an alarm in my Telegram if any of the camera detect a motion. Though I started it for fun, I had a great learning. Fundamentally it enables video analytics at the edge without needing a cloud. I am here to share my learning and eager to learn from you if there are ways to optimize.
I have 4 different IP cameras that stream 720P videos at 25FPS. I have a raspberry pi sitting idle and have got an Intel Movidius neural compute stick (ie first generation of NCS ). I wanted the Raspberry PI and NCS to perform the human detection and send me the notification in telegram when the camera detects a person. There were few things that I consider very important during the build, which are
1. I should be able to run the application almost 24/7 , that means the code should be efficient. The CPU utilization must be as minimum as possible so that the PI’s temperature is under control.
2. I should get the notification almost instantaneously. The highest priority was that the human detection should complete as soon as it happens.
3. The notification should contain an image so that I can understand the context of the alert (who was the person).
Let me tell you in advance, the item 1, and 2 were much harder than I thought.
I thought it is an easy task assuming Raspberry pi can get the video frame from each of the camera and NCS can perform the human detection. However, it was not so easy.
As usual, I started with plain OpenCV code to read the video RTSP stream a single camera and see how it works.
cap = cv2.VideoCapture(“RTSP URL of the IP Camera”) while(True): ret, frame = cap.read() cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release()cv2.destroyAllWindows()
However few things were not working as I expected. First and foremost, there were huge delay in getting the frame in real time. Ie even if there are no processing (human detection) there was a delay of around 5 to 10 seconds and in some cases, it went to 40 seconds within couple of minutes of running the application. The CPU utilization reached 100% immediately. This is the point where I realized this is much complex than I thought. So, I had to go back to the drawing board to see what would be the best way to solve this problem.
I observed that this solution does not require to process each and every frame from the camera during my analysis. We absolutely don’t need to analyze 25 frames that are generated in a second. This is one of the primary principles that I used in my design and I came up the following design. What parameter will help us to define the number of frames that the system can process will be discussed later.
As you may notice, the idea is to capture N number of frames from each of the camera in every X seconds. This was not the only reason which made the system work efficiently. The solution made use of the hardware acceleration available in Raspberry pi so that the CPU utilization is very minimal. This will be detailed when I describe about GStreamer. The reason why the number of frames and the duration are variable is that it is purely based on the processing power of the hardware that is used for processing the frames. As per my knowledge, the first version of Intel NCS can perform less number of inferences. As you can imagine, the diagram clearly shows the bottle neck in the processing engine since it has to process all the frames. Since my plan to make use of an existing Intel NCS, I had to adjust these parameters according to the capabilities of the NCS.
As a starting point, I decided to capture one frame in every one second from each of the camera. This seems to be reasonable to me. Since it is not practically possible for a person to go past the camera viewing area in less than a second. However there is a possibility that the processing engine might fail to detect the object, but that is a separate topic which we will look later.
I realized that it is difficult to specify the frame number(s) / second that I want to capture when I am using OpenCV. So explored and found out that there are possibly two approaches to solve this problem . One is GStreamer and another is FFMPG. So I decided to explore the first option GStreamer further.
I found GStreamer is extremely powerful but complex due to the lack of documentation / examples. So I started exploring few tutorials in youtube and I found them very useful. I have mentioned the links that helped me to study about GStreamer in the Reference section. I am sure it will help you too.
The source code for this experiment can be found here :
github.com
The first step for me was to install GStreamer in Raspberry PI. This was fairly straight forward.
sudo apt-get install gstreamer1.0-tools
The next step was to install Intel OpenVino toolkit for raspberry PI. This was necessary since the processing engine was Intel NCS. I had to install a version of OpenVINO that is supporting intel NCS since the latest versions of OpenVINO only support the Intel NCS 2. Please follow the link below link and install OpenVINO based on the NCS that you have.
docs.openvinotoolkit.org
Other libraries include:
pip install telepotpip install viztracersudo apt-get install pkg-config libcairo2-dev gcc python3-dev libgirepository1.0-devsudo apt-get install python3-gipip install gobject PyGObject
The next step is to create the GStreamer pipeline. As I mentioned earlier, it is very powerful tool. Gstreamer is configured by the use of pipelines, which are a series of commands specifying where to get video from, how to process and encode it, and then where to send it out.
Lets have a look at the pipeline that I have created.
pipelinestring = "rtspsrc location={0} name=m_rtspsrc ! rtph264depay ! h264parse ! v4l2h264dec capture-io-mode=4 ! video/x-raw ! v4l2convert output-io-mode=5 capture-io-mode=4 ! video/x-raw, format=(string)BGR, width=(int)640, height=(int)480 ! videorate ! video/x-raw,framerate=1/1 ! appsink name=m_appsink sync=false"
Lets see the purpose of each element.
rtspsrc location={0} — The location is the RTSP url of the camera stream.
rtph264depay — Extracts H264 video from RTP packets.
v4l2h264dec- This is an interesting one . This tells the Raspberry PI to decode the H264 using the GPU. Remember there is an alternative which uses the CPU to decode. It is avdec_h264. Using avdec_h264 might work if we try to decode from only one camera. However since our objective is to capture from 4 cameras, it is very essential for us to offload it to the GPU.
Lets look into the parameters,
Offloading the video decoding to GPU is a critical step towards our goal of minimizing the usage of CPU.
v4l2convert — This is letting the system know to convert the frame using the GPU instead of the CPU. There is a CPU equivalent which is video convert. This is again a CPU intensive process so we should be using v4l2convert to make use of the hardware acceleration offered by the Raspberry PI. We are doing few conversions here, they are
converting the source format into BGR. The frame size is reduced to 640x480 (from the original (720P). The documentation for v4l2convert says that there is an option for controlling the frame rate using v4l2convert itself. However I couldn’t make it work. Please let me know if any of you have made it work, I would be glad to hear. I had to use another videorate to control the frame rate since I couldn’t make v4l2convert control the frame rate.
videorate — This will help us to control the framerate that we want to capture in the application. Here in our case we want to capture only 1 frame in a second from a camera. So it will be framerate=”1/1” . Assume we want to capture only one frame in two seconds then the framerate will be “1/2”. Incase if we want to capture 5 frames in a second, the frame rate will be “5/1”
Now the idea is to run the video capture application using multiprocessing to make use of the different cores of Raspberry PI. The main program will kick off a separate process for each of the camera.
The rest of things are fairly straight forward. Once the frame is captured, it is converted to OpenCV format and pushed into a Queue. Currently this conversion is done using python code, kindly let me know if there is way to handle it within GStreamer pipeline. I am assuming there will be, but I have not investigated. It can further reduce the CPU usage if we can handle it within GStreamer pipeline as per my knowledge. Since we have 4 different cameras, there will be 4 different queues. The queues are using TCP protocol, because it will help us to distribute the load in future if we want this system to work on multiple hardware. ie we can scale out the processing server based on our needs and increase the frame rate or interval of capture or add more cameras. Probably we shall optimize it for distributed environment in the next release.
In the main_prgall.py (line number 27), you will have enter the RTSP URL of your streams
self.camlink1 = 'rtsp://<username>:<password>@192.168.1.2:554/cam/realmonitor?channel=1&subtype=0&unicast=true&proto=Onvif' #Add your RTSP cam link
and add the rest of the stream URLs based on your environment.
You can consume GStreamer pipeline from OpenCV. The Opencv needs to build with GStreamer support.
Processing Server
The idea is very straight forward, grab the frame from the Queues (4 queues) and push it to the intel NCS. The queue works using PUB / SUB model here. The camera is the PUB and the process server is the SUB. We shall move a frame to another queue if NCS detects a human in the frame.I have used the person detection retail 013 model from the intel model zoom. The details of the model can be found here:
docs.openvinotoolkit.org
It is essential that you should use the model that is compactible with your device. If you have NCS 2, then you should use the model that support NCS2.This is a model that can detect person in the video frame. It accepts the input frame of size height 320 and width 544
Communication engine
This is a very straight forward component. It gets the processed data from the Queue and stores the image into the local directory. It also connects with the Telegram bot and sends out a notification with the image attached.
The Bot Key and user ID is removed from the source code. You will have to insert your own Telegram bot Key and user ID
You can see from the image that the frames are processed almost realtime. During my testing, I found that all the frames were able to process in less than 2 seconds. ( detect motion in less than 2 seconds ). There might be a slight delay in the Telegram bot sending the image, but that is based on your Internet connectivity . However, I found it was negligible in almost all the cases.
CPU Consumption
The CPU consumption was around 30–35% which is okay considering the fact that it is processing the videos from 4 different streams in every second. The below image shows the CPU consumption and the temperature reported by raspberry pi.
I have found another way in which CPU utilization can be reduced. That is not in the python scripts, but in the CCTV itself. Most of the IP cameras supports multiple streams. ie one Mainstream ( with High quality resolution and frame rate) and sub stream with reduced resolution(640x480 in my case). The following screenshot shows the setting in my camera web interface
The following diagram shows the CPU utilization and temperature when connected to sub stream
As you may notice , the overall cpu utilization is between 16–22% that seems to be very reasonable. Since the heavy lifting was done the GPU, the system is able process multiple streams with less CPU usage in less than 2 seconds
Raspberry PI is a great platform. You will be able to find plenty of libraries and support .It is relatively cheap and efficient. The Intel NCS 1 does its duty. Probably the Intel NCS2 will be able to perform more number of inferences because it is advertised as much better in terms of performance. I have not got a chance to test the application in NCS 2 since I dont have one. I would really love to hear If any of you would like to test the script in NCS2 and report the performance . Having said, it just happened that I had both NCS1 and Raspberry PI for my experimenting. This might not be the best platforms if you are starting from scratch from a cost perspective. The RPI will cost around 4K INR and NCS costed me around 8K INR. I am curious to know how Nvidia’s Jetson Nano 2GB is. It has much better performance than NCS2 and dont require another SBC like PI. The cost is around 5K INR. Probably I shall cover it in my next update.
References
https://github.com/sahilparekh/GStreamer-Python — This is great repo that shows how to fetech RTSP streams in OpenCV. I have extended this sample in my project and the credit goes to the respective owner.
https://www.youtube.com/watch?v=HDY8pf-b1nA — This is a great place to start learning about GStreamer . This has really helped me to learn about GStreamer.
http://lifestyletransfer.com/how-to-use-gstreamer-appsrc-in-python/ — This is great place to learn about advanced Gstreamer concepts . A great set of working examples with great explanations. | [
{
"code": null,
"e": 785,
"s": 172,
"text": "I have recently installed a CCTV system at my home. It consisted of 4 IP cameras. I wanted them to be a bit more smarter. Instead of looking at the CCTV footage always, it would be good to get a notification if there is human detected by any of the cameras. This is a really cool stuff. I thought it would be really good if I get an alarm in my Telegram if any of the camera detect a motion. Though I started it for fun, I had a great learning. Fundamentally it enables video analytics at the edge without needing a cloud. I am here to share my learning and eager to learn from you if there are ways to optimize."
},
{
"code": null,
"e": 1188,
"s": 785,
"text": "I have 4 different IP cameras that stream 720P videos at 25FPS. I have a raspberry pi sitting idle and have got an Intel Movidius neural compute stick (ie first generation of NCS ). I wanted the Raspberry PI and NCS to perform the human detection and send me the notification in telegram when the camera detects a person. There were few things that I consider very important during the build, which are"
},
{
"code": null,
"e": 1384,
"s": 1188,
"text": "1. I should be able to run the application almost 24/7 , that means the code should be efficient. The CPU utilization must be as minimum as possible so that the PI’s temperature is under control."
},
{
"code": null,
"e": 1530,
"s": 1384,
"text": "2. I should get the notification almost instantaneously. The highest priority was that the human detection should complete as soon as it happens."
},
{
"code": null,
"e": 1646,
"s": 1530,
"text": "3. The notification should contain an image so that I can understand the context of the alert (who was the person)."
},
{
"code": null,
"e": 1725,
"s": 1646,
"text": "Let me tell you in advance, the item 1, and 2 were much harder than I thought."
},
{
"code": null,
"e": 1894,
"s": 1725,
"text": "I thought it is an easy task assuming Raspberry pi can get the video frame from each of the camera and NCS can perform the human detection. However, it was not so easy."
},
{
"code": null,
"e": 2005,
"s": 1894,
"text": "As usual, I started with plain OpenCV code to read the video RTSP stream a single camera and see how it works."
},
{
"code": null,
"e": 2217,
"s": 2005,
"text": "cap = cv2.VideoCapture(“RTSP URL of the IP Camera”) while(True): ret, frame = cap.read() cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release()cv2.destroyAllWindows()"
},
{
"code": null,
"e": 2753,
"s": 2217,
"text": "However few things were not working as I expected. First and foremost, there were huge delay in getting the frame in real time. Ie even if there are no processing (human detection) there was a delay of around 5 to 10 seconds and in some cases, it went to 40 seconds within couple of minutes of running the application. The CPU utilization reached 100% immediately. This is the point where I realized this is much complex than I thought. So, I had to go back to the drawing board to see what would be the best way to solve this problem."
},
{
"code": null,
"e": 3157,
"s": 2753,
"text": "I observed that this solution does not require to process each and every frame from the camera during my analysis. We absolutely don’t need to analyze 25 frames that are generated in a second. This is one of the primary principles that I used in my design and I came up the following design. What parameter will help us to define the number of frames that the system can process will be discussed later."
},
{
"code": null,
"e": 4026,
"s": 3157,
"text": "As you may notice, the idea is to capture N number of frames from each of the camera in every X seconds. This was not the only reason which made the system work efficiently. The solution made use of the hardware acceleration available in Raspberry pi so that the CPU utilization is very minimal. This will be detailed when I describe about GStreamer. The reason why the number of frames and the duration are variable is that it is purely based on the processing power of the hardware that is used for processing the frames. As per my knowledge, the first version of Intel NCS can perform less number of inferences. As you can imagine, the diagram clearly shows the bottle neck in the processing engine since it has to process all the frames. Since my plan to make use of an existing Intel NCS, I had to adjust these parameters according to the capabilities of the NCS."
},
{
"code": null,
"e": 4412,
"s": 4026,
"text": "As a starting point, I decided to capture one frame in every one second from each of the camera. This seems to be reasonable to me. Since it is not practically possible for a person to go past the camera viewing area in less than a second. However there is a possibility that the processing engine might fail to detect the object, but that is a separate topic which we will look later."
},
{
"code": null,
"e": 4719,
"s": 4412,
"text": "I realized that it is difficult to specify the frame number(s) / second that I want to capture when I am using OpenCV. So explored and found out that there are possibly two approaches to solve this problem . One is GStreamer and another is FFMPG. So I decided to explore the first option GStreamer further."
},
{
"code": null,
"e": 5019,
"s": 4719,
"text": "I found GStreamer is extremely powerful but complex due to the lack of documentation / examples. So I started exploring few tutorials in youtube and I found them very useful. I have mentioned the links that helped me to study about GStreamer in the Reference section. I am sure it will help you too."
},
{
"code": null,
"e": 5075,
"s": 5019,
"text": "The source code for this experiment can be found here :"
},
{
"code": null,
"e": 5086,
"s": 5075,
"text": "github.com"
},
{
"code": null,
"e": 5184,
"s": 5086,
"text": "The first step for me was to install GStreamer in Raspberry PI. This was fairly straight forward."
},
{
"code": null,
"e": 5224,
"s": 5184,
"text": "sudo apt-get install gstreamer1.0-tools"
},
{
"code": null,
"e": 5579,
"s": 5224,
"text": "The next step was to install Intel OpenVino toolkit for raspberry PI. This was necessary since the processing engine was Intel NCS. I had to install a version of OpenVINO that is supporting intel NCS since the latest versions of OpenVINO only support the Intel NCS 2. Please follow the link below link and install OpenVINO based on the NCS that you have."
},
{
"code": null,
"e": 5604,
"s": 5579,
"text": "docs.openvinotoolkit.org"
},
{
"code": null,
"e": 5629,
"s": 5604,
"text": "Other libraries include:"
},
{
"code": null,
"e": 5814,
"s": 5629,
"text": "pip install telepotpip install viztracersudo apt-get install pkg-config libcairo2-dev gcc python3-dev libgirepository1.0-devsudo apt-get install python3-gipip install gobject PyGObject"
},
{
"code": null,
"e": 6092,
"s": 5814,
"text": "The next step is to create the GStreamer pipeline. As I mentioned earlier, it is very powerful tool. Gstreamer is configured by the use of pipelines, which are a series of commands specifying where to get video from, how to process and encode it, and then where to send it out."
},
{
"code": null,
"e": 6146,
"s": 6092,
"text": "Lets have a look at the pipeline that I have created."
},
{
"code": null,
"e": 6469,
"s": 6146,
"text": "pipelinestring = \"rtspsrc location={0} name=m_rtspsrc ! rtph264depay ! h264parse ! v4l2h264dec capture-io-mode=4 ! video/x-raw ! v4l2convert output-io-mode=5 capture-io-mode=4 ! video/x-raw, format=(string)BGR, width=(int)640, height=(int)480 ! videorate ! video/x-raw,framerate=1/1 ! appsink name=m_appsink sync=false\""
},
{
"code": null,
"e": 6507,
"s": 6469,
"text": "Lets see the purpose of each element."
},
{
"code": null,
"e": 6581,
"s": 6507,
"text": "rtspsrc location={0} — The location is the RTSP url of the camera stream."
},
{
"code": null,
"e": 6634,
"s": 6581,
"text": "rtph264depay — Extracts H264 video from RTP packets."
},
{
"code": null,
"e": 7001,
"s": 6634,
"text": "v4l2h264dec- This is an interesting one . This tells the Raspberry PI to decode the H264 using the GPU. Remember there is an alternative which uses the CPU to decode. It is avdec_h264. Using avdec_h264 might work if we try to decode from only one camera. However since our objective is to capture from 4 cameras, it is very essential for us to offload it to the GPU."
},
{
"code": null,
"e": 7032,
"s": 7001,
"text": "Lets look into the parameters,"
},
{
"code": null,
"e": 7137,
"s": 7032,
"text": "Offloading the video decoding to GPU is a critical step towards our goal of minimizing the usage of CPU."
},
{
"code": null,
"e": 7474,
"s": 7137,
"text": "v4l2convert — This is letting the system know to convert the frame using the GPU instead of the CPU. There is a CPU equivalent which is video convert. This is again a CPU intensive process so we should be using v4l2convert to make use of the hardware acceleration offered by the Raspberry PI. We are doing few conversions here, they are"
},
{
"code": null,
"e": 7922,
"s": 7474,
"text": "converting the source format into BGR. The frame size is reduced to 640x480 (from the original (720P). The documentation for v4l2convert says that there is an option for controlling the frame rate using v4l2convert itself. However I couldn’t make it work. Please let me know if any of you have made it work, I would be glad to hear. I had to use another videorate to control the frame rate since I couldn’t make v4l2convert control the frame rate."
},
{
"code": null,
"e": 8299,
"s": 7922,
"text": "videorate — This will help us to control the framerate that we want to capture in the application. Here in our case we want to capture only 1 frame in a second from a camera. So it will be framerate=”1/1” . Assume we want to capture only one frame in two seconds then the framerate will be “1/2”. Incase if we want to capture 5 frames in a second, the frame rate will be “5/1”"
},
{
"code": null,
"e": 8500,
"s": 8299,
"text": "Now the idea is to run the video capture application using multiprocessing to make use of the different cores of Raspberry PI. The main program will kick off a separate process for each of the camera."
},
{
"code": null,
"e": 9349,
"s": 8500,
"text": "The rest of things are fairly straight forward. Once the frame is captured, it is converted to OpenCV format and pushed into a Queue. Currently this conversion is done using python code, kindly let me know if there is way to handle it within GStreamer pipeline. I am assuming there will be, but I have not investigated. It can further reduce the CPU usage if we can handle it within GStreamer pipeline as per my knowledge. Since we have 4 different cameras, there will be 4 different queues. The queues are using TCP protocol, because it will help us to distribute the load in future if we want this system to work on multiple hardware. ie we can scale out the processing server based on our needs and increase the frame rate or interval of capture or add more cameras. Probably we shall optimize it for distributed environment in the next release."
},
{
"code": null,
"e": 9438,
"s": 9349,
"text": "In the main_prgall.py (line number 27), you will have enter the RTSP URL of your streams"
},
{
"code": null,
"e": 9586,
"s": 9438,
"text": "self.camlink1 = 'rtsp://<username>:<password>@192.168.1.2:554/cam/realmonitor?channel=1&subtype=0&unicast=true&proto=Onvif' #Add your RTSP cam link"
},
{
"code": null,
"e": 9649,
"s": 9586,
"text": "and add the rest of the stream URLs based on your environment."
},
{
"code": null,
"e": 9747,
"s": 9649,
"text": "You can consume GStreamer pipeline from OpenCV. The Opencv needs to build with GStreamer support."
},
{
"code": null,
"e": 9765,
"s": 9747,
"text": "Processing Server"
},
{
"code": null,
"e": 10169,
"s": 9765,
"text": "The idea is very straight forward, grab the frame from the Queues (4 queues) and push it to the intel NCS. The queue works using PUB / SUB model here. The camera is the PUB and the process server is the SUB. We shall move a frame to another queue if NCS detects a human in the frame.I have used the person detection retail 013 model from the intel model zoom. The details of the model can be found here:"
},
{
"code": null,
"e": 10194,
"s": 10169,
"text": "docs.openvinotoolkit.org"
},
{
"code": null,
"e": 10464,
"s": 10194,
"text": "It is essential that you should use the model that is compactible with your device. If you have NCS 2, then you should use the model that support NCS2.This is a model that can detect person in the video frame. It accepts the input frame of size height 320 and width 544"
},
{
"code": null,
"e": 10485,
"s": 10464,
"text": "Communication engine"
},
{
"code": null,
"e": 10710,
"s": 10485,
"text": "This is a very straight forward component. It gets the processed data from the Queue and stores the image into the local directory. It also connects with the Telegram bot and sends out a notification with the image attached."
},
{
"code": null,
"e": 10829,
"s": 10710,
"text": "The Bot Key and user ID is removed from the source code. You will have to insert your own Telegram bot Key and user ID"
},
{
"code": null,
"e": 11216,
"s": 10829,
"text": "You can see from the image that the frames are processed almost realtime. During my testing, I found that all the frames were able to process in less than 2 seconds. ( detect motion in less than 2 seconds ). There might be a slight delay in the Telegram bot sending the image, but that is based on your Internet connectivity . However, I found it was negligible in almost all the cases."
},
{
"code": null,
"e": 11232,
"s": 11216,
"text": "CPU Consumption"
},
{
"code": null,
"e": 11468,
"s": 11232,
"text": "The CPU consumption was around 30–35% which is okay considering the fact that it is processing the videos from 4 different streams in every second. The below image shows the CPU consumption and the temperature reported by raspberry pi."
},
{
"code": null,
"e": 11838,
"s": 11468,
"text": "I have found another way in which CPU utilization can be reduced. That is not in the python scripts, but in the CCTV itself. Most of the IP cameras supports multiple streams. ie one Mainstream ( with High quality resolution and frame rate) and sub stream with reduced resolution(640x480 in my case). The following screenshot shows the setting in my camera web interface"
},
{
"code": null,
"e": 11931,
"s": 11838,
"text": "The following diagram shows the CPU utilization and temperature when connected to sub stream"
},
{
"code": null,
"e": 12160,
"s": 11931,
"text": "As you may notice , the overall cpu utilization is between 16–22% that seems to be very reasonable. Since the heavy lifting was done the GPU, the system is able process multiple streams with less CPU usage in less than 2 seconds"
},
{
"code": null,
"e": 13104,
"s": 12160,
"text": "Raspberry PI is a great platform. You will be able to find plenty of libraries and support .It is relatively cheap and efficient. The Intel NCS 1 does its duty. Probably the Intel NCS2 will be able to perform more number of inferences because it is advertised as much better in terms of performance. I have not got a chance to test the application in NCS 2 since I dont have one. I would really love to hear If any of you would like to test the script in NCS2 and report the performance . Having said, it just happened that I had both NCS1 and Raspberry PI for my experimenting. This might not be the best platforms if you are starting from scratch from a cost perspective. The RPI will cost around 4K INR and NCS costed me around 8K INR. I am curious to know how Nvidia’s Jetson Nano 2GB is. It has much better performance than NCS2 and dont require another SBC like PI. The cost is around 5K INR. Probably I shall cover it in my next update."
},
{
"code": null,
"e": 13115,
"s": 13104,
"text": "References"
},
{
"code": null,
"e": 13320,
"s": 13115,
"text": "https://github.com/sahilparekh/GStreamer-Python — This is great repo that shows how to fetech RTSP streams in OpenCV. I have extended this sample in my project and the credit goes to the respective owner."
},
{
"code": null,
"e": 13476,
"s": 13320,
"text": "https://www.youtube.com/watch?v=HDY8pf-b1nA — This is a great place to start learning about GStreamer . This has really helped me to learn about GStreamer."
}
] |
Redis - Hash Hset Command | Redis HSET command is used to set field in the hash stored at the key to value. If the key does not exist, a new key holding a hash is created. If the field already exists in the hash, it is overwritten.
Integer reply
1 if the field is a new field in the hash and value was set.
0 if the field already exists in the hash and the value was updated.
Following is the basic syntax of Redis HSET command.
redis 127.0.0.1:6379> HSET KEY_NAME FIELD VALUE
redis 127.0.0.1:6379> HSET myhash field1 "foo"
OK
redis 127.0.0.1:6379> HGET myhash field1
"foo"
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2249,
"s": 2045,
"text": "Redis HSET command is used to set field in the hash stored at the key to value. If the key does not exist, a new key holding a hash is created. If the field already exists in the hash, it is overwritten."
},
{
"code": null,
"e": 2263,
"s": 2249,
"text": "Integer reply"
},
{
"code": null,
"e": 2324,
"s": 2263,
"text": "1 if the field is a new field in the hash and value was set."
},
{
"code": null,
"e": 2393,
"s": 2324,
"text": "0 if the field already exists in the hash and the value was updated."
},
{
"code": null,
"e": 2446,
"s": 2393,
"text": "Following is the basic syntax of Redis HSET command."
},
{
"code": null,
"e": 2495,
"s": 2446,
"text": "redis 127.0.0.1:6379> HSET KEY_NAME FIELD VALUE\n"
},
{
"code": null,
"e": 2597,
"s": 2495,
"text": "redis 127.0.0.1:6379> HSET myhash field1 \"foo\" \nOK \nredis 127.0.0.1:6379> HGET myhash field1 \n\"foo\" \n"
},
{
"code": null,
"e": 2629,
"s": 2597,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2649,
"s": 2629,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2656,
"s": 2649,
"text": " Print"
},
{
"code": null,
"e": 2667,
"s": 2656,
"text": " Add Notes"
}
] |
How to select a range of rows from a dataframe in PySpark ? - GeeksforGeeks | 29 Jun, 2021
In this article, we are going to select a range of rows from a PySpark dataframe.
It can be done in these ways:
Using filter().
Using where().
Using SQL expression.
Creating Dataframe for demonstration:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "sravan", "vignan", 67, 89], ["2", "ojaswi", "vvit", 78, 89], ["3", "rohith", "vvit", 100, 80], ["4", "sridevi", "vignan", 78, 80], ["1", "sravan", "vignan", 89, 98], ["5", "gnanesh", "iit", 94, 98]] # specify column namescolumns = ['student ID', 'student NAME', 'college', 'subject1', 'subject2'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show()
Output:
Method 1: Using filter()
This function is used to filter the dataframe by selecting the records based on the given condition.
Syntax: dataframe.filter(condition)
Example: Python code to select the dataframe based on subject2 column.
Python3
# select dataframe between# 23 and 78 marks in subject2 dataframe.filter( dataframe.subject1.between(23,78)).show()
Output:
Method 2: Using where()
This function is used to filter the dataframe by selecting the records based on the given condition.
Syntax: dataframe.where(condition)
Example 1: Python program to select dataframe based on subject1 column.
Python3
# select dataframe between# 85 and 100 in subject1 columndataframe.filter( dataframe.subject1.between(85,100)).show()
Output:
Example 2: Select rows in dataframe by college column
Python3
# select dataframe in college column # for vvitdataframe.filter( dataframe.college.between("vvit","vvit")).collect()
Output:
[Row(ID=’2′, student NAME=’ojaswi’, college=’vvit’, subject1=78, subject2=89),
Row(ID=’3′, student NAME=’rohith’, college=’vvit’, subject1=100, subject2=80)]
Method 3: Using SQL Expression
By using SQL query with between() operator we can get the range of rows.
Syntax: spark.sql(“SELECT * FROM my_view WHERE column_name between value1 and value2”)
Example 1: Python program to select rows from dataframe based on subject2 column
Python3
# create view for the dataframedataframe.createOrReplaceTempView("my_view") # data subject1 between 23 and 78spark.sql("SELECT * FROM my_view WHERE\subject1 between 23 and 78").collect()
Output:
[Row(student ID=’1′, student NAME=’sravan’, college=’vignan’, subject1=67, subject2=89),
Row(student ID=’2′, student NAME=’ojaswi’, college=’vvit’, subject1=78, subject2=89),
Row(student ID=’4′, student NAME=’sridevi’, college=’vignan’, subject1=78, subject2=80)]
Example 2: Select based on ID
Python3
# create view for the dataframedataframe.createOrReplaceTempView("my_view") # data subject1 between 23 and 78spark.sql("SELECT * FROM my_view WHERE\ID between 1 and 3").collect()
Output:
[Row(ID=’1′, student NAME=’sravan’, college=’vignan’, subject1=67, subject2=89),
Row(ID=’2′, student NAME=’ojaswi’, college=’vvit’, subject1=78, subject2=89),
Row(ID=’3′, student NAME=’rohith’, college=’vvit’, subject1=100, subject2=80),
Row(ID=’1′, student NAME=’sravan’, college=’vignan’, subject1=89, subject2=98)]
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24317,
"s": 24289,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 24399,
"s": 24317,
"text": "In this article, we are going to select a range of rows from a PySpark dataframe."
},
{
"code": null,
"e": 24429,
"s": 24399,
"text": "It can be done in these ways:"
},
{
"code": null,
"e": 24445,
"s": 24429,
"text": "Using filter()."
},
{
"code": null,
"e": 24460,
"s": 24445,
"text": "Using where()."
},
{
"code": null,
"e": 24482,
"s": 24460,
"text": "Using SQL expression."
},
{
"code": null,
"e": 24520,
"s": 24482,
"text": "Creating Dataframe for demonstration:"
},
{
"code": null,
"e": 24528,
"s": 24520,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"sravan\", \"vignan\", 67, 89], [\"2\", \"ojaswi\", \"vvit\", 78, 89], [\"3\", \"rohith\", \"vvit\", 100, 80], [\"4\", \"sridevi\", \"vignan\", 78, 80], [\"1\", \"sravan\", \"vignan\", 89, 98], [\"5\", \"gnanesh\", \"iit\", 94, 98]] # specify column namescolumns = ['student ID', 'student NAME', 'college', 'subject1', 'subject2'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show()",
"e": 25272,
"s": 24528,
"text": null
},
{
"code": null,
"e": 25280,
"s": 25272,
"text": "Output:"
},
{
"code": null,
"e": 25305,
"s": 25280,
"text": "Method 1: Using filter()"
},
{
"code": null,
"e": 25406,
"s": 25305,
"text": "This function is used to filter the dataframe by selecting the records based on the given condition."
},
{
"code": null,
"e": 25442,
"s": 25406,
"text": "Syntax: dataframe.filter(condition)"
},
{
"code": null,
"e": 25513,
"s": 25442,
"text": "Example: Python code to select the dataframe based on subject2 column."
},
{
"code": null,
"e": 25521,
"s": 25513,
"text": "Python3"
},
{
"code": "# select dataframe between# 23 and 78 marks in subject2 dataframe.filter( dataframe.subject1.between(23,78)).show()",
"e": 25638,
"s": 25521,
"text": null
},
{
"code": null,
"e": 25646,
"s": 25638,
"text": "Output:"
},
{
"code": null,
"e": 25670,
"s": 25646,
"text": "Method 2: Using where()"
},
{
"code": null,
"e": 25771,
"s": 25670,
"text": "This function is used to filter the dataframe by selecting the records based on the given condition."
},
{
"code": null,
"e": 25806,
"s": 25771,
"text": "Syntax: dataframe.where(condition)"
},
{
"code": null,
"e": 25878,
"s": 25806,
"text": "Example 1: Python program to select dataframe based on subject1 column."
},
{
"code": null,
"e": 25886,
"s": 25878,
"text": "Python3"
},
{
"code": "# select dataframe between# 85 and 100 in subject1 columndataframe.filter( dataframe.subject1.between(85,100)).show()",
"e": 26005,
"s": 25886,
"text": null
},
{
"code": null,
"e": 26013,
"s": 26005,
"text": "Output:"
},
{
"code": null,
"e": 26067,
"s": 26013,
"text": "Example 2: Select rows in dataframe by college column"
},
{
"code": null,
"e": 26075,
"s": 26067,
"text": "Python3"
},
{
"code": "# select dataframe in college column # for vvitdataframe.filter( dataframe.college.between(\"vvit\",\"vvit\")).collect()",
"e": 26193,
"s": 26075,
"text": null
},
{
"code": null,
"e": 26201,
"s": 26193,
"text": "Output:"
},
{
"code": null,
"e": 26280,
"s": 26201,
"text": "[Row(ID=’2′, student NAME=’ojaswi’, college=’vvit’, subject1=78, subject2=89),"
},
{
"code": null,
"e": 26359,
"s": 26280,
"text": "Row(ID=’3′, student NAME=’rohith’, college=’vvit’, subject1=100, subject2=80)]"
},
{
"code": null,
"e": 26390,
"s": 26359,
"text": "Method 3: Using SQL Expression"
},
{
"code": null,
"e": 26463,
"s": 26390,
"text": "By using SQL query with between() operator we can get the range of rows."
},
{
"code": null,
"e": 26550,
"s": 26463,
"text": "Syntax: spark.sql(“SELECT * FROM my_view WHERE column_name between value1 and value2”)"
},
{
"code": null,
"e": 26631,
"s": 26550,
"text": "Example 1: Python program to select rows from dataframe based on subject2 column"
},
{
"code": null,
"e": 26639,
"s": 26631,
"text": "Python3"
},
{
"code": "# create view for the dataframedataframe.createOrReplaceTempView(\"my_view\") # data subject1 between 23 and 78spark.sql(\"SELECT * FROM my_view WHERE\\subject1 between 23 and 78\").collect()",
"e": 26827,
"s": 26639,
"text": null
},
{
"code": null,
"e": 26835,
"s": 26827,
"text": "Output:"
},
{
"code": null,
"e": 26924,
"s": 26835,
"text": "[Row(student ID=’1′, student NAME=’sravan’, college=’vignan’, subject1=67, subject2=89),"
},
{
"code": null,
"e": 27010,
"s": 26924,
"text": "Row(student ID=’2′, student NAME=’ojaswi’, college=’vvit’, subject1=78, subject2=89),"
},
{
"code": null,
"e": 27099,
"s": 27010,
"text": "Row(student ID=’4′, student NAME=’sridevi’, college=’vignan’, subject1=78, subject2=80)]"
},
{
"code": null,
"e": 27129,
"s": 27099,
"text": "Example 2: Select based on ID"
},
{
"code": null,
"e": 27137,
"s": 27129,
"text": "Python3"
},
{
"code": "# create view for the dataframedataframe.createOrReplaceTempView(\"my_view\") # data subject1 between 23 and 78spark.sql(\"SELECT * FROM my_view WHERE\\ID between 1 and 3\").collect()",
"e": 27317,
"s": 27137,
"text": null
},
{
"code": null,
"e": 27325,
"s": 27317,
"text": "Output:"
},
{
"code": null,
"e": 27406,
"s": 27325,
"text": "[Row(ID=’1′, student NAME=’sravan’, college=’vignan’, subject1=67, subject2=89),"
},
{
"code": null,
"e": 27484,
"s": 27406,
"text": "Row(ID=’2′, student NAME=’ojaswi’, college=’vvit’, subject1=78, subject2=89),"
},
{
"code": null,
"e": 27563,
"s": 27484,
"text": "Row(ID=’3′, student NAME=’rohith’, college=’vvit’, subject1=100, subject2=80),"
},
{
"code": null,
"e": 27643,
"s": 27563,
"text": "Row(ID=’1′, student NAME=’sravan’, college=’vignan’, subject1=89, subject2=98)]"
},
{
"code": null,
"e": 27650,
"s": 27643,
"text": "Picked"
},
{
"code": null,
"e": 27665,
"s": 27650,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 27672,
"s": 27665,
"text": "Python"
},
{
"code": null,
"e": 27770,
"s": 27672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27779,
"s": 27770,
"text": "Comments"
},
{
"code": null,
"e": 27792,
"s": 27779,
"text": "Old Comments"
},
{
"code": null,
"e": 27810,
"s": 27792,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27845,
"s": 27810,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27867,
"s": 27845,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27899,
"s": 27867,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27929,
"s": 27899,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27971,
"s": 27929,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28014,
"s": 27971,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28040,
"s": 28014,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28084,
"s": 28040,
"text": "Reading and Writing to text files in Python"
}
] |
SQL statement to add a table as Virtual table in SAP HANA Smart Data Access | You can use following SQL statement for this −
CREATE VIRTUAL TABLE <table_name> <remote_location_clause>
CREATE VIRTUAL TABLE ABC.test_VT AT “ORCL_11G_WIN”.”NULL”.”OUTLN”.”Dept”;
In this SQL statement, ABC.test_VT is Virtual table name
“ORCL_11G_WIN”.”NULL”.”OUTLN”.”Dept”;- Remote location for creating Virtual table | [
{
"code": null,
"e": 1109,
"s": 1062,
"text": "You can use following SQL statement for this −"
},
{
"code": null,
"e": 1168,
"s": 1109,
"text": "CREATE VIRTUAL TABLE <table_name> <remote_location_clause>"
},
{
"code": null,
"e": 1242,
"s": 1168,
"text": "CREATE VIRTUAL TABLE ABC.test_VT AT “ORCL_11G_WIN”.”NULL”.”OUTLN”.”Dept”;"
},
{
"code": null,
"e": 1299,
"s": 1242,
"text": "In this SQL statement, ABC.test_VT is Virtual table name"
},
{
"code": null,
"e": 1381,
"s": 1299,
"text": "“ORCL_11G_WIN”.”NULL”.”OUTLN”.”Dept”;- Remote location for creating Virtual table"
}
] |
SQL - Using GROUP BY to COUNT the Number of Rows For Each Unique Entry in a Column - GeeksforGeeks | 18 Oct, 2021
In this article, we will see how to use GROUP BY to count the number of rows for each unique entry in a given table. Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table.
Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.
Now, for the demonstration follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
USE geeks;
Step 3: Table definition
We have the following demo_table in our geek’s database.
Query:
CREATE TABLE demo_table(
NAME VARCHAR(20),
AGE int,
CITY VARCHAR(10));
Step 4: Insert data into a table
Query:
INSERT INTO demo_table VALUES ('Romy',23,'Delhi'),
('Pushkar',23,'Delhi'),
('Nikhil',24,'Punjab'),
('Rinkle',23,'Punjab'),
('Samiksha',23,'Banglore'),
('Ashtha',24,'Banglore'),
('Satish',30,'Patna'),
('Girish',30,'Patna');
Step 5: View the content
Execute the below query to see the content of the table
SELECT * FROM demo_table;
Output:
Step 6: use of COUNT without ORDER BY statement
COUNT(*) counts all rows
COUNT(column_name) counts non-NULLs only in the specified column name.
Syntax(count all rows):
SELECT COUNT(*)
FROM table_name;
Query:
SELECT COUNT(*) FROM demo_table;
Output:
The result is 8, as we have 8 entries in our demo_table.
Step 7: use GROUP BY
For counting the unique values in the AGE column.
Query:
SELECT AGE, COUNT(*) as COUNT from demo_table GROUP BY AGE;
Output:
For counting the unique values in the CITY column.
SELECT CITY,COUNT(*) as COUNT from demo_table GROUP BY CITY;
Output:
Picked
SQL-Server
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Types of Internet Protocols
SQL Statement to Remove Part of a String
Basics of API Testing Using Postman | [
{
"code": null,
"e": 24188,
"s": 24160,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 24410,
"s": 24188,
"text": "In this article, we will see how to use GROUP BY to count the number of rows for each unique entry in a given table. Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table."
},
{
"code": null,
"e": 24503,
"s": 24410,
"text": "Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column."
},
{
"code": null,
"e": 24554,
"s": 24503,
"text": "Now, for the demonstration follow the below steps:"
},
{
"code": null,
"e": 24580,
"s": 24554,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 24648,
"s": 24580,
"text": "we can use the following command to create a database called geeks."
},
{
"code": null,
"e": 24655,
"s": 24648,
"text": "Query:"
},
{
"code": null,
"e": 24678,
"s": 24655,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 24699,
"s": 24678,
"text": "Step 2: Use database"
},
{
"code": null,
"e": 24768,
"s": 24699,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 24779,
"s": 24768,
"text": "USE geeks;"
},
{
"code": null,
"e": 24804,
"s": 24779,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 24862,
"s": 24804,
"text": "We have the following demo_table in our geek’s database. "
},
{
"code": null,
"e": 24869,
"s": 24862,
"text": "Query:"
},
{
"code": null,
"e": 24940,
"s": 24869,
"text": "CREATE TABLE demo_table(\nNAME VARCHAR(20),\nAGE int,\nCITY VARCHAR(10));"
},
{
"code": null,
"e": 24973,
"s": 24940,
"text": "Step 4: Insert data into a table"
},
{
"code": null,
"e": 24980,
"s": 24973,
"text": "Query:"
},
{
"code": null,
"e": 25203,
"s": 24980,
"text": "INSERT INTO demo_table VALUES ('Romy',23,'Delhi'),\n('Pushkar',23,'Delhi'),\n('Nikhil',24,'Punjab'),\n('Rinkle',23,'Punjab'),\n('Samiksha',23,'Banglore'),\n('Ashtha',24,'Banglore'),\n('Satish',30,'Patna'),\n('Girish',30,'Patna');"
},
{
"code": null,
"e": 25228,
"s": 25203,
"text": "Step 5: View the content"
},
{
"code": null,
"e": 25284,
"s": 25228,
"text": "Execute the below query to see the content of the table"
},
{
"code": null,
"e": 25310,
"s": 25284,
"text": "SELECT * FROM demo_table;"
},
{
"code": null,
"e": 25318,
"s": 25310,
"text": "Output:"
},
{
"code": null,
"e": 25366,
"s": 25318,
"text": "Step 6: use of COUNT without ORDER BY statement"
},
{
"code": null,
"e": 25391,
"s": 25366,
"text": "COUNT(*) counts all rows"
},
{
"code": null,
"e": 25462,
"s": 25391,
"text": "COUNT(column_name) counts non-NULLs only in the specified column name."
},
{
"code": null,
"e": 25486,
"s": 25462,
"text": "Syntax(count all rows):"
},
{
"code": null,
"e": 25519,
"s": 25486,
"text": "SELECT COUNT(*)\nFROM table_name;"
},
{
"code": null,
"e": 25526,
"s": 25519,
"text": "Query:"
},
{
"code": null,
"e": 25559,
"s": 25526,
"text": "SELECT COUNT(*) FROM demo_table;"
},
{
"code": null,
"e": 25567,
"s": 25559,
"text": "Output:"
},
{
"code": null,
"e": 25624,
"s": 25567,
"text": "The result is 8, as we have 8 entries in our demo_table."
},
{
"code": null,
"e": 25645,
"s": 25624,
"text": "Step 7: use GROUP BY"
},
{
"code": null,
"e": 25695,
"s": 25645,
"text": "For counting the unique values in the AGE column."
},
{
"code": null,
"e": 25702,
"s": 25695,
"text": "Query:"
},
{
"code": null,
"e": 25762,
"s": 25702,
"text": "SELECT AGE, COUNT(*) as COUNT from demo_table GROUP BY AGE;"
},
{
"code": null,
"e": 25770,
"s": 25762,
"text": "Output:"
},
{
"code": null,
"e": 25821,
"s": 25770,
"text": "For counting the unique values in the CITY column."
},
{
"code": null,
"e": 25882,
"s": 25821,
"text": "SELECT CITY,COUNT(*) as COUNT from demo_table GROUP BY CITY;"
},
{
"code": null,
"e": 25890,
"s": 25882,
"text": "Output:"
},
{
"code": null,
"e": 25897,
"s": 25890,
"text": "Picked"
},
{
"code": null,
"e": 25908,
"s": 25897,
"text": "SQL-Server"
},
{
"code": null,
"e": 25922,
"s": 25908,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 25926,
"s": 25922,
"text": "SQL"
},
{
"code": null,
"e": 25935,
"s": 25926,
"text": "TrueGeek"
},
{
"code": null,
"e": 25939,
"s": 25935,
"text": "SQL"
},
{
"code": null,
"e": 26037,
"s": 25939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26046,
"s": 26037,
"text": "Comments"
},
{
"code": null,
"e": 26059,
"s": 26046,
"text": "Old Comments"
},
{
"code": null,
"e": 26125,
"s": 26059,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26178,
"s": 26125,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 26210,
"s": 26178,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26227,
"s": 26210,
"text": "SQL using Python"
},
{
"code": null,
"e": 26305,
"s": 26227,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26350,
"s": 26305,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 26407,
"s": 26350,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 26435,
"s": 26407,
"text": "Types of Internet Protocols"
},
{
"code": null,
"e": 26476,
"s": 26435,
"text": "SQL Statement to Remove Part of a String"
}
] |
Counting the occurrences of JavaScript array elements and put in a new 2d array | We are required to write a JavaScript function that takes in an array of literal values. The function should then count the frequency of each element of the input array and prepare a new array on that basis.
For example − If the input array is −
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
Then the output should be −
const output = [
[5, 3],
[2, 5],
[9, 1],
[4, 1]
];
The code for this will be −
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequencyArray = (arr = []) => {
const res = [];
arr.forEach(el => {
if (!this[el]) {
this[el] = [el, 0];
res.push(this[el])
};
this[el][1] ++
}, {});
return res;
};
console.log(frequencyArray(arr));
And the output in the console will be −
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ] | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of literal values. The function should then count the frequency of each element of the input array and prepare a new array on that basis."
},
{
"code": null,
"e": 1308,
"s": 1270,
"text": "For example − If the input array is −"
},
{
"code": null,
"e": 1352,
"s": 1308,
"text": "const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];"
},
{
"code": null,
"e": 1380,
"s": 1352,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1443,
"s": 1380,
"text": "const output = [\n [5, 3],\n [2, 5],\n [9, 1],\n [4, 1]\n];"
},
{
"code": null,
"e": 1471,
"s": 1443,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1769,
"s": 1471,
"text": "const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];\nconst frequencyArray = (arr = []) => {\n const res = [];\n arr.forEach(el => {\n if (!this[el]) {\n this[el] = [el, 0];\n res.push(this[el])\n };\n this[el][1] ++\n }, {});\n return res;\n};\nconsole.log(frequencyArray(arr));"
},
{
"code": null,
"e": 1809,
"s": 1769,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 1852,
"s": 1809,
"text": "[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]"
}
] |
Python 3 - os.listdir() Method | The method listdir() returns a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
path may be either of type str or of type bytes. If path is of type bytes, the filenames returned will also be of type bytes; in all other circumstances, they will be of type str.
Following is the syntax for listdir() method −
os.listdir(path)
path − This is the directory, which needs to be explored.
This method returns a list containing the names of the entries in the directory given by path.
The following example shows the usage of listdir() method.
#!/usr/bin/python3
import os, sys
# Open a file
path = "d:\\tmp\\"
dirs = os.listdir( path )
# This would print all the files and directories
for file in dirs:
print (file)
When we run the above program, it produces the following result −
Applicationdocs.docx
test.java
book.zip
foo.txt
Java Multiple Inheritance.htm
Java Multiple Inheritance_files
java.ppt
ParallelPortViewer
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2572,
"s": 2340,
"text": "The method listdir() returns a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory."
},
{
"code": null,
"e": 2752,
"s": 2572,
"text": "path may be either of type str or of type bytes. If path is of type bytes, the filenames returned will also be of type bytes; in all other circumstances, they will be of type str."
},
{
"code": null,
"e": 2799,
"s": 2752,
"text": "Following is the syntax for listdir() method −"
},
{
"code": null,
"e": 2817,
"s": 2799,
"text": "os.listdir(path)\n"
},
{
"code": null,
"e": 2875,
"s": 2817,
"text": "path − This is the directory, which needs to be explored."
},
{
"code": null,
"e": 2970,
"s": 2875,
"text": "This method returns a list containing the names of the entries in the directory given by path."
},
{
"code": null,
"e": 3029,
"s": 2970,
"text": "The following example shows the usage of listdir() method."
},
{
"code": null,
"e": 3207,
"s": 3029,
"text": "#!/usr/bin/python3\nimport os, sys\n\n# Open a file\npath = \"d:\\\\tmp\\\\\"\ndirs = os.listdir( path )\n\n# This would print all the files and directories\nfor file in dirs:\n print (file)"
},
{
"code": null,
"e": 3273,
"s": 3207,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3412,
"s": 3273,
"text": "Applicationdocs.docx\ntest.java\nbook.zip\nfoo.txt\nJava Multiple Inheritance.htm\nJava Multiple Inheritance_files\njava.ppt\nParallelPortViewer\n"
},
{
"code": null,
"e": 3449,
"s": 3412,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3465,
"s": 3449,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3498,
"s": 3465,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3517,
"s": 3498,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3552,
"s": 3517,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3574,
"s": 3552,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3608,
"s": 3574,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3636,
"s": 3608,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3671,
"s": 3636,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3685,
"s": 3671,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3718,
"s": 3685,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3735,
"s": 3718,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3742,
"s": 3735,
"text": " Print"
},
{
"code": null,
"e": 3753,
"s": 3742,
"text": " Add Notes"
}
] |
JavaScript RegExp return values between various square brackets? How to get value brackets? | Use regular expression with indexes 0,1....N to get the value without brackets. Following is the
code −
var regularExpression= /(?<=\[).*?(?=\])/g;
var getTheValueWithIndex= "[John Smith][David
Miller]".match(regularExpression);
console.log("The first value without bracket="+getTheValueWithIndex[0]);
console.log("The second value without
bracket="+getTheValueWithIndex[1]);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo132.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo132.js
The first value without bracket=John Smith
The second value without bracket=David Miller | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "Use regular expression with indexes 0,1....N to get the value without brackets. Following is the\ncode −"
},
{
"code": null,
"e": 1438,
"s": 1166,
"text": "var regularExpression= /(?<=\\[).*?(?=\\])/g;\nvar getTheValueWithIndex= \"[John Smith][David\nMiller]\".match(regularExpression);\nconsole.log(\"The first value without bracket=\"+getTheValueWithIndex[0]);\nconsole.log(\"The second value without\nbracket=\"+getTheValueWithIndex[1]);"
},
{
"code": null,
"e": 1504,
"s": 1438,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1522,
"s": 1504,
"text": "node fileName.js."
},
{
"code": null,
"e": 1556,
"s": 1522,
"text": "Here, my file name is demo132.js."
},
{
"code": null,
"e": 1597,
"s": 1556,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1736,
"s": 1597,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo132.js\nThe first value without bracket=John Smith\nThe second value without bracket=David Miller"
}
] |
PyQt5 – Hide push button on click - GeeksforGeeks | 23 Sep, 2021
In this article we will see how to hide the push button. When we design a GUI (Graphical User Interface) we create push button in it which do some task when they are pressed. But some time their is a need to hide the button if task is completed, in order to hide the button we will use hide method.
Syntax : button.hide()Argument : It takes no argument.Action performed : It hides the push button
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) # creating a button self.button = QPushButton("CLICK", self) # setting up the geometry self.button.setGeometry(200, 150, 200, 40) # connecting method when button get clicked self.button.clicked.connect(self.clickme) # showing all the widgets self.show() # action method def clickme(self): # hiding the button self.button.hide() # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
When click button is pressed, output will generate and button will get hidden.
pressed
sweetyty
Python-gui
Python-PyQt
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 ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Convert integer to string in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24133,
"s": 24105,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 24432,
"s": 24133,
"text": "In this article we will see how to hide the push button. When we design a GUI (Graphical User Interface) we create push button in it which do some task when they are pressed. But some time their is a need to hide the button if task is completed, in order to hide the button we will use hide method."
},
{
"code": null,
"e": 24530,
"s": 24432,
"text": "Syntax : button.hide()Argument : It takes no argument.Action performed : It hides the push button"
},
{
"code": null,
"e": 24539,
"s": 24530,
"text": "Code : "
},
{
"code": null,
"e": 24547,
"s": 24539,
"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) # creating a button self.button = QPushButton(\"CLICK\", self) # setting up the geometry self.button.setGeometry(200, 150, 200, 40) # connecting method when button get clicked self.button.clicked.connect(self.clickme) # showing all the widgets self.show() # action method def clickme(self): # hiding the button self.button.hide() # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 25465,
"s": 24547,
"text": null
},
{
"code": null,
"e": 25475,
"s": 25465,
"text": "Output : "
},
{
"code": null,
"e": 25555,
"s": 25475,
"text": "When click button is pressed, output will generate and button will get hidden. "
},
{
"code": null,
"e": 25564,
"s": 25555,
"text": "pressed "
},
{
"code": null,
"e": 25575,
"s": 25566,
"text": "sweetyty"
},
{
"code": null,
"e": 25586,
"s": 25575,
"text": "Python-gui"
},
{
"code": null,
"e": 25598,
"s": 25586,
"text": "Python-PyQt"
},
{
"code": null,
"e": 25605,
"s": 25598,
"text": "Python"
},
{
"code": null,
"e": 25703,
"s": 25605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25712,
"s": 25703,
"text": "Comments"
},
{
"code": null,
"e": 25725,
"s": 25712,
"text": "Old Comments"
},
{
"code": null,
"e": 25757,
"s": 25725,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25799,
"s": 25757,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25836,
"s": 25799,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 25892,
"s": 25836,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25921,
"s": 25892,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 25954,
"s": 25921,
"text": "Graph Plotting in Python | Set 1"
},
{
"code": null,
"e": 25996,
"s": 25954,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26038,
"s": 25996,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26074,
"s": 26038,
"text": "Convert integer to string in Python"
}
] |
How to delete azure blob (file) from the Storage account using PowerShell? | To delete the Azure blob from the azure storage account using PowerShell, we can use the RemoveAzStorageBlob command. Before running this command, we need to make sure that the Azure cloud account is connected (Connect-AzAccount) and the proper subscription is set in which the storage account resides (Set-AzContext).
Once the above two commands are executed, we can use the Remove-AzStorageBlob command but we need to use the storage context to work with the Azure Storage account.
The below commands will set the context for the Azure storage account with the storage account key.
$rg = "az204"
$storageaccount = "az204storage05june"
$key = (Get-AzStorageAccountKey -ResourceGroupName $rg - Name $storageaccount)[0].Value
$context = New-AzStorageContext -StorageAccountName $storageaccount - StorageAccountKey $key
The below will remove azure storage blob test1.py from the storage container ‘container1’.
Remove-AzStorageBlob -Container 'container1' -Context $context -Blob 'Test1.py' - Verbose
-Blob parameter accepts only one file or blob at a time. If you want to delete the entire content of the container then you need to use a loop.
foreach($file in (Get-AzStorageBlob -Container 'container1' -
Context $context).Name){
Remove-AzStorageBlob -Container 'container1' -Context $context -Blob $file - Verbose
} | [
{
"code": null,
"e": 1381,
"s": 1062,
"text": "To delete the Azure blob from the azure storage account using PowerShell, we can use the RemoveAzStorageBlob command. Before running this command, we need to make sure that the Azure cloud account is connected (Connect-AzAccount) and the proper subscription is set in which the storage account resides (Set-AzContext)."
},
{
"code": null,
"e": 1546,
"s": 1381,
"text": "Once the above two commands are executed, we can use the Remove-AzStorageBlob command but we need to use the storage context to work with the Azure Storage account."
},
{
"code": null,
"e": 1646,
"s": 1546,
"text": "The below commands will set the context for the Azure storage account with the storage account key."
},
{
"code": null,
"e": 1880,
"s": 1646,
"text": "$rg = \"az204\"\n$storageaccount = \"az204storage05june\"\n$key = (Get-AzStorageAccountKey -ResourceGroupName $rg - Name $storageaccount)[0].Value\n$context = New-AzStorageContext -StorageAccountName $storageaccount - StorageAccountKey $key"
},
{
"code": null,
"e": 1971,
"s": 1880,
"text": "The below will remove azure storage blob test1.py from the storage container ‘container1’."
},
{
"code": null,
"e": 2061,
"s": 1971,
"text": "Remove-AzStorageBlob -Container 'container1' -Context $context -Blob 'Test1.py' - Verbose"
},
{
"code": null,
"e": 2205,
"s": 2061,
"text": "-Blob parameter accepts only one file or blob at a time. If you want to delete the entire content of the container then you need to use a loop."
},
{
"code": null,
"e": 2382,
"s": 2205,
"text": "foreach($file in (Get-AzStorageBlob -Container 'container1' -\nContext $context).Name){\n Remove-AzStorageBlob -Container 'container1' -Context $context -Blob $file - Verbose\n}"
}
] |
How to launch Chrome Browser via Selenium? | We can launch Chrome browser via Selenium. Java JDK, Eclipse and Selenium webdriver should be installed in the system before Chrome browser is launch.
Follow the steps one by one to launch Chrome −
Navigate to the link: https://chromedriver.chromium.org/downloads.
Navigate to the link: https://chromedriver.chromium.org/downloads.
Select the Chrome driver link which matches with the Chrome browser in our system.
Select the Chrome driver link which matches with the Chrome browser in our system.
Next, we have to choose and click on the Chrome driver link which is compatible with the operating system we are using.
Next, we have to choose and click on the Chrome driver link which is compatible with the operating system we are using.
A zip file gets downloaded. Extract and save the chromedriver.exe file in a location.
A zip file gets downloaded. Extract and save the chromedriver.exe file in a location.
We can configure the chromedriver.exe file in the following ways −
By setting the System Properties in the Environment Variables. Go to the Start and type System and click on it. Select the Advanced System Settings. Then click on the Environment Variables from the Advanced. From the System Variables, select Path and click on Edit. Then click on New. Add the chromedriver.exe path and proceed.
By setting the System Properties in the Environment Variables. Go to the Start and type System and click on it. Select the Advanced System Settings. Then click on the Environment Variables from the Advanced. From the System Variables, select Path and click on Edit. Then click on New. Add the chromedriver.exe path and proceed.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChromeLaunch{
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
String url = " https://www.tutorialspoint.com/questions/index.php";
driver.get(url);
}
}
By setting the System Properties in the script. By adding the browser type and chromedriver.exe path as parameters to the System.setProperty method in the code.
By setting the System Properties in the script. By adding the browser type and chromedriver.exe path as parameters to the System.setProperty method in the code.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchChromeBrw{
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
// browser type and chromedrover.exe path as parameters
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
String url = " https://www.tutorialspoint.com/questions/index.php";
driver.get(url);
}
} | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "We can launch Chrome browser via Selenium. Java JDK, Eclipse and Selenium webdriver should be installed in the system before Chrome browser is launch."
},
{
"code": null,
"e": 1260,
"s": 1213,
"text": "Follow the steps one by one to launch Chrome −"
},
{
"code": null,
"e": 1327,
"s": 1260,
"text": "Navigate to the link: https://chromedriver.chromium.org/downloads."
},
{
"code": null,
"e": 1394,
"s": 1327,
"text": "Navigate to the link: https://chromedriver.chromium.org/downloads."
},
{
"code": null,
"e": 1477,
"s": 1394,
"text": "Select the Chrome driver link which matches with the Chrome browser in our system."
},
{
"code": null,
"e": 1560,
"s": 1477,
"text": "Select the Chrome driver link which matches with the Chrome browser in our system."
},
{
"code": null,
"e": 1680,
"s": 1560,
"text": "Next, we have to choose and click on the Chrome driver link which is compatible with the operating system we are using."
},
{
"code": null,
"e": 1800,
"s": 1680,
"text": "Next, we have to choose and click on the Chrome driver link which is compatible with the operating system we are using."
},
{
"code": null,
"e": 1886,
"s": 1800,
"text": "A zip file gets downloaded. Extract and save the chromedriver.exe file in a location."
},
{
"code": null,
"e": 1972,
"s": 1886,
"text": "A zip file gets downloaded. Extract and save the chromedriver.exe file in a location."
},
{
"code": null,
"e": 2039,
"s": 1972,
"text": "We can configure the chromedriver.exe file in the following ways −"
},
{
"code": null,
"e": 2367,
"s": 2039,
"text": "By setting the System Properties in the Environment Variables. Go to the Start and type System and click on it. Select the Advanced System Settings. Then click on the Environment Variables from the Advanced. From the System Variables, select Path and click on Edit. Then click on New. Add the chromedriver.exe path and proceed."
},
{
"code": null,
"e": 2695,
"s": 2367,
"text": "By setting the System Properties in the Environment Variables. Go to the Start and type System and click on it. Select the Advanced System Settings. Then click on the Environment Variables from the Advanced. From the System Variables, select Path and click on Edit. Then click on New. Add the chromedriver.exe path and proceed."
},
{
"code": null,
"e": 3001,
"s": 2695,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class ChromeLaunch{\n public static void main(String[] args) {\n WebDriver driver = new ChromeDriver();\n String url = \" https://www.tutorialspoint.com/questions/index.php\";\n driver.get(url);\n }\n}"
},
{
"code": null,
"e": 3162,
"s": 3001,
"text": "By setting the System Properties in the script. By adding the browser type and chromedriver.exe path as parameters to the System.setProperty method in the code."
},
{
"code": null,
"e": 3323,
"s": 3162,
"text": "By setting the System Properties in the script. By adding the browser type and chromedriver.exe path as parameters to the System.setProperty method in the code."
},
{
"code": null,
"e": 3808,
"s": 3323,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class LaunchChromeBrw{\n public static void main(String[] args) {\n WebDriver driver = new ChromeDriver();\n // browser type and chromedrover.exe path as parameters\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n String url = \" https://www.tutorialspoint.com/questions/index.php\";\n driver.get(url);\n }\n}"
}
] |
How to add items to a list in C#? | Firstly, declare a list −
var teams = new List<string>();
To add items to a C# list, use the Add() method −
teams.Add("US");
teams.Add("Canada");
teams.Add("India");
teams.Add("Australia");
You can try to run the following code to add items to a list in C# −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var teams = new List<string>();
teams.Add("US");
teams.Add("Canada");
teams.Add("India");
teams.Add("Australia");
Console.WriteLine("Elements...");
foreach (var countries in teams) {
Console.WriteLine(countries);
}
}
} | [
{
"code": null,
"e": 1088,
"s": 1062,
"text": "Firstly, declare a list −"
},
{
"code": null,
"e": 1120,
"s": 1088,
"text": "var teams = new List<string>();"
},
{
"code": null,
"e": 1170,
"s": 1120,
"text": "To add items to a C# list, use the Add() method −"
},
{
"code": null,
"e": 1252,
"s": 1170,
"text": "teams.Add(\"US\");\nteams.Add(\"Canada\");\nteams.Add(\"India\");\nteams.Add(\"Australia\");"
},
{
"code": null,
"e": 1321,
"s": 1252,
"text": "You can try to run the following code to add items to a list in C# −"
},
{
"code": null,
"e": 1718,
"s": 1321,
"text": "using System;\nusing System.Collections.Generic;\n\npublic class Demo {\n public static void Main(string[] args) {\n\n var teams = new List<string>();\n teams.Add(\"US\");\n teams.Add(\"Canada\");\n teams.Add(\"India\");\n teams.Add(\"Australia\");\n \n Console.WriteLine(\"Elements...\");\n foreach (var countries in teams) {\n Console.WriteLine(countries);\n }\n }\n}"
}
] |
Dart Programming - ceil Method | This property returns the ceiling value, that is the smallest integer greater than or equal to a number.
Number.ceil()
void main() {
var a = 2.4;
print("The ceiling value of 2.4 = ${a.ceil()}");
}
It will produce the following output −.
The ceiling value of 2.4 = 3
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2630,
"s": 2525,
"text": "This property returns the ceiling value, that is the smallest integer greater than or equal to a number."
},
{
"code": null,
"e": 2645,
"s": 2630,
"text": "Number.ceil()\n"
},
{
"code": null,
"e": 2734,
"s": 2645,
"text": "void main() { \n var a = 2.4; \n print(\"The ceiling value of 2.4 = ${a.ceil()}\"); \n} "
},
{
"code": null,
"e": 2774,
"s": 2734,
"text": "It will produce the following output −."
},
{
"code": null,
"e": 2805,
"s": 2774,
"text": "The ceiling value of 2.4 = 3 \n"
},
{
"code": null,
"e": 2840,
"s": 2805,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2860,
"s": 2840,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 2893,
"s": 2860,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2913,
"s": 2893,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 2946,
"s": 2913,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2963,
"s": 2946,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2998,
"s": 2963,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3015,
"s": 2998,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3050,
"s": 3015,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3070,
"s": 3050,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3103,
"s": 3070,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3123,
"s": 3103,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3130,
"s": 3123,
"text": " Print"
},
{
"code": null,
"e": 3141,
"s": 3130,
"text": " Add Notes"
}
] |
The Modin view of Scaling Pandas. Comparing Modin with Dask, Ray, Vaex... | by Devin Petersohn | Towards Data Science | Recently, a blog post was written that compared a variety of tools in a set of head to heads. I wanted to take the opportunity to talk about our vision with Modin and where we’d like to take the field of data science.
Modin (https://github.com/modin-project/modin) takes a different view of how systems should be built. Modin is designed around enabling the data scientist to be more productive. When I created Modin as a PhD student in the RISELab at UC Berkeley, I noticed a dangerous trend: data science tools are being built with hardware performance in mind, but becoming more and more complex. This complexity and performance burden is being pushed onto the data scientist. These tools optimize for processor time at the cost of the data scientist’s time.
This trend is harmful to the overall field of data science: we don’t want to force every data scientist into becoming a distributed systems expert or require that they understand low-level implementation details to avoid getting punished by performance. Modin is disrupting the data science tooling space by prioritizing the data scientists time over hardware time. To this end, Modin has:
No upfront cost to learning a new APIIntegration with the Python ecosystemIntegration with Ray/Dask clusters (Run on/with what you have!)
No upfront cost to learning a new API
Integration with the Python ecosystem
Integration with Ray/Dask clusters (Run on/with what you have!)
Modin started as a drop-in replacement for Pandas, because that is where we saw the biggest need. Using Modin is as simple as pip install modin[ray] or pip install modin[dask] and then changing the import statement:
# import pandas as pdimport modin.pandas as pd
Modin is evolving into more than just a drop-in replacement for pandas (try latest version 0.7.4), and I will discuss this later in this post. First, I’d like to do a more detailed comparison of Modin vs. other libraries since many comparisons often leave out crucial information.
These systems aim to solve different problems, so fair comparisons are challenging. I will try to stick to the qualitative properties to avoid bias.
Dask Dataframe (https://github.com/dask/dask) covers roughly 40% of the Pandas API due to how the underlying system is architected. Dask Dataframe is a row store, like many SQL systems before it. However, dataframes are not SQL Tables. This architecture allows Dask Dataframe to scale extremely well, but prevents it from supporting all Pandas APIs. Dask Dataframe also places requirements on the user to add .compute() or .persist() calls into their data science workload to manage when compute is triggered. Users are also required to specify the number of partitions. Dask is more mature with >5 years since first commit.
Modin currently covers >80% of the Pandas API. Modin is architected as a flexible column store, so the partitioning within Modin can be changed based on the operation that needs to be computed. This allows Modin to scale algorithms that strict column or row stores could not. Modin also does not place any computation or partitioning burden onto the user. Optimizations on the user’s query are run under the hood, without input from the user. Modin is still in its infancy at 2 years since first commit.
Modin integrates with Dask’s scheduling API, so Modin can run on top of Dask clusters as well. More on this comparison here.
Vaex (https://github.com/vaexio/vaex) is a query engine on top of HDF5 and Arrow memory mapped files, so if your data is already in HDF5 format, it is a solid choice. Going from other file formats (CSV, JSON, Parquet) into a Vaex compatible format takes non-trivial compute time and disk space. Vaex can support roughly 35% of the Pandas API, and does not support key Pandas features like the Pandas row Index. Vaex has had nearly 6 years since the first commit.
As of writing, Modin relies on Pandas for its HDF5 file reader, and does not support the memory-mapped style of querying that Vaex supports. Modin scales to clusters, while Vaex tries to help users avoid the need for clusters with memory mapped files.
cuDF (https://github.com/rapidsai/cudf) is a dataframe library with a Pandas-like API that runs on NVIDIA GPUs. cuDF is bottlenecked by the amount of memory (up to 48GB), and spilling over to host memory comes with a high overhead. The performance you get on the GPU is great as long as the data reasonably fits into the GPU memory. You can use multiple GPUs with cuDF and Dask, and the resulting distributed GPU dataframe will have the same general properties outlined above in the Dask section. cuDF has had 3 years since the first commit.
As of writing, Modin does not have GPU support, but Modin’s architecture is layered, so Modin could integrate GPU kernels alongside CPU. Because of the flexibility of the underlying architecture Modin can even integrate hybrid CPU/GPU/*PU kernels. With this GPU support, we will need to ensure it is implemented in a way that allows users to avoid thinking about GPU memory constraints. More on this comparison here.
Modin is the data processing engine for Ray. Ray is a low-level distributed computing framework for scaling Python code, while Modin has higher level APIs for data manipulation and querying.
Modin has disrupted the interactive data science space, centering the discussion around data science productivity over benchmark performance. As Modin continues to mature, it is evolving into a platform for empowering data science at every scale. A few big features are coming at the end of July, with more later this year. I will discuss a couple of these features, if you’d like to find more, feel free to explore our future plans on the GitHub Issue tracker or ZenHub board.
One of the major difficulties that data scientists face is that they often must switch between Jupyter notebooks to run code on different clusters or environments. This becomes cumbersome when trying to debug code locally, so we have developed an API for switching between running code locally or on multiple different cloud or cluster environments with just one line of code. Note: this API may change, and is not yet available on the latest release (0.7.4). Feedback welcome!
import modinimport modin.pandas as pdtest_cluster = modin.cloud.create(provider="AWS", instance="m4.xlarge", numnodes=2)with modin.local(): # run this code locally df_local = pd.read_csv("a_file.csv") df_local.head()with modin.cloud.deploy(test_cluster): # run on my test cluster df_test = pd.read_csv("s3://bucket/a_file.csv") df_test.head()with modin.local(): df_local.count()with modin.cloud.deploy(test_cluster): df_test.count()with modin.cloud.deploy(production): # run this on production df_prod = ...
This works in standard Jupyter notebooks, or any python interpreter and enables data scientists to be more productive than ever in the context of a single notebook.
These APIs have been long requested and are being built out. This will integrate with the existing Pandas engine and avoid common bottlenecks in going to/from Modin’s dataframe and numpy or sklearn. As is the case with the Pandas API, they will be drop-in replacements as well.
import modin.pandas as pdimport modin.numpy as npfrom modin.sklearn.model_selection import train_test_split
As is the case with dataframes, Modin will be layered to integrate other technologies and compute kernels. We can integrate other computation engines or kernels, e.g. nums (another RISELab project).
Data scientists love their tools, and we love data scientists. Modin is designed around enabling the data scientist to be more productive with the tools that they love. We are working to shift the focus of data science tooling to value the data scientist’s time more than the time of the hardware they are using. | [
{
"code": null,
"e": 389,
"s": 171,
"text": "Recently, a blog post was written that compared a variety of tools in a set of head to heads. I wanted to take the opportunity to talk about our vision with Modin and where we’d like to take the field of data science."
},
{
"code": null,
"e": 933,
"s": 389,
"text": "Modin (https://github.com/modin-project/modin) takes a different view of how systems should be built. Modin is designed around enabling the data scientist to be more productive. When I created Modin as a PhD student in the RISELab at UC Berkeley, I noticed a dangerous trend: data science tools are being built with hardware performance in mind, but becoming more and more complex. This complexity and performance burden is being pushed onto the data scientist. These tools optimize for processor time at the cost of the data scientist’s time."
},
{
"code": null,
"e": 1323,
"s": 933,
"text": "This trend is harmful to the overall field of data science: we don’t want to force every data scientist into becoming a distributed systems expert or require that they understand low-level implementation details to avoid getting punished by performance. Modin is disrupting the data science tooling space by prioritizing the data scientists time over hardware time. To this end, Modin has:"
},
{
"code": null,
"e": 1461,
"s": 1323,
"text": "No upfront cost to learning a new APIIntegration with the Python ecosystemIntegration with Ray/Dask clusters (Run on/with what you have!)"
},
{
"code": null,
"e": 1499,
"s": 1461,
"text": "No upfront cost to learning a new API"
},
{
"code": null,
"e": 1537,
"s": 1499,
"text": "Integration with the Python ecosystem"
},
{
"code": null,
"e": 1601,
"s": 1537,
"text": "Integration with Ray/Dask clusters (Run on/with what you have!)"
},
{
"code": null,
"e": 1817,
"s": 1601,
"text": "Modin started as a drop-in replacement for Pandas, because that is where we saw the biggest need. Using Modin is as simple as pip install modin[ray] or pip install modin[dask] and then changing the import statement:"
},
{
"code": null,
"e": 1864,
"s": 1817,
"text": "# import pandas as pdimport modin.pandas as pd"
},
{
"code": null,
"e": 2145,
"s": 1864,
"text": "Modin is evolving into more than just a drop-in replacement for pandas (try latest version 0.7.4), and I will discuss this later in this post. First, I’d like to do a more detailed comparison of Modin vs. other libraries since many comparisons often leave out crucial information."
},
{
"code": null,
"e": 2294,
"s": 2145,
"text": "These systems aim to solve different problems, so fair comparisons are challenging. I will try to stick to the qualitative properties to avoid bias."
},
{
"code": null,
"e": 2919,
"s": 2294,
"text": "Dask Dataframe (https://github.com/dask/dask) covers roughly 40% of the Pandas API due to how the underlying system is architected. Dask Dataframe is a row store, like many SQL systems before it. However, dataframes are not SQL Tables. This architecture allows Dask Dataframe to scale extremely well, but prevents it from supporting all Pandas APIs. Dask Dataframe also places requirements on the user to add .compute() or .persist() calls into their data science workload to manage when compute is triggered. Users are also required to specify the number of partitions. Dask is more mature with >5 years since first commit."
},
{
"code": null,
"e": 3423,
"s": 2919,
"text": "Modin currently covers >80% of the Pandas API. Modin is architected as a flexible column store, so the partitioning within Modin can be changed based on the operation that needs to be computed. This allows Modin to scale algorithms that strict column or row stores could not. Modin also does not place any computation or partitioning burden onto the user. Optimizations on the user’s query are run under the hood, without input from the user. Modin is still in its infancy at 2 years since first commit."
},
{
"code": null,
"e": 3548,
"s": 3423,
"text": "Modin integrates with Dask’s scheduling API, so Modin can run on top of Dask clusters as well. More on this comparison here."
},
{
"code": null,
"e": 4011,
"s": 3548,
"text": "Vaex (https://github.com/vaexio/vaex) is a query engine on top of HDF5 and Arrow memory mapped files, so if your data is already in HDF5 format, it is a solid choice. Going from other file formats (CSV, JSON, Parquet) into a Vaex compatible format takes non-trivial compute time and disk space. Vaex can support roughly 35% of the Pandas API, and does not support key Pandas features like the Pandas row Index. Vaex has had nearly 6 years since the first commit."
},
{
"code": null,
"e": 4263,
"s": 4011,
"text": "As of writing, Modin relies on Pandas for its HDF5 file reader, and does not support the memory-mapped style of querying that Vaex supports. Modin scales to clusters, while Vaex tries to help users avoid the need for clusters with memory mapped files."
},
{
"code": null,
"e": 4805,
"s": 4263,
"text": "cuDF (https://github.com/rapidsai/cudf) is a dataframe library with a Pandas-like API that runs on NVIDIA GPUs. cuDF is bottlenecked by the amount of memory (up to 48GB), and spilling over to host memory comes with a high overhead. The performance you get on the GPU is great as long as the data reasonably fits into the GPU memory. You can use multiple GPUs with cuDF and Dask, and the resulting distributed GPU dataframe will have the same general properties outlined above in the Dask section. cuDF has had 3 years since the first commit."
},
{
"code": null,
"e": 5222,
"s": 4805,
"text": "As of writing, Modin does not have GPU support, but Modin’s architecture is layered, so Modin could integrate GPU kernels alongside CPU. Because of the flexibility of the underlying architecture Modin can even integrate hybrid CPU/GPU/*PU kernels. With this GPU support, we will need to ensure it is implemented in a way that allows users to avoid thinking about GPU memory constraints. More on this comparison here."
},
{
"code": null,
"e": 5413,
"s": 5222,
"text": "Modin is the data processing engine for Ray. Ray is a low-level distributed computing framework for scaling Python code, while Modin has higher level APIs for data manipulation and querying."
},
{
"code": null,
"e": 5891,
"s": 5413,
"text": "Modin has disrupted the interactive data science space, centering the discussion around data science productivity over benchmark performance. As Modin continues to mature, it is evolving into a platform for empowering data science at every scale. A few big features are coming at the end of July, with more later this year. I will discuss a couple of these features, if you’d like to find more, feel free to explore our future plans on the GitHub Issue tracker or ZenHub board."
},
{
"code": null,
"e": 6369,
"s": 5891,
"text": "One of the major difficulties that data scientists face is that they often must switch between Jupyter notebooks to run code on different clusters or environments. This becomes cumbersome when trying to debug code locally, so we have developed an API for switching between running code locally or on multiple different cloud or cluster environments with just one line of code. Note: this API may change, and is not yet available on the latest release (0.7.4). Feedback welcome!"
},
{
"code": null,
"e": 6969,
"s": 6369,
"text": "import modinimport modin.pandas as pdtest_cluster = modin.cloud.create(provider=\"AWS\", instance=\"m4.xlarge\", numnodes=2)with modin.local(): # run this code locally df_local = pd.read_csv(\"a_file.csv\") df_local.head()with modin.cloud.deploy(test_cluster): # run on my test cluster df_test = pd.read_csv(\"s3://bucket/a_file.csv\") df_test.head()with modin.local(): df_local.count()with modin.cloud.deploy(test_cluster): df_test.count()with modin.cloud.deploy(production): # run this on production df_prod = ..."
},
{
"code": null,
"e": 7134,
"s": 6969,
"text": "This works in standard Jupyter notebooks, or any python interpreter and enables data scientists to be more productive than ever in the context of a single notebook."
},
{
"code": null,
"e": 7412,
"s": 7134,
"text": "These APIs have been long requested and are being built out. This will integrate with the existing Pandas engine and avoid common bottlenecks in going to/from Modin’s dataframe and numpy or sklearn. As is the case with the Pandas API, they will be drop-in replacements as well."
},
{
"code": null,
"e": 7520,
"s": 7412,
"text": "import modin.pandas as pdimport modin.numpy as npfrom modin.sklearn.model_selection import train_test_split"
},
{
"code": null,
"e": 7719,
"s": 7520,
"text": "As is the case with dataframes, Modin will be layered to integrate other technologies and compute kernels. We can integrate other computation engines or kernels, e.g. nums (another RISELab project)."
}
] |
A Complete Guide to Learn XML For Android App Development - GeeksforGeeks | 23 Jul, 2021
XML stands for Extensible Markup Language. XML is a markup language much like HTML used to describe data. It is derived from Standard Generalized Markup Language(SMGL). Basically, the XML tags are not predefined in XML. We need to implement and define the tags in XML. XML tags define the data and used to store and organize data. It’s easily scalable and simple to develop. In Android, the XML is used to implement UI-related data, and it’s a lightweight markup language that doesn’t make layout heavy. XML only contains tags, while implementing they need to be just invoked.
The simple syntax of XML is
<tag_name>Hello World!</tag_name>
So in this article, there is a deep discussion on how to learn and understand what XML is for Android Development.
Basically in Android XML is used to implement the UI-related data. So understanding the core part of the UI interface with respect to XML is important. The User Interface for an Android App is built as the hierarchy of main layouts, widgets. The layouts are ViewGroup objects or containers that control how the child view should be positioned on the screen. Widgets here are view objects, such as Buttons and text boxes. Considering the following simple example of the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!--ViewGroup1--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:orientation="vertical" android:padding="24dp" tools:context=".MainActivity"> <!--TextView1 widget inside ViewGroup1--> <TextView style="@style/TextAppearance.MaterialComponents.Headline5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GEEKSFORGEEKS" android:textColor="@color/green_500" /> <!--TextView2 widget inside ViewGroup1--> <TextView style="@style/TextAppearance.MaterialComponents.Headline6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Enter the user information" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--ViewGroup2--> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:clipToPadding="false"> <!--EditText1 widget inside ViewGroup2--> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter first name" /> <!--EditText2 widget inside ViewGroup2--> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editText1" android:hint="Enter last name" /> <!--Button widget inside ViewGroup2--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/editText2" android:layout_alignParentEnd="true" android:text="Submit" /> </RelativeLayout><!--End of ViewGroup2--> </LinearLayout><!--End of ViewGroup1-->
Output UI:
In the above example of XML file, There are 2 view groups one is LinearLayout and another is RelativeLayout and the TextView1 and TextView2 is child widgets under the ViewGroup1 that is LinearLayout. EditText1, EditText2, and Button are the child widgets under ViewGroup2 that is RelativeLayout. ViewGroup2(RelativeLayout) is nested under the ViewGroup1 which produces the following hierarchy.
From the hierarchy, it’s been observed that every widget like EdtText, TextView, or Button is one of the View. These Views are contained inside the ViewGroup, like RelativeLayout, LinearLayout, FrameLayout, etc.
Different XML files serve different purposes in Android Studio. The list of various XML files in Android Studio with their purposes is discussed below.
1. Layout XML files in android
The Layout XML files are responsible for the actual User Interface of the application. It holds all the widgets or views like Buttons, TextViews, EditTexts, etc. which are defined under the ViewGroups. The Location of the layout files in Android is:
app -> src -> main -> res -> layout
The folder contains the layout files for respective activity, fragments. The basic layout of the is as follows for activity_main.xml:
XML
<?xml version="1.0" encoding="utf-8"?><!--ViewGroup1--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:orientation="vertical" android:padding="24dp" tools:context=".MainActivity"> <!--TextView1 widget inside ViewGroup1--> <TextView style="@style/TextAppearance.MaterialComponents.Headline5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GEEKSFORGEEKS" android:textColor="@color/green_500" /> <!--TextView2 widget inside ViewGroup1--> <TextView style="@style/TextAppearance.MaterialComponents.Headline6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Enter the user information" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--ViewGroup2--> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:clipToPadding="false"> <!--EditText1 widget inside ViewGroup2--> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter first name" /> <!--EditText2 widget inside ViewGroup2--> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editText1" android:hint="Enter last name" /> <!--Button widget inside ViewGroup2--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/editText2" android:layout_alignParentEnd="true" android:text="Submit" /> </RelativeLayout><!--End of ViewGroup2--> </LinearLayout><!--End of ViewGroup1-->
2. AndroidManifest.xml file
This file describes the essential information about the application’s, like the application’s package names which matches code’s namespaces, a component of the application like activities, services, broadcast receivers, and content providers. Permission required by the user for the application features also mentioned in this XML file. Location of the AndroidManifest.xml file:
app -> src -> main
A typical code inside AndroidManifest.xml with internet permission looks like this:
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.adityamshidlyali.gfgarticle"> <!--internet permission from the user--> <uses-permission android:name="ANDROID.PERMISSION.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.GFGArticle"> <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>
3. strings.xml file
This file contains texts for all the TextViews widgets. This enables reusability of code, and also helps in the localization of the application with different languages. The strings defined in these files can be used to replace all hardcoded text in the entire application. Location of the strings.xml file
app -> src -> main -> res -> values
A typical code inside strings.xml looks like this:
XML
<resources> <string name="app_name">GFG Article</string> <string name="gfg_heading">GEEKSFORGEEKS</string> <string name="settings_label">settings</string></resources>
4. themes.xml file
This file defines the base theme and customized themes of the application. It also used to define styles and looks for the UI(User Interface) of the application. By defining styles we can customize how the views or widgets look on the User Interface. Location of styles.xml file
app -> src -> main -> res -> values
A typical code inside themes.xml looks like this:
XML
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.GFGArticle" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/green_500</item> <item name="colorPrimaryVariant">@color/green_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>
5. Drawable XML files
These are the XML files that provide graphics to elements like custom background for the buttons and its ripple effects, also various gradients can be created. This also holds the vector graphics like icons. Using these files custom layouts can be constructed for EditTexts. Location for the Drawable files are:
app -> src -> main -> res -> drawable
A typical code inside my_custom_gradient.xml looks like this:
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:centerColor="@color/green_500" android:endColor="@color/green_700" android:startColor="@color/green_200" /></shape>
which produces the following gradient effect:
6. colors.xml file
The colors.xml file is responsible to hold all the types of colors required for the application. It may be primary brand color and its variants and secondary brand color and its variants. The colors help uphold the brand of the applications. So the colors need to be decided cautiously as they are responsible for the User Experience. The colors need to be defined in the hex code format. Location of colors.xml file:
app -> src -> main -> res -> values
A typical code inside custom.xml looks like this:
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="purple_200">#FFBB86FC</color> <color name="purple_500">#FF6200EE</color> <color name="purple_700">#FF3700B3</color> <color name="teal_200">#FF03DAC5</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <!--custom colors--> <color name="green_200">#55cf86</color> <color name="green_500">#0f9d58</color> <color name="green_700">#006d2d</color></resources>
7. dimens.xml file
As the file name itself suggests that the file is responsible to hold the entire dimensions for the views. it may be the height of the Button, padding of the views, the margin for the views, etc. The dimensions need to in the format of pixel density(dp) values. Which replaces all the hard-coded dp values for the views. This file needs to be created separately in the values folder. Location to create dimens.xml file:
app -> src -> main -> res -> values
A typical code inside dimens.xml looks like this:
XML
<?xml version="1.0" encoding="utf-8"?><resources> <dimen name="button_height">58dp</dimen> <dimen name="default_start_margin">16dp</dimen> <dimen name="default_end_margin">16dp</dimen> <dimen name="card_view_elevation">12dp</dimen></resources>
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
How to Get Current Location in Android?
Fragment Lifecycle in Android
Difference Between a Fragment and an Activity in Android | [
{
"code": null,
"e": 26515,
"s": 26487,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 27093,
"s": 26515,
"text": "XML stands for Extensible Markup Language. XML is a markup language much like HTML used to describe data. It is derived from Standard Generalized Markup Language(SMGL). Basically, the XML tags are not predefined in XML. We need to implement and define the tags in XML. XML tags define the data and used to store and organize data. It’s easily scalable and simple to develop. In Android, the XML is used to implement UI-related data, and it’s a lightweight markup language that doesn’t make layout heavy. XML only contains tags, while implementing they need to be just invoked. "
},
{
"code": null,
"e": 27122,
"s": 27093,
"text": "The simple syntax of XML is "
},
{
"code": null,
"e": 27156,
"s": 27122,
"text": "<tag_name>Hello World!</tag_name>"
},
{
"code": null,
"e": 27271,
"s": 27156,
"text": "So in this article, there is a deep discussion on how to learn and understand what XML is for Android Development."
},
{
"code": null,
"e": 27764,
"s": 27271,
"text": "Basically in Android XML is used to implement the UI-related data. So understanding the core part of the UI interface with respect to XML is important. The User Interface for an Android App is built as the hierarchy of main layouts, widgets. The layouts are ViewGroup objects or containers that control how the child view should be positioned on the screen. Widgets here are view objects, such as Buttons and text boxes. Considering the following simple example of the activity_main.xml file."
},
{
"code": null,
"e": 27768,
"s": 27764,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--ViewGroup1--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:clipToPadding=\"false\" android:orientation=\"vertical\" android:padding=\"24dp\" tools:context=\".MainActivity\"> <!--TextView1 widget inside ViewGroup1--> <TextView style=\"@style/TextAppearance.MaterialComponents.Headline5\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GEEKSFORGEEKS\" android:textColor=\"@color/green_500\" /> <!--TextView2 widget inside ViewGroup1--> <TextView style=\"@style/TextAppearance.MaterialComponents.Headline6\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Enter the user information\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--ViewGroup2--> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"8dp\" android:clipToPadding=\"false\"> <!--EditText1 widget inside ViewGroup2--> <EditText android:id=\"@+id/editText1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter first name\" /> <!--EditText2 widget inside ViewGroup2--> <EditText android:id=\"@+id/editText2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/editText1\" android:hint=\"Enter last name\" /> <!--Button widget inside ViewGroup2--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/editText2\" android:layout_alignParentEnd=\"true\" android:text=\"Submit\" /> </RelativeLayout><!--End of ViewGroup2--> </LinearLayout><!--End of ViewGroup1-->",
"e": 30145,
"s": 27768,
"text": null
},
{
"code": null,
"e": 30156,
"s": 30145,
"text": "Output UI:"
},
{
"code": null,
"e": 30550,
"s": 30156,
"text": "In the above example of XML file, There are 2 view groups one is LinearLayout and another is RelativeLayout and the TextView1 and TextView2 is child widgets under the ViewGroup1 that is LinearLayout. EditText1, EditText2, and Button are the child widgets under ViewGroup2 that is RelativeLayout. ViewGroup2(RelativeLayout) is nested under the ViewGroup1 which produces the following hierarchy."
},
{
"code": null,
"e": 30762,
"s": 30550,
"text": "From the hierarchy, it’s been observed that every widget like EdtText, TextView, or Button is one of the View. These Views are contained inside the ViewGroup, like RelativeLayout, LinearLayout, FrameLayout, etc."
},
{
"code": null,
"e": 30914,
"s": 30762,
"text": "Different XML files serve different purposes in Android Studio. The list of various XML files in Android Studio with their purposes is discussed below."
},
{
"code": null,
"e": 30945,
"s": 30914,
"text": "1. Layout XML files in android"
},
{
"code": null,
"e": 31195,
"s": 30945,
"text": "The Layout XML files are responsible for the actual User Interface of the application. It holds all the widgets or views like Buttons, TextViews, EditTexts, etc. which are defined under the ViewGroups. The Location of the layout files in Android is:"
},
{
"code": null,
"e": 31231,
"s": 31195,
"text": "app -> src -> main -> res -> layout"
},
{
"code": null,
"e": 31365,
"s": 31231,
"text": "The folder contains the layout files for respective activity, fragments. The basic layout of the is as follows for activity_main.xml:"
},
{
"code": null,
"e": 31369,
"s": 31365,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--ViewGroup1--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:clipToPadding=\"false\" android:orientation=\"vertical\" android:padding=\"24dp\" tools:context=\".MainActivity\"> <!--TextView1 widget inside ViewGroup1--> <TextView style=\"@style/TextAppearance.MaterialComponents.Headline5\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GEEKSFORGEEKS\" android:textColor=\"@color/green_500\" /> <!--TextView2 widget inside ViewGroup1--> <TextView style=\"@style/TextAppearance.MaterialComponents.Headline6\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Enter the user information\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--ViewGroup2--> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"8dp\" android:clipToPadding=\"false\"> <!--EditText1 widget inside ViewGroup2--> <EditText android:id=\"@+id/editText1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter first name\" /> <!--EditText2 widget inside ViewGroup2--> <EditText android:id=\"@+id/editText2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/editText1\" android:hint=\"Enter last name\" /> <!--Button widget inside ViewGroup2--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/editText2\" android:layout_alignParentEnd=\"true\" android:text=\"Submit\" /> </RelativeLayout><!--End of ViewGroup2--> </LinearLayout><!--End of ViewGroup1-->",
"e": 33746,
"s": 31369,
"text": null
},
{
"code": null,
"e": 33774,
"s": 33746,
"text": "2. AndroidManifest.xml file"
},
{
"code": null,
"e": 34153,
"s": 33774,
"text": "This file describes the essential information about the application’s, like the application’s package names which matches code’s namespaces, a component of the application like activities, services, broadcast receivers, and content providers. Permission required by the user for the application features also mentioned in this XML file. Location of the AndroidManifest.xml file:"
},
{
"code": null,
"e": 34172,
"s": 34153,
"text": "app -> src -> main"
},
{
"code": null,
"e": 34256,
"s": 34172,
"text": "A typical code inside AndroidManifest.xml with internet permission looks like this:"
},
{
"code": null,
"e": 34260,
"s": 34256,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.adityamshidlyali.gfgarticle\"> <!--internet permission from the user--> <uses-permission android:name=\"ANDROID.PERMISSION.INTERNET\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.GFGArticle\"> <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": 35092,
"s": 34260,
"text": null
},
{
"code": null,
"e": 35112,
"s": 35092,
"text": "3. strings.xml file"
},
{
"code": null,
"e": 35419,
"s": 35112,
"text": "This file contains texts for all the TextViews widgets. This enables reusability of code, and also helps in the localization of the application with different languages. The strings defined in these files can be used to replace all hardcoded text in the entire application. Location of the strings.xml file"
},
{
"code": null,
"e": 35455,
"s": 35419,
"text": "app -> src -> main -> res -> values"
},
{
"code": null,
"e": 35506,
"s": 35455,
"text": "A typical code inside strings.xml looks like this:"
},
{
"code": null,
"e": 35510,
"s": 35506,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GFG Article</string> <string name=\"gfg_heading\">GEEKSFORGEEKS</string> <string name=\"settings_label\">settings</string></resources>",
"e": 35686,
"s": 35510,
"text": null
},
{
"code": null,
"e": 35705,
"s": 35686,
"text": "4. themes.xml file"
},
{
"code": null,
"e": 35984,
"s": 35705,
"text": "This file defines the base theme and customized themes of the application. It also used to define styles and looks for the UI(User Interface) of the application. By defining styles we can customize how the views or widgets look on the User Interface. Location of styles.xml file"
},
{
"code": null,
"e": 36020,
"s": 35984,
"text": "app -> src -> main -> res -> values"
},
{
"code": null,
"e": 36070,
"s": 36020,
"text": "A typical code inside themes.xml looks like this:"
},
{
"code": null,
"e": 36074,
"s": 36070,
"text": "XML"
},
{
"code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.GFGArticle\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/green_500</item> <item name=\"colorPrimaryVariant\">@color/green_700</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>",
"e": 36890,
"s": 36074,
"text": null
},
{
"code": null,
"e": 36912,
"s": 36890,
"text": "5. Drawable XML files"
},
{
"code": null,
"e": 37224,
"s": 36912,
"text": "These are the XML files that provide graphics to elements like custom background for the buttons and its ripple effects, also various gradients can be created. This also holds the vector graphics like icons. Using these files custom layouts can be constructed for EditTexts. Location for the Drawable files are:"
},
{
"code": null,
"e": 37262,
"s": 37224,
"text": "app -> src -> main -> res -> drawable"
},
{
"code": null,
"e": 37324,
"s": 37262,
"text": "A typical code inside my_custom_gradient.xml looks like this:"
},
{
"code": null,
"e": 37328,
"s": 37324,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\"> <gradient android:centerColor=\"@color/green_500\" android:endColor=\"@color/green_700\" android:startColor=\"@color/green_200\" /></shape>",
"e": 37591,
"s": 37328,
"text": null
},
{
"code": null,
"e": 37637,
"s": 37591,
"text": "which produces the following gradient effect:"
},
{
"code": null,
"e": 37656,
"s": 37637,
"text": "6. colors.xml file"
},
{
"code": null,
"e": 38074,
"s": 37656,
"text": "The colors.xml file is responsible to hold all the types of colors required for the application. It may be primary brand color and its variants and secondary brand color and its variants. The colors help uphold the brand of the applications. So the colors need to be decided cautiously as they are responsible for the User Experience. The colors need to be defined in the hex code format. Location of colors.xml file:"
},
{
"code": null,
"e": 38110,
"s": 38074,
"text": "app -> src -> main -> res -> values"
},
{
"code": null,
"e": 38160,
"s": 38110,
"text": "A typical code inside custom.xml looks like this:"
},
{
"code": null,
"e": 38164,
"s": 38160,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"purple_200\">#FFBB86FC</color> <color name=\"purple_500\">#FF6200EE</color> <color name=\"purple_700\">#FF3700B3</color> <color name=\"teal_200\">#FF03DAC5</color> <color name=\"teal_700\">#FF018786</color> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color> <!--custom colors--> <color name=\"green_200\">#55cf86</color> <color name=\"green_500\">#0f9d58</color> <color name=\"green_700\">#006d2d</color></resources>",
"e": 38689,
"s": 38164,
"text": null
},
{
"code": null,
"e": 38708,
"s": 38689,
"text": "7. dimens.xml file"
},
{
"code": null,
"e": 39128,
"s": 38708,
"text": "As the file name itself suggests that the file is responsible to hold the entire dimensions for the views. it may be the height of the Button, padding of the views, the margin for the views, etc. The dimensions need to in the format of pixel density(dp) values. Which replaces all the hard-coded dp values for the views. This file needs to be created separately in the values folder. Location to create dimens.xml file:"
},
{
"code": null,
"e": 39164,
"s": 39128,
"text": "app -> src -> main -> res -> values"
},
{
"code": null,
"e": 39214,
"s": 39164,
"text": "A typical code inside dimens.xml looks like this:"
},
{
"code": null,
"e": 39218,
"s": 39214,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <dimen name=\"button_height\">58dp</dimen> <dimen name=\"default_start_margin\">16dp</dimen> <dimen name=\"default_end_margin\">16dp</dimen> <dimen name=\"card_view_elevation\">12dp</dimen></resources>",
"e": 39474,
"s": 39218,
"text": null
},
{
"code": null,
"e": 39482,
"s": 39474,
"text": "Android"
},
{
"code": null,
"e": 39490,
"s": 39482,
"text": "Android"
},
{
"code": null,
"e": 39588,
"s": 39490,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39626,
"s": 39588,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 39665,
"s": 39626,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 39715,
"s": 39665,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 39741,
"s": 39715,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 39783,
"s": 39741,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 39834,
"s": 39783,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 39872,
"s": 39834,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 39912,
"s": 39872,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 39942,
"s": 39912,
"text": "Fragment Lifecycle in Android"
}
] |
Directi Interview Questions - GeeksforGeeks | 09 Aug, 2019
I took Coding Round 1 of Direct I campus recruitment today. Sharing the 2 questions which have been asked.
Question 1 (Optimal substring reversal):You are given a string S. Each character of S is either ‘a’, or ‘b’. You wish to reverse exactly one sub-string of S such that the new string is lexicographically smaller than all the other strings that you can get by reversing exactly one sub-string.For example, given ‘abab’, you may choose to reverse the substring ‘ab’ that starts from index 2 (0-based). This gives you the string ‘abba’. But, if you choose the reverse the substring ‘ba’ starting from index 1, you will get ‘aabb’. There is no way of getting a smaller string, hence reversing the substring in the range [1, 2] is optimal.
Input:First line contains a number T, the number of test cases.Each test case contains a single string S. The characters of the string will be from the set { a, b }.
Output:For each test case, print two numbers separated by comma; for example “x,y” (without the quotes and without any additional whitespace). “x,y” describe the starting index (0-based) and ending index respectively of the substring that must be reversed in order to achieve the smallest lexicographical string. If there are multiple possible answers, print the one with the smallest ‘x’. If there are still multiple answers possible, print the one with the smallest ‘y’.
Constraints:1 ? T ? 1001 ? length of S ? 1000
Sample Input:
5
abab
abba
bbaa
aaaa
babaabba
Sample Output:
1,2
1,3
0,3
0,0
0,4
Attention:The constraints are designed such that an O(N3) algorithm per test case, would not pass.
Question 2 (Database Queries): 2 pointsYou have a set of N objects. Each of these objects has certain properties associated with them. A property is represented by a (key, value) pair. For example, assume you have the following two objects.
Tower:
{
(height, 100), (weight, 50),
(xposition, 25), (yposition, 36)
}
Tree:
{
(area, 100), (noofleaves, 500),
(height, 25), (yposition, 36)
}
Each object you have will have at most 4 properties. An object will have at least 1 property. Note, from the two objects above, that it is not necessary for key in the properties to be the same for all the objects. Also, it is not necessary for the key to be different.Now, given N such objects, you wish to answer M queries. Each query is represented by a set of properties (again, at most 4 properties, and at least 1 property). The answer for the query is the number of objects in the set, that have all the given properties. Two properties are considered equal iff both the key and the value match.For example, if you have the above two objects, then the answer for the following queries isQuery: { (height, 100), (yposition, 36) }Answer: 1 // matches Tower, but not Tree
Query: { (yposition, 36) }Answer: 2 // matches both Tower and Tree
Query: { (height, 100), (noofleaves, 500) }Answer: 0 // neither Tower, not Tree satisfy both properties
Input:The first line of input contains N and M. This is followed by the description of the N objects. The description of the i-th object will start by a number k, which is the number of properties associated with the object. The next k lines contain two space-separated strings – the property key and the property value. Note that the property value is not necessarily an integer (although this is so for the example above).This is followed by the description of M queries. The format of a query will be exactly the same to that of the objects. Check the Sample Input for clarification.One test file will contain only one test case. A single test case may contain several queries.
Output:Print M lines. Each line must be the answer of the respective query.
Constraints:1 ? N ? 100001 ? M ? 1000001 ? k ? 4
Sample Input
2 3
4
height 100a
weight 50b
xposition 25a
yposition 36b
4
area 100a
noofleaves 500
height 25
yposition 36b
3
weight 80
xposition 25a
yposition 36b
1
yposition 36b
2
xposition 25a
yposition 36b
Sample Output:
0
2
1
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Directi
Interview Experiences
Directi
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Zoho Interview | Set 3 (Off-Campus)
Amazon Interview Experience
Amazon Interview Experience for SDE-1
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience (Off-Campus) 2022
Directi Interview | Set 7 (Programming Questions)
Amazon Interview Experience for SDE-1 (On-Campus) | [
{
"code": null,
"e": 25949,
"s": 25921,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 26056,
"s": 25949,
"text": "I took Coding Round 1 of Direct I campus recruitment today. Sharing the 2 questions which have been asked."
},
{
"code": null,
"e": 26690,
"s": 26056,
"text": "Question 1 (Optimal substring reversal):You are given a string S. Each character of S is either ‘a’, or ‘b’. You wish to reverse exactly one sub-string of S such that the new string is lexicographically smaller than all the other strings that you can get by reversing exactly one sub-string.For example, given ‘abab’, you may choose to reverse the substring ‘ab’ that starts from index 2 (0-based). This gives you the string ‘abba’. But, if you choose the reverse the substring ‘ba’ starting from index 1, you will get ‘aabb’. There is no way of getting a smaller string, hence reversing the substring in the range [1, 2] is optimal."
},
{
"code": null,
"e": 26856,
"s": 26690,
"text": "Input:First line contains a number T, the number of test cases.Each test case contains a single string S. The characters of the string will be from the set { a, b }."
},
{
"code": null,
"e": 27329,
"s": 26856,
"text": "Output:For each test case, print two numbers separated by comma; for example “x,y” (without the quotes and without any additional whitespace). “x,y” describe the starting index (0-based) and ending index respectively of the substring that must be reversed in order to achieve the smallest lexicographical string. If there are multiple possible answers, print the one with the smallest ‘x’. If there are still multiple answers possible, print the one with the smallest ‘y’."
},
{
"code": null,
"e": 27375,
"s": 27329,
"text": "Constraints:1 ? T ? 1001 ? length of S ? 1000"
},
{
"code": null,
"e": 27457,
"s": 27375,
"text": "Sample Input:\n5\nabab\nabba\nbbaa\naaaa\nbabaabba\n\nSample Output:\n1,2\n1,3\n0,3\n0,0\n0,4 "
},
{
"code": null,
"e": 27556,
"s": 27457,
"text": "Attention:The constraints are designed such that an O(N3) algorithm per test case, would not pass."
},
{
"code": null,
"e": 27797,
"s": 27556,
"text": "Question 2 (Database Queries): 2 pointsYou have a set of N objects. Each of these objects has certain properties associated with them. A property is represented by a (key, value) pair. For example, assume you have the following two objects."
},
{
"code": null,
"e": 27967,
"s": 27797,
"text": "Tower:\n{\n (height, 100), (weight, 50),\n (xposition, 25), (yposition, 36)\n}\n\nTree:\n{\n (area, 100), (noofleaves, 500),\n (height, 25), (yposition, 36)\n}"
},
{
"code": null,
"e": 28743,
"s": 27967,
"text": "Each object you have will have at most 4 properties. An object will have at least 1 property. Note, from the two objects above, that it is not necessary for key in the properties to be the same for all the objects. Also, it is not necessary for the key to be different.Now, given N such objects, you wish to answer M queries. Each query is represented by a set of properties (again, at most 4 properties, and at least 1 property). The answer for the query is the number of objects in the set, that have all the given properties. Two properties are considered equal iff both the key and the value match.For example, if you have the above two objects, then the answer for the following queries isQuery: { (height, 100), (yposition, 36) }Answer: 1 // matches Tower, but not Tree"
},
{
"code": null,
"e": 28810,
"s": 28743,
"text": "Query: { (yposition, 36) }Answer: 2 // matches both Tower and Tree"
},
{
"code": null,
"e": 28914,
"s": 28810,
"text": "Query: { (height, 100), (noofleaves, 500) }Answer: 0 // neither Tower, not Tree satisfy both properties"
},
{
"code": null,
"e": 29595,
"s": 28914,
"text": "Input:The first line of input contains N and M. This is followed by the description of the N objects. The description of the i-th object will start by a number k, which is the number of properties associated with the object. The next k lines contain two space-separated strings – the property key and the property value. Note that the property value is not necessarily an integer (although this is so for the example above).This is followed by the description of M queries. The format of a query will be exactly the same to that of the objects. Check the Sample Input for clarification.One test file will contain only one test case. A single test case may contain several queries."
},
{
"code": null,
"e": 29671,
"s": 29595,
"text": "Output:Print M lines. Each line must be the answer of the respective query."
},
{
"code": null,
"e": 29720,
"s": 29671,
"text": "Constraints:1 ? N ? 100001 ? M ? 1000001 ? k ? 4"
},
{
"code": null,
"e": 29953,
"s": 29720,
"text": "Sample Input\n2 3\n4\nheight 100a\nweight 50b\nxposition 25a\nyposition 36b\n\n4\narea 100a\nnoofleaves 500\nheight 25\nyposition 36b\n\n3\nweight 80\nxposition 25a\nyposition 36b\n\n1\nyposition 36b\n\n2\nxposition 25a\nyposition 36b\n\nSample Output:\n0\n2\n1"
},
{
"code": null,
"e": 30174,
"s": 29953,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30182,
"s": 30174,
"text": "Directi"
},
{
"code": null,
"e": 30204,
"s": 30182,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30212,
"s": 30204,
"text": "Directi"
},
{
"code": null,
"e": 30310,
"s": 30212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30361,
"s": 30310,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 30403,
"s": 30361,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 30439,
"s": 30403,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 30475,
"s": 30439,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 30503,
"s": 30475,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 30541,
"s": 30503,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30613,
"s": 30541,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 30659,
"s": 30613,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 30709,
"s": 30659,
"text": "Directi Interview | Set 7 (Programming Questions)"
}
] |
HTML <center> Tag - GeeksforGeeks | 17 Mar, 2022
The <center> tag in HTML is used to set the alignment of text into the center. This tag is not supported in HTML5. CSS’s property is used to set the alignment of the element instead of the center tag in HTML5.
Syntax:
<center> Contents... </center>
Attributes: This tag dos not accept any attribute.
Example 1: In this example, we simply used the Hi Geeks content in the HTML center tag.
HTML
<!DOCTYPE html><html> <body> <h2>Welcome to GeeksforGeeks</h2> <!--center tag is used here--> <center>Hi Geeks</center> </body> </html>
Output:
HTML <center> tag
Example 2: This example illustrates the HTML center tag.
HTML
<!DOCTYPE html><html> <body> <!--center tag starts here --> <center> <h1>GeeksforGeeks</h1> <h2><center> tag</h2> <p>GeeksforGeeks: A computer science portal for geeks</p> <!--center tag ends here --> </center> </body></html>
Output:
HTML <center> tag
Example 3: Use CSS property in HTML5 to set the text alignment into the center.
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <!--center using CSS style --> <h2 style="text-align: center"> CSS center property </h2> </body></html>
Output:
HTML <center> tag
Supported Browsers:
Google Chrome
Microsoft Edge 12 and above
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
arorakashish0911
shubhamyadav4
bhaskargeeksforgeeks
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript | [
{
"code": null,
"e": 23003,
"s": 22975,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 23213,
"s": 23003,
"text": "The <center> tag in HTML is used to set the alignment of text into the center. This tag is not supported in HTML5. CSS’s property is used to set the alignment of the element instead of the center tag in HTML5."
},
{
"code": null,
"e": 23221,
"s": 23213,
"text": "Syntax:"
},
{
"code": null,
"e": 23252,
"s": 23221,
"text": "<center> Contents... </center>"
},
{
"code": null,
"e": 23303,
"s": 23252,
"text": "Attributes: This tag dos not accept any attribute."
},
{
"code": null,
"e": 23391,
"s": 23303,
"text": "Example 1: In this example, we simply used the Hi Geeks content in the HTML center tag."
},
{
"code": null,
"e": 23396,
"s": 23391,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome to GeeksforGeeks</h2> <!--center tag is used here--> <center>Hi Geeks</center> </body> </html>",
"e": 23544,
"s": 23396,
"text": null
},
{
"code": null,
"e": 23552,
"s": 23544,
"text": "Output:"
},
{
"code": null,
"e": 23570,
"s": 23552,
"text": "HTML <center> tag"
},
{
"code": null,
"e": 23628,
"s": 23570,
"text": "Example 2: This example illustrates the HTML center tag. "
},
{
"code": null,
"e": 23633,
"s": 23628,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <!--center tag starts here --> <center> <h1>GeeksforGeeks</h1> <h2><center> tag</h2> <p>GeeksforGeeks: A computer science portal for geeks</p> <!--center tag ends here --> </center> </body></html>",
"e": 23890,
"s": 23633,
"text": null
},
{
"code": null,
"e": 23898,
"s": 23890,
"text": "Output:"
},
{
"code": null,
"e": 23916,
"s": 23898,
"text": "HTML <center> tag"
},
{
"code": null,
"e": 23997,
"s": 23916,
"text": "Example 3: Use CSS property in HTML5 to set the text alignment into the center. "
},
{
"code": null,
"e": 24002,
"s": 23997,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <!--center using CSS style --> <h2 style=\"text-align: center\"> CSS center property </h2> </body></html>",
"e": 24178,
"s": 24002,
"text": null
},
{
"code": null,
"e": 24186,
"s": 24178,
"text": "Output:"
},
{
"code": null,
"e": 24204,
"s": 24186,
"text": "HTML <center> tag"
},
{
"code": null,
"e": 24224,
"s": 24204,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 24238,
"s": 24224,
"text": "Google Chrome"
},
{
"code": null,
"e": 24266,
"s": 24238,
"text": "Microsoft Edge 12 and above"
},
{
"code": null,
"e": 24284,
"s": 24266,
"text": "Internet Explorer"
},
{
"code": null,
"e": 24292,
"s": 24284,
"text": "Firefox"
},
{
"code": null,
"e": 24298,
"s": 24292,
"text": "Opera"
},
{
"code": null,
"e": 24305,
"s": 24298,
"text": "Safari"
},
{
"code": null,
"e": 24442,
"s": 24305,
"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": 24459,
"s": 24442,
"text": "arorakashish0911"
},
{
"code": null,
"e": 24473,
"s": 24459,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 24494,
"s": 24473,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 24504,
"s": 24494,
"text": "HTML-Tags"
},
{
"code": null,
"e": 24509,
"s": 24504,
"text": "HTML"
},
{
"code": null,
"e": 24514,
"s": 24509,
"text": "HTML"
},
{
"code": null,
"e": 24612,
"s": 24514,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24621,
"s": 24612,
"text": "Comments"
},
{
"code": null,
"e": 24634,
"s": 24621,
"text": "Old Comments"
},
{
"code": null,
"e": 24696,
"s": 24634,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 24746,
"s": 24696,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 24806,
"s": 24746,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 24854,
"s": 24806,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 24915,
"s": 24854,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 24965,
"s": 24915,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 25018,
"s": 24965,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 25042,
"s": 25018,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 25079,
"s": 25042,
"text": "Types of CSS (Cascading Style Sheet)"
}
] |
How to target desktop, tablet and mobile using Media Query ? - GeeksforGeeks | 10 Jan, 2022
Media Query is a popular technique that enables to deliver a style sheet to different devices which have different screen sizes and resolutions respectively. They are used to customize the appearance of a website on multiple devices. A media query consist of a media type that can contain one or more expression which can be either true or false. The result of the query is true if the specified media matches the type of device the document is displayed on. If the media query is true then the style sheet is applied.
The screen resolutions of different devices are listed below:
Mobile (Smartphone) max-width: 480px
Low Resolution Tablets and ipads max-width: 767px
Tablets Ipads portrait mode max-width:1024px
Desktops max-width:1280px
Huge size (Larger screen) max-width: 1281px and greater
Syntax:
@media( media feature ) {
// CSS Property
}
It uses @media rule to include a block of CSS properties when a certain condition is true. Certain media features are width (max-width and min-width), aspect ratio, resolution, orientation, etc.
Example:
html
<!DOCTYPE html><html> <head> <title>Media Query</title> <style> /* Media Query for Mobile Devices */ @media (max-width: 480px) { body { background-color: red; } } /* Media Query for low resolution Tablets, Ipads */ @media (min-width: 481px) and (max-width: 767px) { body { background-color: yellow; } } /* Media Query for Tablets Ipads portrait mode */ @media (min-width: 768px) and (max-width: 1024px){ body { background-color: blue; } } /* Media Query for Laptops and Desktops */ @media (min-width: 1025px) and (max-width: 1280px){ body { background-color: green; } } /* Media Query for Large screens */ @media (min-width: 1281px) { body { background-color: white; } } </style></head> <body style = "text-align:center;"> <h1>GeeksforGeeks</h1> <h2>Media Query</h2></body> </html>
Output on Mobile Device:
Output on low resolution Tablets, Ipads:
Output on Tablets Ipads portrait mode:
Output on Laptops and Desktops:
Output on large screens:
Note: Change the screen size to see the media query effect.
Supported Browsers: The browser supported by Media Query are listed below:
Google Chrome 21.0
Internet Explorer 9.0
Mozilla Firefox 3.5
Safari 4.0
Opera 9.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
simmytarika5
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
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": 25210,
"s": 25182,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 25729,
"s": 25210,
"text": "Media Query is a popular technique that enables to deliver a style sheet to different devices which have different screen sizes and resolutions respectively. They are used to customize the appearance of a website on multiple devices. A media query consist of a media type that can contain one or more expression which can be either true or false. The result of the query is true if the specified media matches the type of device the document is displayed on. If the media query is true then the style sheet is applied."
},
{
"code": null,
"e": 25791,
"s": 25729,
"text": "The screen resolutions of different devices are listed below:"
},
{
"code": null,
"e": 25828,
"s": 25791,
"text": "Mobile (Smartphone) max-width: 480px"
},
{
"code": null,
"e": 25878,
"s": 25828,
"text": "Low Resolution Tablets and ipads max-width: 767px"
},
{
"code": null,
"e": 25923,
"s": 25878,
"text": "Tablets Ipads portrait mode max-width:1024px"
},
{
"code": null,
"e": 25949,
"s": 25923,
"text": "Desktops max-width:1280px"
},
{
"code": null,
"e": 26005,
"s": 25949,
"text": "Huge size (Larger screen) max-width: 1281px and greater"
},
{
"code": null,
"e": 26013,
"s": 26005,
"text": "Syntax:"
},
{
"code": null,
"e": 26062,
"s": 26013,
"text": "@media( media feature ) {\n // CSS Property\n}\n"
},
{
"code": null,
"e": 26257,
"s": 26062,
"text": "It uses @media rule to include a block of CSS properties when a certain condition is true. Certain media features are width (max-width and min-width), aspect ratio, resolution, orientation, etc."
},
{
"code": null,
"e": 26266,
"s": 26257,
"text": "Example:"
},
{
"code": null,
"e": 26271,
"s": 26266,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Media Query</title> <style> /* Media Query for Mobile Devices */ @media (max-width: 480px) { body { background-color: red; } } /* Media Query for low resolution Tablets, Ipads */ @media (min-width: 481px) and (max-width: 767px) { body { background-color: yellow; } } /* Media Query for Tablets Ipads portrait mode */ @media (min-width: 768px) and (max-width: 1024px){ body { background-color: blue; } } /* Media Query for Laptops and Desktops */ @media (min-width: 1025px) and (max-width: 1280px){ body { background-color: green; } } /* Media Query for Large screens */ @media (min-width: 1281px) { body { background-color: white; } } </style></head> <body style = \"text-align:center;\"> <h1>GeeksforGeeks</h1> <h2>Media Query</h2></body> </html> ",
"e": 27442,
"s": 26271,
"text": null
},
{
"code": null,
"e": 27467,
"s": 27442,
"text": "Output on Mobile Device:"
},
{
"code": null,
"e": 27508,
"s": 27467,
"text": "Output on low resolution Tablets, Ipads:"
},
{
"code": null,
"e": 27547,
"s": 27508,
"text": "Output on Tablets Ipads portrait mode:"
},
{
"code": null,
"e": 27579,
"s": 27547,
"text": "Output on Laptops and Desktops:"
},
{
"code": null,
"e": 27604,
"s": 27579,
"text": "Output on large screens:"
},
{
"code": null,
"e": 27664,
"s": 27604,
"text": "Note: Change the screen size to see the media query effect."
},
{
"code": null,
"e": 27739,
"s": 27664,
"text": "Supported Browsers: The browser supported by Media Query are listed below:"
},
{
"code": null,
"e": 27758,
"s": 27739,
"text": "Google Chrome 21.0"
},
{
"code": null,
"e": 27780,
"s": 27758,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 27800,
"s": 27780,
"text": "Mozilla Firefox 3.5"
},
{
"code": null,
"e": 27811,
"s": 27800,
"text": "Safari 4.0"
},
{
"code": null,
"e": 27821,
"s": 27811,
"text": "Opera 9.0"
},
{
"code": null,
"e": 27958,
"s": 27821,
"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": 27971,
"s": 27958,
"text": "simmytarika5"
},
{
"code": null,
"e": 27981,
"s": 27971,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27988,
"s": 27981,
"text": "Picked"
},
{
"code": null,
"e": 27993,
"s": 27988,
"text": "HTML"
},
{
"code": null,
"e": 28010,
"s": 27993,
"text": "Web Technologies"
},
{
"code": null,
"e": 28015,
"s": 28010,
"text": "HTML"
},
{
"code": null,
"e": 28113,
"s": 28015,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28163,
"s": 28113,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28225,
"s": 28163,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28273,
"s": 28225,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28333,
"s": 28273,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28394,
"s": 28333,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28434,
"s": 28394,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28467,
"s": 28434,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28512,
"s": 28467,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28555,
"s": 28512,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Neural Network Model Architecture Visualization | by Himanshu Sharma | Towards Data Science | Neural Network is a subset of Machine Learning which is inspired by the human brain and is used to solve AI-related problems. It is inspired by neurons found in the human brain, it is a network that is connected using different neurons called a Neural Network. It is an advanced field of Data Science that generally helps in solving the problem related to Artificial Intelligence.
Visualizing a neural network can be helpful in understanding how different layers are connected to each other and how many neurons are there between each layer. It is one of the best ways to understand how a black box model looks from the inside. Visualizing can also be helpful by presenting a model to someone to make them understand how different layers of a neural network are actually connected to each other.
Visualkeras is an open-source Python library that is used for creating Neural Network model visualization. It is one of the best libraries for understanding how different layers are connected.
In this article, we will explore Visualkeras and create some visualizations using them.
Let’s get started...
We will start by installing Visualkeras using pip installation. The command given below will install Visualkeras using pip.
pip install visualkeras
In this step, we will import all the libraries that are required for creating the visualizations.
from tensorflow import kerasfrom tensorflow.keras import layersimport visualkeras
Now we will start by creating a neural network model. We will define a model using different layers like Dense, Flatten, Conv2D, etc. Then we will visualize the model after that.
encoder_input = keras.Input(shape=(28, 28, 1), name='img')x = layers.Conv2D(16, 3, activation='relu')(encoder_input)x = layers.Conv2D(32, 3, activation='relu')(x)x = layers.MaxPooling2D(3)(x)x = layers.Conv2D(32, 3, activation='relu')(x)x = layers.Conv2D(16, 3, activation='relu')(x)encoder_output = layers.GlobalMaxPooling2D()(x)encoder = keras.Model(encoder_input, encoder_output, name='encoder')visualkeras.layered_view(encoder, to_file='encoder.png')x = layers.Reshape((4, 4, 1))(encoder_output)x = layers.Conv2DTranspose(16, 3, activation='relu')(x)x = layers.Conv2DTranspose(32, 3, activation='relu')(x)x = layers.UpSampling2D(3)(x)x = layers.Conv2DTranspose(16, 3, activation='relu')(x)decoder_output = layers.Conv2DTranspose(1, 3, activation='relu')(x)autoencoder = keras.Model(encoder_input, decoder_output, name='autoencoder')
Here you can see how we defined a Neural Network Model using different layers. Now let us visualize the Model.
Now we will use Visualkeras to visualize the model.
visualkeras.layered_view(autoencoder, to_file="model.png')
Here we can see how different layers of the Neural Network are connected. This helps in understanding how the model looks from the inside.
Try this with different models, create different visualizations, and let me know your comments in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me at [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science. | [
{
"code": null,
"e": 553,
"s": 172,
"text": "Neural Network is a subset of Machine Learning which is inspired by the human brain and is used to solve AI-related problems. It is inspired by neurons found in the human brain, it is a network that is connected using different neurons called a Neural Network. It is an advanced field of Data Science that generally helps in solving the problem related to Artificial Intelligence."
},
{
"code": null,
"e": 968,
"s": 553,
"text": "Visualizing a neural network can be helpful in understanding how different layers are connected to each other and how many neurons are there between each layer. It is one of the best ways to understand how a black box model looks from the inside. Visualizing can also be helpful by presenting a model to someone to make them understand how different layers of a neural network are actually connected to each other."
},
{
"code": null,
"e": 1161,
"s": 968,
"text": "Visualkeras is an open-source Python library that is used for creating Neural Network model visualization. It is one of the best libraries for understanding how different layers are connected."
},
{
"code": null,
"e": 1249,
"s": 1161,
"text": "In this article, we will explore Visualkeras and create some visualizations using them."
},
{
"code": null,
"e": 1270,
"s": 1249,
"text": "Let’s get started..."
},
{
"code": null,
"e": 1394,
"s": 1270,
"text": "We will start by installing Visualkeras using pip installation. The command given below will install Visualkeras using pip."
},
{
"code": null,
"e": 1418,
"s": 1394,
"text": "pip install visualkeras"
},
{
"code": null,
"e": 1516,
"s": 1418,
"text": "In this step, we will import all the libraries that are required for creating the visualizations."
},
{
"code": null,
"e": 1598,
"s": 1516,
"text": "from tensorflow import kerasfrom tensorflow.keras import layersimport visualkeras"
},
{
"code": null,
"e": 1777,
"s": 1598,
"text": "Now we will start by creating a neural network model. We will define a model using different layers like Dense, Flatten, Conv2D, etc. Then we will visualize the model after that."
},
{
"code": null,
"e": 2614,
"s": 1777,
"text": "encoder_input = keras.Input(shape=(28, 28, 1), name='img')x = layers.Conv2D(16, 3, activation='relu')(encoder_input)x = layers.Conv2D(32, 3, activation='relu')(x)x = layers.MaxPooling2D(3)(x)x = layers.Conv2D(32, 3, activation='relu')(x)x = layers.Conv2D(16, 3, activation='relu')(x)encoder_output = layers.GlobalMaxPooling2D()(x)encoder = keras.Model(encoder_input, encoder_output, name='encoder')visualkeras.layered_view(encoder, to_file='encoder.png')x = layers.Reshape((4, 4, 1))(encoder_output)x = layers.Conv2DTranspose(16, 3, activation='relu')(x)x = layers.Conv2DTranspose(32, 3, activation='relu')(x)x = layers.UpSampling2D(3)(x)x = layers.Conv2DTranspose(16, 3, activation='relu')(x)decoder_output = layers.Conv2DTranspose(1, 3, activation='relu')(x)autoencoder = keras.Model(encoder_input, decoder_output, name='autoencoder')"
},
{
"code": null,
"e": 2725,
"s": 2614,
"text": "Here you can see how we defined a Neural Network Model using different layers. Now let us visualize the Model."
},
{
"code": null,
"e": 2777,
"s": 2725,
"text": "Now we will use Visualkeras to visualize the model."
},
{
"code": null,
"e": 2836,
"s": 2777,
"text": "visualkeras.layered_view(autoencoder, to_file=\"model.png')"
},
{
"code": null,
"e": 2975,
"s": 2836,
"text": "Here we can see how different layers of the Neural Network are connected. This helps in understanding how the model looks from the inside."
},
{
"code": null,
"e": 3095,
"s": 2975,
"text": "Try this with different models, create different visualizations, and let me know your comments in the response section."
},
{
"code": null,
"e": 3148,
"s": 3095,
"text": "This article is in collaboration with Piyush Ingale."
}
] |
C++ Program to Find Strongly Connected Components in Graphs | Weakly or Strongly Connected for a given a directed graph can be found out using DFS. This is a C++ program of this problem.
Begin
Function fillorder() = fill stack with all the vertices.
a) Mark the current node as visited and print it
b) Recur for all the vertices adjacent to this vertex
c) All vertices reachable from v are processed by now, push v to Stack
End
Begin
Function DFS() :
a) Mark the current node as visited and print it
b) Recur for all the vertices adjacent to this vertex
End
#include <iostream>
#include <list>
#include <stack>
using namespace std;
class G {
int m;
list<int> *adj;
//declaration of functions
void fillOrder(int n, bool visited[], stack<int> &Stack);
void DFS(int n, bool visited[]);
public:
G(int N); //constructor
void addEd(int v, int w);
int print();
G getTranspose();
};
G::G(int m) {
this->m = m;
adj = new list<int> [m];
}
void G::DFS(int n, bool visited[]) {
visited[n] = true; // Mark the current node as visited and print it
cout << n << " ";
list<int>::iterator i;
//Recur for all the vertices adjacent to this vertex
for (i = adj[n].begin(); i != adj[n].end(); ++i)
if (!visited[*i])
DFS(*i, visited);
}
G G::getTranspose() {
G g(m);
for (int n = 0; n< m; n++) {
list<int>::iterator i;
for (i = adj[n].begin(); i != adj[n].end(); ++i) {
g.adj[*i].push_back(n);
}
}
return g;
}
void G::addEd(int v, int w) {
adj[v].push_back(w); //add w to v's list
}
void G::fillOrder(int v, bool visited[], stack<int> &Stack) {
visited[v] = true; //Mark the current node as visited and print it
list<int>::iterator i;
//Recur for all the vertices adjacent to this vertex
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
fillOrder(*i, visited, Stack);
Stack.push(v);
}
int G::print() { //print the solution
stack<int> Stack;
bool *visited = new bool[m];
for (int i = 0; i < m; i++)
visited[i] = false;
for (int i = 0; i < m; i++)
if (visited[i] == false)
fillOrder(i, visited, Stack);
G graph= getTranspose(); //Create a reversed graph
for (int i = 0; i < m; i++)//Mark all the vertices as not visited
visited[i] = false;
int count = 0;
//now process all vertices in order defined by Stack
while (Stack.empty() == false) {
int v = Stack.top();
Stack.pop(); //pop vertex from stack
if (visited[v] == false) {
graph.DFS(v, visited);
cout << endl;
}
count++;
}
return count;
}
int main() {
G g(5);
g.addEd(2, 1);
g.addEd(3, 2);
g.addEd(1, 0);
g.addEd(0, 3);
g.addEd(3, 1);
cout << "Following are strongly connected components
in given graph \n";
if (g.print() > 1) {
cout << "Graph is weakly connected.";
} else {
cout << "Graph is strongly connected.";
}
return 0;
}
Following are strongly connected components in given
graph
4
0 1 2 3
Graph is weakly connected. | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "Weakly or Strongly Connected for a given a directed graph can be found out using DFS. This is a C++ program of this problem."
},
{
"code": null,
"e": 1573,
"s": 1187,
"text": "Begin\nFunction fillorder() = fill stack with all the vertices.\n a) Mark the current node as visited and print it\n b) Recur for all the vertices adjacent to this vertex\n c) All vertices reachable from v are processed by now, push v to Stack\nEnd\nBegin\nFunction DFS() :\n a) Mark the current node as visited and print it\n b) Recur for all the vertices adjacent to this vertex\nEnd"
},
{
"code": null,
"e": 3986,
"s": 1573,
"text": "#include <iostream>\n#include <list>\n#include <stack>\nusing namespace std;\nclass G {\n int m;\n list<int> *adj;\n //declaration of functions\n void fillOrder(int n, bool visited[], stack<int> &Stack);\n void DFS(int n, bool visited[]);\n public:\n G(int N); //constructor\n void addEd(int v, int w);\n int print();\n G getTranspose();\n};\nG::G(int m) {\n this->m = m;\n adj = new list<int> [m];\n}\nvoid G::DFS(int n, bool visited[]) {\n visited[n] = true; // Mark the current node as visited and print it\n cout << n << \" \";\n list<int>::iterator i;\n //Recur for all the vertices adjacent to this vertex\n for (i = adj[n].begin(); i != adj[n].end(); ++i)\n if (!visited[*i])\n DFS(*i, visited);\n}\nG G::getTranspose() {\n G g(m);\n for (int n = 0; n< m; n++) {\n list<int>::iterator i;\n for (i = adj[n].begin(); i != adj[n].end(); ++i) {\n g.adj[*i].push_back(n);\n }\n }\n return g;\n}\nvoid G::addEd(int v, int w) {\n adj[v].push_back(w); //add w to v's list\n}\nvoid G::fillOrder(int v, bool visited[], stack<int> &Stack) {\n visited[v] = true; //Mark the current node as visited and print it\n list<int>::iterator i;\n //Recur for all the vertices adjacent to this vertex\n for (i = adj[v].begin(); i != adj[v].end(); ++i)\n if (!visited[*i])\n fillOrder(*i, visited, Stack);\n Stack.push(v);\n}\nint G::print() { //print the solution\n stack<int> Stack;\n bool *visited = new bool[m];\n for (int i = 0; i < m; i++)\n visited[i] = false;\n for (int i = 0; i < m; i++)\n if (visited[i] == false)\n fillOrder(i, visited, Stack);\n G graph= getTranspose(); //Create a reversed graph\n for (int i = 0; i < m; i++)//Mark all the vertices as not visited\n visited[i] = false;\n int count = 0;\n //now process all vertices in order defined by Stack\n while (Stack.empty() == false) {\n int v = Stack.top();\n Stack.pop(); //pop vertex from stack\n if (visited[v] == false) {\n graph.DFS(v, visited);\n cout << endl;\n }\n count++;\n }\n return count;\n}\nint main() {\n G g(5);\n g.addEd(2, 1);\n g.addEd(3, 2);\n g.addEd(1, 0);\n g.addEd(0, 3);\n g.addEd(3, 1);\n cout << \"Following are strongly connected components\n in given graph \\n\";\n if (g.print() > 1) {\n cout << \"Graph is weakly connected.\";\n } else {\n cout << \"Graph is strongly connected.\";\n }\n return 0;\n}"
},
{
"code": null,
"e": 4082,
"s": 3986,
"text": "Following are strongly connected components in given\ngraph\n4\n0 1 2 3\nGraph is weakly connected."
}
] |
Which CSS property is used to run Animation in Reverse Direction? | Use the animation-direction property to run animation in reverse direction. The property is used with the reverse animation value to achieve this.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 200px;
background-color: yellow;
animation-name: myanim;
animation-duration: 2s;
animation-direction: reverse;
}
@keyframes myanim {
from {
background-color: green;
}
to {
background-color: blue;
}
}
</style>
</head>
<body>
<div></div>
</body>
</html> | [
{
"code": null,
"e": 1209,
"s": 1062,
"text": "Use the animation-direction property to run animation in reverse direction. The property is used with the reverse animation value to achieve this."
},
{
"code": null,
"e": 1219,
"s": 1209,
"text": "Live Demo"
},
{
"code": null,
"e": 1753,
"s": 1219,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n width: 150px;\n height: 200px;\n background-color: yellow;\n animation-name: myanim;\n animation-duration: 2s;\n animation-direction: reverse;\n }\n @keyframes myanim {\n from {\n background-color: green;\n }\n to {\n background-color: blue;\n }\n }\n </style>\n </head>\n <body>\n <div></div>\n </body>\n</html>"
}
] |
How to create a responsive login form with CSS? | Following is the code to create a responsive login form with CSS −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: Arial, Helvetica, sans-serif;
background-color: rgb(189, 189, 255);
}
form {
border: 3px solid #f1f1f1;
background-color: rgb(228, 228, 228);
margin: 20px;
}
h1 {
text-align: center;
}
input[type="text"],
input[type="password"] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
font-size: 30px;
}
label {
font-size: 30px;
}
button {
font-weight: bold;
font-family: monospace, sans-serif, serif;
font-size: 25px;
background-color: #4caf50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.profilePic {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 200px;
height: 200px;
border-radius: 50%;
}
.formFields {
padding: 16px;
}
span.pass {
float: right;
padding-top: 16px;
}
/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
span.pass {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
}
</style>
</head>
<body>
<h1>Responsive Login Form Example</h1>
<form>
<div class="profilePic">
<img
src="https://cdn.pixabay.com/photo/2016/08/08/09/17/avatar-
1577909_960_720.png"
alt="Avatar"
class="avatar"/>
</div>
<div class="formFields">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required />
<label for="pass"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="pass"
required/>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember" /> Remember me
</label>
</div>
<div class="formFields" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="pass">Forgot <a href="#">password?</a></span>
</div>
</form>
</body>
</html>
This will produce the following output − | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Following is the code to create a responsive login form with CSS −"
},
{
"code": null,
"e": 1140,
"s": 1129,
"text": " Live Demo"
},
{
"code": null,
"e": 3314,
"s": 1140,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\nbody {\n font-family: Arial, Helvetica, sans-serif;\n background-color: rgb(189, 189, 255);\n}\nform {\n border: 3px solid #f1f1f1;\n background-color: rgb(228, 228, 228);\n margin: 20px;\n}\nh1 {\n text-align: center;\n}\ninput[type=\"text\"],\ninput[type=\"password\"] {\n width: 100%;\n padding: 12px 20px;\n margin: 8px 0;\n display: inline-block;\n border: 1px solid #ccc;\n box-sizing: border-box;\n font-size: 30px;\n}\nlabel {\n font-size: 30px;\n}\nbutton {\n font-weight: bold;\n font-family: monospace, sans-serif, serif;\n font-size: 25px;\n background-color: #4caf50;\n color: white;\n padding: 14px 20px;\n margin: 8px 0;\n border: none;\n cursor: pointer;\n width: 100%;\n}\nbutton:hover {\n opacity: 0.8;\n}\n.cancelbtn {\n width: auto;\n padding: 10px 18px;\n background-color: #f44336;\n}\n.profilePic {\n text-align: center;\n margin: 24px 0 12px 0;\n}\nimg.avatar {\n width: 200px;\n height: 200px;\n border-radius: 50%;\n}\n.formFields {\n padding: 16px;\n}\nspan.pass {\n float: right;\n padding-top: 16px;\n}\n/* Change styles for span and cancel button on extra small screens */\n@media screen and (max-width: 300px) {\n span.pass {\n display: block;\n float: none;\n }\n .cancelbtn {\n width: 100%;\n }\n}\n</style>\n</head>\n<body>\n<h1>Responsive Login Form Example</h1>\n<form>\n<div class=\"profilePic\">\n<img\nsrc=\"https://cdn.pixabay.com/photo/2016/08/08/09/17/avatar-\n1577909_960_720.png\"\nalt=\"Avatar\"\nclass=\"avatar\"/>\n</div>\n<div class=\"formFields\">\n<label for=\"uname\"><b>Username</b></label>\n<input type=\"text\" placeholder=\"Enter Username\" name=\"uname\" required />\n<label for=\"pass\"><b>Password</b></label>\n<input\ntype=\"password\"\nplaceholder=\"Enter Password\"\nname=\"pass\"\nrequired/>\n<button type=\"submit\">Login</button>\n<label>\n<input type=\"checkbox\" checked=\"checked\" name=\"remember\" /> Remember me\n</label>\n</div>\n<div class=\"formFields\" style=\"background-color:#f1f1f1\">\n<button type=\"button\" class=\"cancelbtn\">Cancel</button>\n<span class=\"pass\">Forgot <a href=\"#\">password?</a></span>\n</div>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 3355,
"s": 3314,
"text": "This will produce the following output −"
}
] |
How to create a covariance matrix in R? | To create a covariance matrix, we first need to find the correlation matrix and a vector of standard deviations is also required. The correlation matrix can be found by using cor function with matrix object. For example, if we have matrix M then the correlation matrix can be found as cor(M). Now we can use this matrix to find the covariance matrix but we should make sure that we have the vector of standard deviations.
Live Demo
> M1<-matrix(rnorm(25,5,1),ncol=5)
> M1
[,1] [,2] [,3] [,4] [,5]
[1,] 5.446881 3.918951 4.306415 4.446757 5.438095
[2,] 5.174487 4.401736 4.755313 5.341615 5.470727
[3,] 4.042656 6.303782 4.939945 4.847339 4.698141
[4,] 3.931823 6.870019 5.196559 6.692013 3.689279
[5,] 4.800770 4.841470 4.356387 3.508081 3.913045
> cor(M1)
[,1] [,2] [,3] [,4] [,5]
[1,] 1.0000000 -0.9908635 -0.8197813 -0.5066590 0.7190219
[2,] -0.9908635 1.0000000 0.8695808 0.6121477 -0.7017947
[3,] -0.8197813 0.8695808 1.0000000 0.8684189 -0.3766508
[4,] -0.5066590 0.6121477 0.8684189 1.0000000 -0.1766397
[5,] 0.7190219 -0.7017947 -0.3766508 -0.1766397 1.0000000
> SD_M1<-rnorm(5)
> M1_Covariance<-(SD_M1%*%t(SD_M1))*cor(M1)
> M1_Covariance
[,1] [,2] [,3] [,4] [,5]
[1,] 0.4916487 0.5972772 0.3299963 0.4854532 0.4018740
[2,] 0.5972772 0.7390424 0.4291690 0.7191096 0.4809114
[3,] 0.3299963 0.4291690 0.3295850 0.6812666 0.1723625
[4,] 0.4854532 0.7191096 0.6812666 1.8672751 0.1924034
[5,] 0.4018740 0.4809114 0.1723625 0.1924034 0.6353903
Live Demo
> M2<-matrix(rnorm(36,5,3),ncol=6)
> M2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3.97345156 2.215491 3.112134 4.6181951 3.6277630 12.322117
[2,] 8.87011312 4.857979 9.067974 6.7924669 5.4123406 3.062662
[3,] 8.70716339 4.905574 5.092897 7.1700455 8.1998048 2.790839
[4,] 2.79704783 8.857838 3.804275 8.0486804 1.8110960 3.789724
[5,] 4.37050111 4.220881 7.835320 -0.9182616 0.5487265 5.676240
[6,] 0.01411185 4.138786 1.736414 6.8982956 4.4729650 6.719265
> cor(M2)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.00000000 -0.05099798 0.72101949 0.0606742 0.5573581 -0.4634089
[2,] -0.05099798 1.00000000 0.02406821 0.4332765 -0.1929059 -0.6648619
[3,] 0.72101949 0.02406821 1.00000000 -0.3981214 -0.0489995 -0.4858796
[4,] 0.06067420 0.43327648 -0.39812145 1.0000000 0.5885335 -0.2935423
[5,] 0.55735812 -0.19290585 -0.04899950 0.5885335 1.0000000 -0.2820521
[6,] -0.46340892 -0.66486188 -0.48587961 -0.2935423 -0.2820521 1.0000000
> SD_M2<-rnorm(6)
> M2_Covariance<-round((SD_M2%*%t(SD_M2))*cor(M2),2)
> M2_Covariance
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0.02 0.00 0.01 0.00 -0.17 -0.10
[2,] 0.00 0.00 0.00 0.00 0.00 -0.01
[3,] 0.01 0.00 0.00 0.00 0.01 -0.04
[4,] 0.00 0.00 0.00 0.01 -0.09 -0.03
[5,] -0.17 0.00 0.01 -0.09 4.10 0.80
[6,] -0.10 -0.01 -0.04 -0.03 0.80 1.95
Live Demo
> M3<-matrix(runif(36,2,5),ncol=6)
> M3
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3.532356 3.325595 2.533484 3.858067 4.209765 4.520970
[2,] 2.836041 4.624075 2.739955 4.294261 2.815741 3.037129
[3,] 2.171741 2.277840 3.939984 3.464941 4.209270 3.565684
[4,] 3.363305 2.623304 2.398647 2.180268 3.740313 3.967784
[5,] 4.637331 2.672298 4.518063 4.851971 2.905769 2.946685
[6,] 3.855836 4.070287 3.698472 4.741746 3.726380 2.603361
> cor(M3)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.00000000 0.02856209 0.3130817 0.4599297 -0.3979636 -0.2620906
[2,] 0.02856209 1.00000000 -0.3159665 0.4775255 -0.4282192 -0.4020013
[3,] 0.31308166 -0.31596655 1.0000000 0.5990245 -0.2107199 -0.6214000
[4,] 0.45992975 0.47752549 0.5990245 1.0000000 -0.4594787 -0.6584400
[5,] -0.39796357 -0.42821922 -0.2107199 -0.4594787 1.0000000 0.6207340
[6,] -0.26209064 -0.40200135 -0.6214000 -0.6584400 0.6207340 1.0000000
> SD_M3<-runif(6,2,3)
> M3_Covariance<-round((SD_M3%*%t(SD_M3))*cor(M3),4)
> M3_Covariance
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 8.2937 0.1818 2.7005 3.6199 -3.2048 -1.9410
[2,] 0.1818 4.8857 -2.0918 2.8846 -2.6467 -2.2850
[3,] 2.7005 -2.0918 8.9705 4.9032 -1.7648 -4.7860
[4,] 3.6199 2.8846 4.9032 7.4690 -3.5114 -4.6274
[5,] -3.2048 -2.6467 -1.7648 -3.5114 7.8193 4.4635
[6,] -1.9410 -2.2850 -4.7860 -4.6274 4.4635 6.6127
Live Demo
> M4<-matrix(rpois(64,10),ncol=8)
> M4
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 2 12 6 6 20 6 5 13
[2,] 11 14 11 10 13 8 14 9
[3,] 7 10 10 10 13 6 9 13
[4,] 6 15 12 11 9 7 14 11
[5,] 9 14 18 14 13 7 15 15
[6,] 12 12 6 14 9 11 6 5
[7,] 11 9 12 9 10 8 12 3
[8,] 12 15 9 15 8 10 4 9
> round(cor(M4),2)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1.00 0.06 0.15 0.69 -0.75 0.80 0.06 -0.63
[2,] 0.06 1.00 0.20 0.48 -0.20 0.20 0.12 0.37
[3,] 0.15 0.20 1.00 0.27 -0.16 -0.32 0.82 0.33
[4,] 0.69 0.48 0.27 1.00 -0.73 0.68 -0.03 -0.08
[5,] -0.75 -0.20 -0.16 -0.73 1.00 -0.68 -0.10 0.54
[6,] 0.80 0.20 -0.32 0.68 -0.68 1.00 -0.37 -0.67
[7,] 0.06 0.12 0.82 -0.03 -0.10 -0.37 1.00 0.15
[8,] -0.63 0.37 0.33 -0.08 0.54 -0.67 0.15 1.00
> SD_M4<-rpois(8,2)
> M4_Covariance<-round((SD_M4%*%t(SD_M4))*cor(M4),2)
> M4_Covariance
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 4.00 0.12 1.17 1.39 -1.51 3.20 0.24 -2.52
[2,] 0.12 1.00 0.82 0.48 -0.20 0.39 0.24 0.74
[3,] 1.17 0.82 16.00 1.10 -0.63 -2.54 6.56 2.66
[4,] 1.39 0.48 1.10 1.00 -0.73 1.36 -0.06 -0.15
[5,] -1.51 -0.20 -0.63 -0.73 1.00 -1.35 -0.20 1.09
[6,] 3.20 0.39 -2.54 1.36 -1.35 4.00 -1.50 -2.70
[7,] 0.24 0.24 6.56 -0.06 -0.20 -1.50 4.00 0.58
[8,] -2.52 0.74 2.66 -0.15 1.09 -2.70 0.58 4.00 | [
{
"code": null,
"e": 1484,
"s": 1062,
"text": "To create a covariance matrix, we first need to find the correlation matrix and a vector of standard deviations is also required. The correlation matrix can be found by using cor function with matrix object. For example, if we have matrix M then the correlation matrix can be found as cor(M). Now we can use this matrix to find the covariance matrix but we should make sure that we have the vector of standard deviations."
},
{
"code": null,
"e": 1494,
"s": 1484,
"text": "Live Demo"
},
{
"code": null,
"e": 1534,
"s": 1494,
"text": "> M1<-matrix(rnorm(25,5,1),ncol=5)\n> M1"
},
{
"code": null,
"e": 1832,
"s": 1534,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 5.446881 3.918951 4.306415 4.446757 5.438095\n[2,] 5.174487 4.401736 4.755313 5.341615 5.470727\n[3,] 4.042656 6.303782 4.939945 4.847339 4.698141\n[4,] 3.931823 6.870019 5.196559 6.692013 3.689279\n[5,] 4.800770 4.841470 4.356387 3.508081 3.913045"
},
{
"code": null,
"e": 1842,
"s": 1832,
"text": "> cor(M1)"
},
{
"code": null,
"e": 2186,
"s": 1842,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 1.0000000 -0.9908635 -0.8197813 -0.5066590 0.7190219\n[2,] -0.9908635 1.0000000 0.8695808 0.6121477 -0.7017947\n[3,] -0.8197813 0.8695808 1.0000000 0.8684189 -0.3766508\n[4,] -0.5066590 0.6121477 0.8684189 1.0000000 -0.1766397\n[5,] 0.7190219 -0.7017947 -0.3766508 -0.1766397 1.0000000"
},
{
"code": null,
"e": 2264,
"s": 2186,
"text": "> SD_M1<-rnorm(5)\n> M1_Covariance<-(SD_M1%*%t(SD_M1))*cor(M1)\n> M1_Covariance"
},
{
"code": null,
"e": 2591,
"s": 2264,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 0.4916487 0.5972772 0.3299963 0.4854532 0.4018740\n[2,] 0.5972772 0.7390424 0.4291690 0.7191096 0.4809114\n[3,] 0.3299963 0.4291690 0.3295850 0.6812666 0.1723625\n[4,] 0.4854532 0.7191096 0.6812666 1.8672751 0.1924034\n[5,] 0.4018740 0.4809114 0.1723625 0.1924034 0.6353903"
},
{
"code": null,
"e": 2601,
"s": 2591,
"text": "Live Demo"
},
{
"code": null,
"e": 2641,
"s": 2601,
"text": "> M2<-matrix(rnorm(36,5,3),ncol=6)\n> M2"
},
{
"code": null,
"e": 3082,
"s": 2641,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 3.97345156 2.215491 3.112134 4.6181951 3.6277630 12.322117\n[2,] 8.87011312 4.857979 9.067974 6.7924669 5.4123406 3.062662\n[3,] 8.70716339 4.905574 5.092897 7.1700455 8.1998048 2.790839\n[4,] 2.79704783 8.857838 3.804275 8.0486804 1.8110960 3.789724\n[5,] 4.37050111 4.220881 7.835320 -0.9182616 0.5487265 5.676240\n[6,] 0.01411185 4.138786 1.736414 6.8982956 4.4729650 6.719265"
},
{
"code": null,
"e": 3092,
"s": 3082,
"text": "> cor(M2)"
},
{
"code": null,
"e": 3586,
"s": 3092,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 1.00000000 -0.05099798 0.72101949 0.0606742 0.5573581 -0.4634089\n[2,] -0.05099798 1.00000000 0.02406821 0.4332765 -0.1929059 -0.6648619\n[3,] 0.72101949 0.02406821 1.00000000 -0.3981214 -0.0489995 -0.4858796\n[4,] 0.06067420 0.43327648 -0.39812145 1.0000000 0.5885335 -0.2935423\n[5,] 0.55735812 -0.19290585 -0.04899950 0.5885335 1.0000000 -0.2820521\n[6,] -0.46340892 -0.66486188 -0.48587961 -0.2935423 -0.2820521 1.0000000"
},
{
"code": null,
"e": 3673,
"s": 3586,
"text": "> SD_M2<-rnorm(6)\n> M2_Covariance<-round((SD_M2%*%t(SD_M2))*cor(M2),2)\n> M2_Covariance"
},
{
"code": null,
"e": 3930,
"s": 3673,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 0.02 0.00 0.01 0.00 -0.17 -0.10\n[2,] 0.00 0.00 0.00 0.00 0.00 -0.01\n[3,] 0.01 0.00 0.00 0.00 0.01 -0.04\n[4,] 0.00 0.00 0.00 0.01 -0.09 -0.03\n[5,] -0.17 0.00 0.01 -0.09 4.10 0.80\n[6,] -0.10 -0.01 -0.04 -0.03 0.80 1.95"
},
{
"code": null,
"e": 3940,
"s": 3930,
"text": "Live Demo"
},
{
"code": null,
"e": 3980,
"s": 3940,
"text": "> M3<-matrix(runif(36,2,5),ncol=6)\n> M3"
},
{
"code": null,
"e": 4391,
"s": 3980,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 3.532356 3.325595 2.533484 3.858067 4.209765 4.520970\n[2,] 2.836041 4.624075 2.739955 4.294261 2.815741 3.037129\n[3,] 2.171741 2.277840 3.939984 3.464941 4.209270 3.565684\n[4,] 3.363305 2.623304 2.398647 2.180268 3.740313 3.967784\n[5,] 4.637331 2.672298 4.518063 4.851971 2.905769 2.946685\n[6,] 3.855836 4.070287 3.698472 4.741746 3.726380 2.603361"
},
{
"code": null,
"e": 4401,
"s": 4391,
"text": "> cor(M3)"
},
{
"code": null,
"e": 4885,
"s": 4401,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 1.00000000 0.02856209 0.3130817 0.4599297 -0.3979636 -0.2620906\n[2,] 0.02856209 1.00000000 -0.3159665 0.4775255 -0.4282192 -0.4020013\n[3,] 0.31308166 -0.31596655 1.0000000 0.5990245 -0.2107199 -0.6214000\n[4,] 0.45992975 0.47752549 0.5990245 1.0000000 -0.4594787 -0.6584400\n[5,] -0.39796357 -0.42821922 -0.2107199 -0.4594787 1.0000000 0.6207340\n[6,] -0.26209064 -0.40200135 -0.6214000 -0.6584400 0.6207340 1.0000000"
},
{
"code": null,
"e": 4976,
"s": 4885,
"text": "> SD_M3<-runif(6,2,3)\n> M3_Covariance<-round((SD_M3%*%t(SD_M3))*cor(M3),4)\n> M3_Covariance"
},
{
"code": null,
"e": 5306,
"s": 4976,
"text": "[,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 8.2937 0.1818 2.7005 3.6199 -3.2048 -1.9410\n[2,] 0.1818 4.8857 -2.0918 2.8846 -2.6467 -2.2850\n[3,] 2.7005 -2.0918 8.9705 4.9032 -1.7648 -4.7860\n[4,] 3.6199 2.8846 4.9032 7.4690 -3.5114 -4.6274\n[5,] -3.2048 -2.6467 -1.7648 -3.5114 7.8193 4.4635\n[6,] -1.9410 -2.2850 -4.7860 -4.6274 4.4635 6.6127"
},
{
"code": null,
"e": 5316,
"s": 5306,
"text": "Live Demo"
},
{
"code": null,
"e": 5355,
"s": 5316,
"text": "> M4<-matrix(rpois(64,10),ncol=8)\n> M4"
},
{
"code": null,
"e": 5600,
"s": 5355,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 2 12 6 6 20 6 5 13\n[2,] 11 14 11 10 13 8 14 9\n[3,] 7 10 10 10 13 6 9 13\n[4,] 6 15 12 11 9 7 14 11\n[5,] 9 14 18 14 13 7 15 15\n[6,] 12 12 6 14 9 11 6 5\n[7,] 11 9 12 9 10 8 12 3\n[8,] 12 15 9 15 8 10 4 9"
},
{
"code": null,
"e": 5619,
"s": 5600,
"text": "> round(cor(M4),2)"
},
{
"code": null,
"e": 6043,
"s": 5619,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 1.00 0.06 0.15 0.69 -0.75 0.80 0.06 -0.63\n[2,] 0.06 1.00 0.20 0.48 -0.20 0.20 0.12 0.37\n[3,] 0.15 0.20 1.00 0.27 -0.16 -0.32 0.82 0.33\n[4,] 0.69 0.48 0.27 1.00 -0.73 0.68 -0.03 -0.08\n[5,] -0.75 -0.20 -0.16 -0.73 1.00 -0.68 -0.10 0.54\n[6,] 0.80 0.20 -0.32 0.68 -0.68 1.00 -0.37 -0.67\n[7,] 0.06 0.12 0.82 -0.03 -0.10 -0.37 1.00 0.15\n[8,] -0.63 0.37 0.33 -0.08 0.54 -0.67 0.15 1.00"
},
{
"code": null,
"e": 6132,
"s": 6043,
"text": "> SD_M4<-rpois(8,2)\n> M4_Covariance<-round((SD_M4%*%t(SD_M4))*cor(M4),2)\n> M4_Covariance"
},
{
"code": null,
"e": 6557,
"s": 6132,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 4.00 0.12 1.17 1.39 -1.51 3.20 0.24 -2.52\n[2,] 0.12 1.00 0.82 0.48 -0.20 0.39 0.24 0.74\n[3,] 1.17 0.82 16.00 1.10 -0.63 -2.54 6.56 2.66\n[4,] 1.39 0.48 1.10 1.00 -0.73 1.36 -0.06 -0.15\n[5,] -1.51 -0.20 -0.63 -0.73 1.00 -1.35 -0.20 1.09\n[6,] 3.20 0.39 -2.54 1.36 -1.35 4.00 -1.50 -2.70\n[7,] 0.24 0.24 6.56 -0.06 -0.20 -1.50 4.00 0.58\n[8,] -2.52 0.74 2.66 -0.15 1.09 -2.70 0.58 4.00"
}
] |
How to Speedup your Pandas Code by 10x | by Peter Grant | Towards Data Science | As we all know, pandas is a fantastic data science tool. It provides us with the dataframe structure we need, powerful computational abilities, and does so in a very user-friendly format. It even has quality documentation and a large support network, making it easy to learn. It’s excellent.
But it’s not always particularly fast.
This can become a problem when many, many computations are involved. If the processing method is slow, it takes longer to run the program. And that gets very bothersome if millions of computations are required and total computation time stretches on and on.
This is a common problem in the work that I do. A big focus of my work is developing simulation models representing common equipment in buildings. This means I create functions emulating the heat transfer processes and control logic decisions in a piece of equipment, then pass data describing the building conditions and occupant behavior choices into those models. The models then predict what the equipment will do, how well it will satisfy the occupants needs, and how much energy it will consume.
In order to do that the models need to be time-based. It needs to be able to calculate what happens at one point in the simulation, and only then move on to the next set of calculations. That’s because the outputs at one time are the inputs at the next time. For example, imagine predicting the temperature in your oven at any point in time. Is it currently heating? How much has the temperature increased since the last time in question? What was the temperature at that time?
This dependence on the last time leads to a problem. We can’t use vector calculations. We must use the dreaded for loops. For loops are slow.
One solution, whether vectorizing calculations is possible or not, is to convert your calculations to numpy. According to Sofia Heisler at Upside Engineering Blog, numpy performs a lot of background information using precompiled C code. This precompiled C code makes it significantly faster than pandas by skipping the compiling step, and by including pre-programmed speed optimizations. Additionally, numpy drops a lot of the information in pandas. Pandas keeps track of data types, indexes, and performs error checking. All of which are very useful, but are not necessary at this time and slow down the calculations. Numpy doesn’t do that, and can perform the same calculations significantly faster.
There are multiple ways to convert panads data to numpy.
A series can be converted using the .values method. This creates the same series in numpy. For a simple example, see the following code:
import pandas as pdSeries_Pandas = pd.Series(data=[1, 2, 3, 4, 5, 6])Series_Numpy = Series_Pandas.values
A dataframe can be converted using the .to_numpy() function. This creates an int64 objectwith the same values in numpy. Note that this does not keep the column names, and you need to create a dictionary converting your pandas column names to numpy column numbers. This can be accomplished with the following code:
import pandas as pdimport numpy as npDataframe_Pandas = pd.DataFrame(data=[[0,1], [2,3], [4,5]], columns = ['First Column', 'Second Column'])Dataframe_Numpy = Dataframe_Pandas.to_numpy()Column_Index_Dictionary = dict(zip(Dataframe_Pandas.columns, list(range(0,len(Dataframe_Pandas.columns)))))
That code converts the dataframe to a numpy int64 object and provides all of the tools needed to iterate through each line, editing values in specific columns, in a user-friendly manner. Each cell can be called in a manner similar to using the pandas .loc function with numpy indexing, following the structure int64object[row, Dictionary[‘Pandas Column Name’]]. For instance, if you want to set the value in the first row of ‘Second Column’ to ‘9’ you can use the following code:
Dataframe_Numpy[0, Column_Index_Dictionary['Second Column']] = 9
Of course this is going to vary from one situation to the next. Some scripts will see more improvement by switching to numpy than others. It depends on the types of calculations used in your script and the percentage of all calculations that are converted to numpy. But the results can be drastic.
For an example, I recently used this to convert one of my simulation models from a pandas base to a numpy base. The original, pandas based model required 362 seconds to perform an annual simulation. That’s a bit over 6 minutes. This isn’t terrible if you’re running one simulation with the model, but what if you’re running a thousand? After converting the core of the model to numpy, the same annual simulation required 32 seconds to calculate.
That’s 9% as much time to do the same thing. More than a 10x speedup from user pre-existing functions to convert my code from pandas to numpy.
Numpy has all of the computation capabilities of pandas, but performs them without carrying as much overhead information and uses pre-compiled, optimized methods. As a result, it can be significantly faster than pandas.
Converting a dataframe from pandas to numpy is relatively straightforward. You can use the dataframes .to_numpy() function to automatically convert it, then create a dictionary of the column names to enable accessing each cell similarly to the pandas .loc function.
This simple change can yield significant results. Script using numpy can execute in approximately 10% of the time that would be required if using pandas. | [
{
"code": null,
"e": 464,
"s": 172,
"text": "As we all know, pandas is a fantastic data science tool. It provides us with the dataframe structure we need, powerful computational abilities, and does so in a very user-friendly format. It even has quality documentation and a large support network, making it easy to learn. It’s excellent."
},
{
"code": null,
"e": 503,
"s": 464,
"text": "But it’s not always particularly fast."
},
{
"code": null,
"e": 761,
"s": 503,
"text": "This can become a problem when many, many computations are involved. If the processing method is slow, it takes longer to run the program. And that gets very bothersome if millions of computations are required and total computation time stretches on and on."
},
{
"code": null,
"e": 1263,
"s": 761,
"text": "This is a common problem in the work that I do. A big focus of my work is developing simulation models representing common equipment in buildings. This means I create functions emulating the heat transfer processes and control logic decisions in a piece of equipment, then pass data describing the building conditions and occupant behavior choices into those models. The models then predict what the equipment will do, how well it will satisfy the occupants needs, and how much energy it will consume."
},
{
"code": null,
"e": 1741,
"s": 1263,
"text": "In order to do that the models need to be time-based. It needs to be able to calculate what happens at one point in the simulation, and only then move on to the next set of calculations. That’s because the outputs at one time are the inputs at the next time. For example, imagine predicting the temperature in your oven at any point in time. Is it currently heating? How much has the temperature increased since the last time in question? What was the temperature at that time?"
},
{
"code": null,
"e": 1883,
"s": 1741,
"text": "This dependence on the last time leads to a problem. We can’t use vector calculations. We must use the dreaded for loops. For loops are slow."
},
{
"code": null,
"e": 2585,
"s": 1883,
"text": "One solution, whether vectorizing calculations is possible or not, is to convert your calculations to numpy. According to Sofia Heisler at Upside Engineering Blog, numpy performs a lot of background information using precompiled C code. This precompiled C code makes it significantly faster than pandas by skipping the compiling step, and by including pre-programmed speed optimizations. Additionally, numpy drops a lot of the information in pandas. Pandas keeps track of data types, indexes, and performs error checking. All of which are very useful, but are not necessary at this time and slow down the calculations. Numpy doesn’t do that, and can perform the same calculations significantly faster."
},
{
"code": null,
"e": 2642,
"s": 2585,
"text": "There are multiple ways to convert panads data to numpy."
},
{
"code": null,
"e": 2779,
"s": 2642,
"text": "A series can be converted using the .values method. This creates the same series in numpy. For a simple example, see the following code:"
},
{
"code": null,
"e": 2884,
"s": 2779,
"text": "import pandas as pdSeries_Pandas = pd.Series(data=[1, 2, 3, 4, 5, 6])Series_Numpy = Series_Pandas.values"
},
{
"code": null,
"e": 3198,
"s": 2884,
"text": "A dataframe can be converted using the .to_numpy() function. This creates an int64 objectwith the same values in numpy. Note that this does not keep the column names, and you need to create a dictionary converting your pandas column names to numpy column numbers. This can be accomplished with the following code:"
},
{
"code": null,
"e": 3492,
"s": 3198,
"text": "import pandas as pdimport numpy as npDataframe_Pandas = pd.DataFrame(data=[[0,1], [2,3], [4,5]], columns = ['First Column', 'Second Column'])Dataframe_Numpy = Dataframe_Pandas.to_numpy()Column_Index_Dictionary = dict(zip(Dataframe_Pandas.columns, list(range(0,len(Dataframe_Pandas.columns)))))"
},
{
"code": null,
"e": 3972,
"s": 3492,
"text": "That code converts the dataframe to a numpy int64 object and provides all of the tools needed to iterate through each line, editing values in specific columns, in a user-friendly manner. Each cell can be called in a manner similar to using the pandas .loc function with numpy indexing, following the structure int64object[row, Dictionary[‘Pandas Column Name’]]. For instance, if you want to set the value in the first row of ‘Second Column’ to ‘9’ you can use the following code:"
},
{
"code": null,
"e": 4037,
"s": 3972,
"text": "Dataframe_Numpy[0, Column_Index_Dictionary['Second Column']] = 9"
},
{
"code": null,
"e": 4335,
"s": 4037,
"text": "Of course this is going to vary from one situation to the next. Some scripts will see more improvement by switching to numpy than others. It depends on the types of calculations used in your script and the percentage of all calculations that are converted to numpy. But the results can be drastic."
},
{
"code": null,
"e": 4781,
"s": 4335,
"text": "For an example, I recently used this to convert one of my simulation models from a pandas base to a numpy base. The original, pandas based model required 362 seconds to perform an annual simulation. That’s a bit over 6 minutes. This isn’t terrible if you’re running one simulation with the model, but what if you’re running a thousand? After converting the core of the model to numpy, the same annual simulation required 32 seconds to calculate."
},
{
"code": null,
"e": 4924,
"s": 4781,
"text": "That’s 9% as much time to do the same thing. More than a 10x speedup from user pre-existing functions to convert my code from pandas to numpy."
},
{
"code": null,
"e": 5144,
"s": 4924,
"text": "Numpy has all of the computation capabilities of pandas, but performs them without carrying as much overhead information and uses pre-compiled, optimized methods. As a result, it can be significantly faster than pandas."
},
{
"code": null,
"e": 5410,
"s": 5144,
"text": "Converting a dataframe from pandas to numpy is relatively straightforward. You can use the dataframes .to_numpy() function to automatically convert it, then create a dictionary of the column names to enable accessing each cell similarly to the pandas .loc function."
}
] |
Human Computer Interface - Quick Guide | Human Computer Interface (HCI) was previously known as the man-machine studies or man-machine interaction. It deals with the design, execution and assessment of computer systems and related phenomenon that are for human use.
HCI can be used in all disciplines wherever there is a possibility of computer installation. Some of the areas where HCI can be implemented with distinctive importance are mentioned below −
Computer Science − For application design and engineering.
Computer Science − For application design and engineering.
Psychology − For application of theories and analytical purpose.
Psychology − For application of theories and analytical purpose.
Sociology − For interaction between technology and organization.
Sociology − For interaction between technology and organization.
Industrial Design − For interactive products like mobile phones, microwave oven, etc.
Industrial Design − For interactive products like mobile phones, microwave oven, etc.
The world’s leading organization in HCI is ACM − SIGCHI, which stands for Association for Computer Machinery − Special Interest Group on Computer–Human Interaction. SIGCHI defines Computer Science to be the core discipline of HCI. In India, it emerged as an interaction proposal, mostly based in the field of Design.
The intention of this subject is to learn the ways of designing user-friendly interfaces or interactions. Considering which, we will learn the following −
Ways to design and assess interactive systems.
Ways to design and assess interactive systems.
Ways to reduce design time through cognitive system and task models.
Ways to reduce design time through cognitive system and task models.
Procedures and heuristics for interactive system design.
Procedures and heuristics for interactive system design.
From the initial computers performing batch processing to the user-centric design, there were several milestones which are mentioned below −
Early computer (e.g. ENIAC, 1946) − Improvement in the H/W technology brought massive increase in computing power. People started thinking on innovative ideas.
Early computer (e.g. ENIAC, 1946) − Improvement in the H/W technology brought massive increase in computing power. People started thinking on innovative ideas.
Visual Display Unit (1950s) − SAGE (semi-automatic ground environment), an air defense system of the USA used the earliest version of VDU.
Visual Display Unit (1950s) − SAGE (semi-automatic ground environment), an air defense system of the USA used the earliest version of VDU.
Development of the Sketchpad (1962) − Ivan Sutherland developed Sketchpad and proved that computer can be used for more than data processing.
Development of the Sketchpad (1962) − Ivan Sutherland developed Sketchpad and proved that computer can be used for more than data processing.
Douglas Engelbart introduced the idea of programming toolkits (1963) − Smaller systems created larger systems and components.
Douglas Engelbart introduced the idea of programming toolkits (1963) − Smaller systems created larger systems and components.
Introduction of Word Processor, Mouse (1968) − Design of NLS (oNLine System).
Introduction of Word Processor, Mouse (1968) − Design of NLS (oNLine System).
Introduction of personal computer Dynabook (1970s) − Developed smalltalk at Xerox PARC.
Introduction of personal computer Dynabook (1970s) − Developed smalltalk at Xerox PARC.
Windows and WIMP interfaces − Simultaneous jobs at one desktop, switching between work and screens, sequential interaction.
Windows and WIMP interfaces − Simultaneous jobs at one desktop, switching between work and screens, sequential interaction.
The idea of metaphor − Xerox star and alto were the first systems to use the concept of metaphors, which led to spontaneity of the interface.
The idea of metaphor − Xerox star and alto were the first systems to use the concept of metaphors, which led to spontaneity of the interface.
Direct Manipulation introduced by Ben Shneiderman (1982) − First used in Apple Mac PC (1984) that reduced the chances for syntactic errors.
Direct Manipulation introduced by Ben Shneiderman (1982) − First used in Apple Mac PC (1984) that reduced the chances for syntactic errors.
Vannevar Bush introduced Hypertext (1945) − To denote the non-linear structure of text.
Vannevar Bush introduced Hypertext (1945) − To denote the non-linear structure of text.
Multimodality (late 1980s).
Multimodality (late 1980s).
Computer Supported Cooperative Work (1990’s) − Computer mediated communication.
Computer Supported Cooperative Work (1990’s) − Computer mediated communication.
WWW (1989) − The first graphical browser (Mosaic) came in 1993.
WWW (1989) − The first graphical browser (Mosaic) came in 1993.
Ubiquitous Computing − Currently the most active research area in HCI. Sensor based/context aware computing also known as pervasive computing.
Ubiquitous Computing − Currently the most active research area in HCI. Sensor based/context aware computing also known as pervasive computing.
Some ground-breaking Creation and Graphic Communication designers started showing interest in the field of HCI from the late 80s. Others crossed the threshold by designing program for CD ROM titles. Some of them entered the field by designing for the web and by providing computer trainings.
Even though India is running behind in offering an established course in HCI, there are designers in India who in addition to creativity and artistic expression, consider design to be a problem-solving activity and prefer to work in an area where the demand has not been met.
This urge for designing has often led them to get into innovative fields and get the knowledge through self-study. Later, when HCI prospects arrived in India, designers adopted techniques from usability assessment, user studies, software prototyping, etc.
Ben Shneiderman, an American computer scientist consolidated some implicit facts about designing and came up with the following eight general guidelines −
Strive for Consistency.
Cater to Universal Usability.
Offer Informative feedback.
Design Dialogs to yield closure.
Prevent Errors.
Permit easy reversal of actions.
Support internal locus of control.
Reduce short term memory load.
These guidelines are beneficial for normal designers as well as interface designers. Using these eight guidelines, it is possible to differentiate a good interface design from a bad one. These are beneficial in experimental assessment of identifying better GUIs.
To assess the interaction between human and computers, Donald Norman in 1988 proposed seven principles. He proposed the seven stages that can be used to transform difficult tasks. Following are the seven principles of Norman −
Use both knowledge in world & knowledge in the head.
Use both knowledge in world & knowledge in the head.
Simplify task structures.
Simplify task structures.
Make things visible.
Make things visible.
Get the mapping right (User mental model = Conceptual model = Designed model).
Get the mapping right (User mental model = Conceptual model = Designed model).
Convert constrains into advantages (Physical constraints, Cultural constraints, Technological constraints).
Convert constrains into advantages (Physical constraints, Cultural constraints, Technological constraints).
Design for Error.
Design for Error.
When all else fails − Standardize.
When all else fails − Standardize.
Heuristics evaluation is a methodical procedure to check user interface for usability problems. Once a usability problem is detected in design, they are attended as an integral part of constant design processes. Heuristic evaluation method includes some usability principles such as Nielsen’s ten Usability principles.
Visibility of system status.
Match between system and real world.
User control and freedom.
Consistency and standards.
Error prevention.
Recognition rather than Recall.
Flexibility and efficiency of use.
Aesthetic and minimalist design.
Help, diagnosis and recovery from errors.
Documentation and Help
The above mentioned ten principles of Nielsen serve as a checklist in evaluating and explaining problems for the heuristic evaluator while auditing an interface or a product.
Some more important HCI design guidelines are presented in this section. General interaction, information display, and data entry are three categories of HCI design guidelines that are explained below.
Guidelines for general interaction are comprehensive advices that focus on general instructions such as −
Be consistent.
Be consistent.
Offer significant feedback.
Offer significant feedback.
Ask for authentication of any non-trivial critical action.
Ask for authentication of any non-trivial critical action.
Authorize easy reversal of most actions.
Authorize easy reversal of most actions.
Lessen the amount of information that must be remembered in between actions.
Lessen the amount of information that must be remembered in between actions.
Seek competence in dialogue, motion and thought.
Seek competence in dialogue, motion and thought.
Excuse mistakes.
Excuse mistakes.
Classify activities by function and establish screen geography accordingly.
Classify activities by function and establish screen geography accordingly.
Deliver help services that are context sensitive.
Deliver help services that are context sensitive.
Use simple action verbs or short verb phrases to name commands.
Use simple action verbs or short verb phrases to name commands.
Information provided by the HCI should not be incomplete or unclear or else the application will not meet the requirements of the user. To provide better display, the following guidelines are prepared −
Exhibit only that information that is applicable to the present context.
Exhibit only that information that is applicable to the present context.
Don't burden the user with data, use a presentation layout that allows rapid integration of information.
Don't burden the user with data, use a presentation layout that allows rapid integration of information.
Use standard labels, standard abbreviations and probable colors.
Use standard labels, standard abbreviations and probable colors.
Permit the user to maintain visual context.
Permit the user to maintain visual context.
Generate meaningful error messages.
Generate meaningful error messages.
Use upper and lower case, indentation and text grouping to aid in understanding.
Use upper and lower case, indentation and text grouping to aid in understanding.
Use windows (if available) to classify different types of information.
Use windows (if available) to classify different types of information.
Use analog displays to characterize information that is more easily integrated with this form of representation.
Use analog displays to characterize information that is more easily integrated with this form of representation.
Consider the available geography of the display screen and use it efficiently.
Consider the available geography of the display screen and use it efficiently.
The following guidelines focus on data entry that is another important aspect of HCI −
Reduce the number of input actions required of the user.
Reduce the number of input actions required of the user.
Uphold steadiness between information display and data input.
Uphold steadiness between information display and data input.
Let the user customize the input.
Let the user customize the input.
Interaction should be flexible but also tuned to the user's favored mode of input.
Interaction should be flexible but also tuned to the user's favored mode of input.
Disable commands that are unsuitable in the context of current actions.
Disable commands that are unsuitable in the context of current actions.
Allow the user to control the interactive flow.
Allow the user to control the interactive flow.
Offer help to assist with all input actions.
Offer help to assist with all input actions.
Remove "mickey mouse" input.
Remove "mickey mouse" input.
The objective of this chapter is to learn all the aspects of design and development of interactive systems, which are now an important part of our lives. The design and usability of these systems leaves an effect on the quality of people’s relationship to technology. Web applications, games, embedded devices, etc., are all a part of this system, which has become an integral part of our lives. Let us now discuss on some major components of this system.
Usability Engineering is a method in the progress of software and systems, which includes user contribution from the inception of the process and assures the effectiveness of the product through the use of a usability requirement and metrics.
It thus refers to the Usability Function features of the entire process of abstracting, implementing & testing hardware and software products. Requirements gathering stage to installation, marketing and testing of products, all fall in this process.
Effective to use − Functional
Efficient to use − Efficient
Error free in use − Safe
Easy to use − Friendly
Enjoyable in use − Delightful Experience
Usability has three components − effectiveness, efficiency and satisfaction, using which, users accomplish their goals in particular environments. Let us look in brief about these components.
Effectiveness − The completeness with which users achieve their goals.
Effectiveness − The completeness with which users achieve their goals.
Efficiency − The competence used in using the resources to effectively achieve the goals.
Efficiency − The competence used in using the resources to effectively achieve the goals.
Satisfaction − The ease of the work system to its users.
Satisfaction − The ease of the work system to its users.
The methodical study on the interaction between people, products, and environment based on experimental assessment. Example: Psychology, Behavioral Science, etc.
The scientific evaluation of the stated usability parameters as per the user’s requirements, competences, prospects, safety and satisfaction is known as usability testing.
Acceptance testing also known as User Acceptance Testing (UAT), is a testing procedure that is performed by the users as a final checkpoint before signing off from a vendor. Let us take an example of the handheld barcode scanner.
A software tool is a programmatic software used to create, maintain, or otherwise support other programs and applications. Some of the commonly used software tools in HCI are as follows −
Specification Methods − The methods used to specify the GUI. Even though these are lengthy and ambiguous methods, they are easy to understand.
Specification Methods − The methods used to specify the GUI. Even though these are lengthy and ambiguous methods, they are easy to understand.
Grammars − Written Instructions or Expressions that a program would understand. They provide confirmations for completeness and correctness.
Grammars − Written Instructions or Expressions that a program would understand. They provide confirmations for completeness and correctness.
Transition Diagram − Set of nodes and links that can be displayed in text, link frequency, state diagram, etc. They are difficult in evaluating usability, visibility, modularity and synchronization.
Transition Diagram − Set of nodes and links that can be displayed in text, link frequency, state diagram, etc. They are difficult in evaluating usability, visibility, modularity and synchronization.
Statecharts − Chart methods developed for simultaneous user activities and external actions. They provide link-specification with interface building tools.
Statecharts − Chart methods developed for simultaneous user activities and external actions. They provide link-specification with interface building tools.
Interface Building Tools − Design methods that help in designing command languages, data-entry structures, and widgets.
Interface Building Tools − Design methods that help in designing command languages, data-entry structures, and widgets.
Interface Mockup Tools − Tools to develop a quick sketch of GUI. E.g., Microsoft Visio, Visual Studio .Net, etc.
Interface Mockup Tools − Tools to develop a quick sketch of GUI. E.g., Microsoft Visio, Visual Studio .Net, etc.
Software Engineering Tools − Extensive programming tools to provide user interface management system.
Software Engineering Tools − Extensive programming tools to provide user interface management system.
Evaluation Tools − Tools to evaluate the correctness and completeness of programs.
Evaluation Tools − Tools to evaluate the correctness and completeness of programs.
Software engineering is the study of designing, development and preservation of software. It comes in contact with HCI to make the man and machine interaction more vibrant and interactive.
Let us see the following model in software engineering for interactive designing.
The uni-directional movement of the waterfall model of Software Engineering shows that every phase depends on the preceding phase and not vice-versa. However, this model is not suitable for the interactive system design.
The interactive system design shows that every phase depends on each other to serve the purpose of designing and product creation. It is a continuous process as there is so much to know and users keep changing all the time. An interactive system designer should recognize this diversity.
Prototyping is another type of software engineering models that can have a complete range of functionalities of the projected system.
In HCI, prototyping is a trial and partial design that helps users in testing design ideas without executing a complete system.
Example of a prototype can be Sketches. Sketches of interactive design can later be produced into graphical interface. See the following diagram.
The above diagram can be considered as a Low Fidelity Prototype as it uses manual procedures like sketching in a paper.
A Medium Fidelity Prototype involves some but not all procedures of the system. E.g., first screen of a GUI.
Finally, a Hi Fidelity Prototype simulates all the functionalities of the system in a design. This prototype requires, time, money and work force.
The process of collecting feedback from users to improve the design is known as user centered design or UCD.
Passive user involvement.
User’s perception about the new interface may be inappropriate.
Designers may ask incorrect questions to users.
The stages in the following diagram are repeated until the solution is reached.
Diagram
Graphic User Interface (GUI) is the interface from where a user can operate programs, applications or devices in a computer system. This is where the icons, menus, widgets, labels exist for the users to access.
It is significant that everything in the GUI is arranged in a way that is recognizable and pleasing to the eye, which shows the aesthetic sense of the GUI designer. GUI aesthetics provides a character and identity to any product.
For the past couple of years, majority IT companies in India are hiring designers for HCI related activities. Even multi-national companies started hiring for HCI from India as Indian designers have proven their capabilities in architectural, visual and interaction designs. Thus, Indian HCI designers are not only making a mark in the country, but also abroad.
The profession has boomed in the last decade even when the usability has been there forever. And since new products are developed frequently, the durability prognosis also looks great.
As per an estimation made on usability specialists, there are mere 1,000 experts in India. The overall requirement is around 60,000. Out of all the designers working in the country, HCI designers count for approximately 2.77%.
Let us take a known analogy that can be understood by everyone. A film director is a person who with his/her experience can work on script writing, acting, editing, and cinematography. He/She can be considered as the only person accountable for all the creative phases of the film.
Similarly, HCI can be considered as the film director whose job is part creative and part technical. An HCI designer have substantial understanding of all areas of designing. The following diagram depicts the analogy −
Several interactive devices are used for the human computer interaction. Some of them are known tools and some are recently developed or are a concept to be developed in the future. In this chapter, we will discuss on some new and old interactive devices.
The touch screen concept was prophesized decades ago, however the platform was acquired recently. Today there are many devices that use touch screen. After vigilant selection of these devices, developers customize their touch screen experiences.
The cheapest and relatively easy way of manufacturing touch screens are the ones using electrodes and a voltage association. Other than the hardware differences, software alone can bring major differences from one touch device to another, even when the same hardware is used.
Along with the innovative designs and new hardware and software, touch screens are likely to grow in a big way in the future. A further development can be made by making a sync between the touch and other devices.
In HCI, touch screen can be considered as a new interactive device.
Gesture recognition is a subject in language technology that has the objective of understanding human movement via mathematical procedures.
Hand gesture recognition is currently the field of focus. This technology is future based.
This new technology magnitudes an advanced association between human and computer where no mechanical devices are used. This new interactive device might terminate the old devices like keyboards and is also heavy on new devices like touch screens.
The technology of transcribing spoken phrases into written text is Speech Recognition. Such technologies can be used in advanced control of many devices such as switching on and off the electrical appliances. Only certain commands are required to be recognized for a complete transcription. However, this cannot be beneficial for big vocabularies.
This HCI device help the user in hands free movement and keep the instruction based technology up to date with the users.
A keyboard can be considered as a primitive device known to all of us today. Keyboard uses an organization of keys/buttons that serves as a mechanical device for a computer. Each key in a keyboard corresponds to a single written symbol or character.
This is the most effective and ancient interactive device between man and machine that has given ideas to develop many more interactive devices as well as has made advancements in itself such as soft screen keyboards for computers and mobile phones.
Response time is the time taken by a device to respond to a request. The request can be anything from a database query to loading a web page. The response time is the sum of the service time and wait time. Transmission time becomes a part of the response time when the response has to travel over a network.
In modern HCI devices, there are several applications installed and most of them function simultaneously or as per the user’s usage. This makes a busier response time. All of that increase in the response time is caused by increase in the wait time. The wait time is due to the running of the requests and the queue of requests following it.
So, it is significant that the response time of a device is faster for which advanced processors are used in modern devices.
HCI design is considered as a problem solving process that has components like planned usage, target area, resources, cost, and viability. It decides on the requirement of product similarities to balance trade-offs.
The following points are the four basic activities of interaction design −
Identifying requirements
Building alternative designs
Developing interactive versions of the designs
Evaluating designs
Three principles for user-centered approach are −
Early focus on users and tasks
Empirical Measurement
Iterative Design
Various methodologies have materialized since the inception that outline the techniques for human–computer interaction. Following are few design methodologies −
Activity Theory − This is an HCI method that describes the framework where the human-computer interactions take place. Activity theory provides reasoning, analytical tools and interaction designs.
Activity Theory − This is an HCI method that describes the framework where the human-computer interactions take place. Activity theory provides reasoning, analytical tools and interaction designs.
User-Centered Design − It provides users the center-stage in designing where they get the opportunity to work with designers and technical practitioners.
User-Centered Design − It provides users the center-stage in designing where they get the opportunity to work with designers and technical practitioners.
Principles of User Interface Design − Tolerance, simplicity, visibility, affordance, consistency, structure and feedback are the seven principles used in interface designing.
Principles of User Interface Design − Tolerance, simplicity, visibility, affordance, consistency, structure and feedback are the seven principles used in interface designing.
Value Sensitive Design − This method is used for developing technology and includes three types of studies − conceptual, empirical and technical.
Conceptual investigations works towards understanding the values of the investors who use technology.
Empirical investigations are qualitative or quantitative design research studies that shows the designer’s understanding of the users’ values.
Technical investigations contain the use of technologies and designs in the conceptual and empirical investigations.
Value Sensitive Design − This method is used for developing technology and includes three types of studies − conceptual, empirical and technical.
Conceptual investigations works towards understanding the values of the investors who use technology.
Conceptual investigations works towards understanding the values of the investors who use technology.
Empirical investigations are qualitative or quantitative design research studies that shows the designer’s understanding of the users’ values.
Empirical investigations are qualitative or quantitative design research studies that shows the designer’s understanding of the users’ values.
Technical investigations contain the use of technologies and designs in the conceptual and empirical investigations.
Technical investigations contain the use of technologies and designs in the conceptual and empirical investigations.
Participatory design process involves all stakeholders in the design process, so that the end result meets the needs they are desiring. This design is used in various areas such as software design, architecture, landscape architecture, product design, sustainability, graphic design, planning, urban design, and even medicine.
Participatory design is not a style, but focus on processes and procedures of designing. It is seen as a way of removing design accountability and origination by designers.
Task Analysis plays an important part in User Requirements Analysis.
Task analysis is the procedure to learn the users and abstract frameworks, the patterns used in workflows, and the chronological implementation of interaction with the GUI. It analyzes the ways in which the user partitions the tasks and sequence them.
Human actions that contributes to a useful objective, aiming at the system, is a task. Task analysis defines performance of users, not computers.
Hierarchical Task Analysis is the procedure of disintegrating tasks into subtasks that could be analyzed using the logical sequence for execution. This would help in achieving the goal in the best possible way.
Task decomposition − Splitting tasks into sub-tasks and in sequence.
Task decomposition − Splitting tasks into sub-tasks and in sequence.
Knowledge-based techniques − Any instructions that users need to know.
Knowledge-based techniques − Any instructions that users need to know.
‘User’ is always the beginning point for a task.
Ethnography − Observation of users’ behavior in the use context.
Ethnography − Observation of users’ behavior in the use context.
Protocol analysis − Observation and documentation of actions of the user. This is achieved by authenticating the user’s thinking. The user is made to think aloud so that the user’s mental logic can be understood.
Protocol analysis − Observation and documentation of actions of the user. This is achieved by authenticating the user’s thinking. The user is made to think aloud so that the user’s mental logic can be understood.
Unlike Hierarchical Task Analysis, Engineering Task Models can be specified formally and are more useful.
Engineering task models have flexible notations, which describes the possible activities clearly.
Engineering task models have flexible notations, which describes the possible activities clearly.
They have organized approaches to support the requirement, analysis, and use of task models in the design.
They have organized approaches to support the requirement, analysis, and use of task models in the design.
They support the recycle of in-condition design solutions to problems that happen throughout applications.
They support the recycle of in-condition design solutions to problems that happen throughout applications.
Finally, they let the automatic tools accessible to support the different phases of the design cycle.
Finally, they let the automatic tools accessible to support the different phases of the design cycle.
CTT is an engineering methodology used for modeling a task and consists of tasks and operators. Operators in CTT are used to portray chronological associations between tasks. Following are the key features of a CTT −
Focus on actions that users wish to accomplish.
Hierarchical structure.
Graphical syntax.
Rich set of sequential operators.
A dialog is the construction of interaction between two or more beings or systems. In HCI, a dialog is studied at three levels −
Lexical − Shape of icons, actual keys pressed, etc., are dealt at this level.
Lexical − Shape of icons, actual keys pressed, etc., are dealt at this level.
Syntactic − The order of inputs and outputs in an interaction are described at this level.
Syntactic − The order of inputs and outputs in an interaction are described at this level.
Semantic − At this level, the effect of dialog on the internal application/data is taken care of.
Semantic − At this level, the effect of dialog on the internal application/data is taken care of.
To represent dialogs, we need formal techniques that serves two purposes −
It helps in understanding the proposed design in a better way.
It helps in understanding the proposed design in a better way.
It helps in analyzing dialogs to identify usability issues. E.g., Questions such as “does the design actually support undo?” can be answered.
It helps in analyzing dialogs to identify usability issues. E.g., Questions such as “does the design actually support undo?” can be answered.
There are many formalism techniques that we can use to signify dialogs. In this chapter, we will discuss on three of these formalism techniques, which are −
The state transition networks (STN)
The state charts
The classical Petri nets
STNs are the most spontaneous, which knows that a dialog fundamentally denotes to a progression from one state of the system to the next.
The syntax of an STN consists of the following two entities −
Circles − A circle refers to a state of the system, which is branded by giving a name to the state.
Circles − A circle refers to a state of the system, which is branded by giving a name to the state.
Arcs − The circles are connected with arcs that refers to the action/event resulting in the transition from the state where the arc initiates, to the state where it ends.
Arcs − The circles are connected with arcs that refers to the action/event resulting in the transition from the state where the arc initiates, to the state where it ends.
StateCharts represent complex reactive systems that extends Finite State Machines (FSM), handle concurrency, and adds memory to FSM. It also simplifies complex system representations. StateCharts has the following states −
Active state − The present state of the underlying FSM.
Active state − The present state of the underlying FSM.
Basic states − These are individual states and are not composed of other states.
Basic states − These are individual states and are not composed of other states.
Super states − These states are composed of other states.
Super states − These states are composed of other states.
Let us see the StateChart Construction of a machine that dispense bottles on inserting coins.
The above diagram explains the entire procedure of a bottle dispensing machine. On pressing the button after inserting coin, the machine will toggle between bottle filling and dispensing modes. When a required request bottle is available, it dispense the bottle. In the background, another procedure runs where any stuck bottle will be cleared. The ‘H’ symbol in Step 4, indicates that a procedure is added to History for future access.
Petri Net is a simple model of active behavior, which has four behavior elements such as − places, transitions, arcs and tokens. Petri Nets provide a graphical explanation for easy understanding.
Place − This element is used to symbolize passive elements of the reactive system. A place is represented by a circle.
Place − This element is used to symbolize passive elements of the reactive system. A place is represented by a circle.
Transition − This element is used to symbolize active elements of the reactive system. Transitions are represented by squares/rectangles.
Transition − This element is used to symbolize active elements of the reactive system. Transitions are represented by squares/rectangles.
Arc − This element is used to represent causal relations. Arc is represented by arrows.
Arc − This element is used to represent causal relations. Arc is represented by arrows.
Token − This element is subject to change. Tokens are represented by small filled circles.
Token − This element is subject to change. Tokens are represented by small filled circles.
Visual materials has assisted in the communication process since ages in form of paintings, sketches, maps, diagrams, photographs, etc. In today’s world, with the invention of technology and its further growth, new potentials are offered for visual information such as thinking and reasoning. As per studies, the command of visual thinking in human-computer interaction (HCI) design is still not discovered completely. So, let us learn the theories that support visual thinking in sense-making activities in HCI design.
An initial terminology for talking about visual thinking was discovered that included concepts such as visual immediacy, visual impetus, visual impedance, and visual metaphors, analogies and associations, in the context of information design for the web.
As such, this design process became well suited as a logical and collaborative method during the design process. Let us discuss in brief the concepts individually.
It is a reasoning process that helps in understanding of information in the visual representation. The term is chosen to highlight its time related quality, which also serves as an indicator of how well the reasoning has been facilitated by the design.
Visual impetus is defined as a stimulus that aims at the increase in engagement in the contextual aspects of the representation.
It is perceived as the opposite of visual immediacy as it is a hindrance in the design of the representation. In relation to reasoning, impedance can be expressed as a slower cognition.
When a visual demonstration is used to understand an idea in terms of another familiar idea it is called a visual metaphor.
When a visual demonstration is used to understand an idea in terms of another familiar idea it is called a visual metaphor.
Visual analogy and conceptual blending are similar to metaphors. Analogy can be defined as an implication from one particular to another. Conceptual blending can be defined as combination of elements and vital relations from varied situations.
Visual analogy and conceptual blending are similar to metaphors. Analogy can be defined as an implication from one particular to another. Conceptual blending can be defined as combination of elements and vital relations from varied situations.
The HCI design can be highly benefited with the use of above mentioned concepts. The concepts are pragmatic in supporting the use of visual procedures in HCI, as well as in the design processes.
Direct manipulation has been acclaimed as a good form of interface design, and are well received by users. Such processes use many source to get the input and finally convert them into an output as desired by the user using inbuilt tools and programs.
“Directness” has been considered as a phenomena that contributes majorly to the manipulation programming. It has the following two aspects.
Distance
Direct Engagement
Distance is an interface that decides the gulfs between a user’s goal and the level of explanation delivered by the systems, with which the user deals. These are referred to as the Gulf of Execution and the Gulf of Evaluation.
The Gulf of Execution
The Gulf of Execution defines the gap/gulf between a user's goal and the device to implement that goal. One of the principal objective of Usability is to diminish this gap by removing barriers and follow steps to minimize the user’s distraction from the intended task that would prevent the flow of the work.
The Gulf of Evaluation
The Gulf of Evaluation is the representation of expectations that the user has interpreted from the system in a design. As per Donald Norman, The gulf is small when the system provides information about its state in a form that is easy to get, is easy to interpret, and matches the way the person thinks of the system.
It is described as a programming where the design directly takes care of the controls of the objects presented by the user and makes a system less difficult to use.
The scrutiny of the execution and evaluation process illuminates the efforts in using a system. It also gives the ways to minimize the mental effort required to use a system.
Even though the immediacy of response and the conversion of objectives to actions has made some tasks easy, all tasks should not be done easily. For example, a repetitive operation is probably best done via a script and not through immediacy.
Even though the immediacy of response and the conversion of objectives to actions has made some tasks easy, all tasks should not be done easily. For example, a repetitive operation is probably best done via a script and not through immediacy.
Direct manipulation interfaces finds it hard to manage variables, or illustration of discrete elements from a class of elements.
Direct manipulation interfaces finds it hard to manage variables, or illustration of discrete elements from a class of elements.
Direct manipulation interfaces may not be accurate as the dependency is on the user rather than on the system.
Direct manipulation interfaces may not be accurate as the dependency is on the user rather than on the system.
An important problem with direct manipulation interfaces is that it directly supports the techniques, the user thinks.
An important problem with direct manipulation interfaces is that it directly supports the techniques, the user thinks.
In HCI, the presentation sequence can be planned according to the task or application requirements. The natural sequence of items in the menu should be taken care of. Main factors in presentation sequence are −
Time
Numeric ordering
Physical properties
A designer must select one of the following prospects when there are no task-related arrangements −
Alphabetic sequence of terms
Grouping of related items
Most frequently used items first
Most important items first
Menus should be organized using task semantics.
Broad-shallow should be preferred to narrow-deep.
Positions should be shown by graphics, numbers or titles.
Subtrees should use items as titles.
Items should be grouped meaningfully.
Items should be sequenced meaningfully.
Brief items should be used.
Consistent grammar, layout and technology should be used.
Type ahead, jump ahead, or other shortcuts should be allowed.
Jumps to previous and main menu should be allowed.
Online help should be considered.
Guidelines for consistency should be defined for the following components −
Titles
Item placement
Instructions
Error messages
Status reports
Appropriate for multiple entry of data fields −
Complete information should be visible to the user.
The display should resemble familiar paper forms.
Some instructions should be given for different types of entries.
Users must be familiar with −
Keyboards
Use of TAB key or mouse to move the cursor
Error correction methods
Field-label meanings
Permissible field contents
Use of the ENTER and/or RETURN key.
Form Fill-in Design Guidelines −
Title should be meaningful.
Instructions should be comprehensible.
Fields should be logically grouped and sequenced.
The form should be visually appealing.
Familiar field labels should be provided.
Consistent terminology and abbreviations should be used.
Convenient cursor movement should be available.
Error correction for individual characters and entire field’s facility should be present.
Error prevention.
Error messages for unacceptable values should be populated.
Optional fields should be clearly marked.
Explanatory messages for fields should be available.
Completion signal should populate.
A database query is the principal mechanism to retrieve information from a database. It consists of predefined format of database questions. Many database management systems use the Structured Query Language (SQL) standard query format.
SELECT DOCUMENT#
FROM JOURNAL-DB
WHERE (DATE >= 2004 AND DATE <= 2008)
AND (LANGUAGE = ENGLISH OR FRENCH)
AND (PUBLISHER = ASIST OR HFES OR ACM)
Users perform better and have better contentment when they can view and control the search. The database query has thus provided substantial amount of help in the human computer interface.
The following points are the five-phase frameworks that clarifies user interfaces for textual search −
Formulation − expressing the search
Formulation − expressing the search
Initiation of action − launching the search
Initiation of action − launching the search
Review of results − reading messages and outcomes
Review of results − reading messages and outcomes
Refinement − formulating the next step
Refinement − formulating the next step
Use − compiling or disseminating insight
Use − compiling or disseminating insight
Following are the major multimedia document search categories.
Preforming an image search in common search engines is not an easy thing to do. However there are sites where image search can be done by entering the image of your choice. Mostly, simple drawing tools are used to build templates to search with. For complex searches such as fingerprint matching, special softwares are developed where the user can search the machine for the predefined data of distinct features.
Map search is another form of multimedia search where the online maps are retrieved through mobile devices and search engines. Though a structured database solution is required for complex searches such as searches with longitude/latitude. With the advanced database options, we can retrieve maps for every possible aspect such as cities, states, countries, world maps, weather sheets, directions, etc.
Some design packages support the search of designs or diagrams as well. E.g., diagrams, blueprints, newspapers, etc.
Sound search can also be done easily through audio search of the database. Though user should clearly speak the words or phrases for search.
New projects such as Infomedia helps in retrieving video searches. They provide an overview of the videos or segmentations of frames from the video.
The frequency of animation search has increased with the popularity of Flash. Now it is possible to search for specific animations such as a moving boat.
Information visualization is the interactive visual illustrations of conceptual data that strengthen human understanding. It has emerged from the research in human-computer interaction and is applied as a critical component in varied fields. It allows users to see, discover, and understand huge amounts of information at once.
Information visualization is also an assumption structure, which is typically followed by formal examination such as statistical hypothesis testing.
Following are the advanced filtering procedures −
Filtering with complex Boolean queries
Automatic filtering
Dynamic queries
Faceted metadata search
Query by example
Implicit search
Collaborative filtering
Multilingual searches
Visual field specification
Hypertext can be defined as the text that has references to hyperlinks with immediate access. Any text that provides a reference to another text can be understood as two nodes of information with the reference forming the link. In hypertext, all the links are active and when clicked, opens something new.
Hypermedia on the other hand, is an information medium that holds different types of media, such as, video, CD, and so forth, as well as hyperlinks.
Hence, both hypertext and hypermedia refers to a system of linked information. A text may refer to links, which may also have visuals or media. So hypertext can be used as a generic term to denote a document, which may in fact be distributed across several media.
Object Action Interface (OAI), can be considered as the next step of the Graphical User Interface (GUI). This model focusses on the priority of the object over the actions.
The OAI model allows the user to perform action on the object. First the object is selected and then the action is performed on the object. Finally, the outcome is shown to the user. In this model, the user does not have to worry about the complexity of any syntactical actions.
The object–action model provides an advantage to the user as they gain a sense of control due to the direct involvement in the design process. The computer serves as a medium to signify different tools.
The Object Oriented programming paradigm plays an important role in human computer interface. It has different components that takes real world objects and performs actions on them, making live interactions between man and the machine. Following are the components of OOPP −
This paradigm describes a real-life system where interactions are among real objects.
This paradigm describes a real-life system where interactions are among real objects.
It models applications as a group of related objects that interact with each other.
It models applications as a group of related objects that interact with each other.
The programming entity is modeled as a class that signifies the collection of related real world objects.
The programming entity is modeled as a class that signifies the collection of related real world objects.
Programming starts with the concept of real world objects and classes.
Programming starts with the concept of real world objects and classes.
Application is divided into numerous packages.
Application is divided into numerous packages.
A package is a collection of classes.
A package is a collection of classes.
A class is an encapsulated group of similar real world objects.
A class is an encapsulated group of similar real world objects.
Real-world objects share two characteristics − They all have state and behavior. Let us see the following pictorial example to understand Objects.
In the above diagram, the object ‘Dog’ has both state and behavior.
An object stores its information in attributes and discloses its behavior through methods. Let us now discuss in brief the different components of object oriented programming.
Hiding the implementation details of the class from the user through an object’s methods is known as data encapsulation. In object oriented programming, it binds the code and the data together and keeps them safe from outside interference.
The point where the software entities interact with each other either in a single computer or in a network is known as pubic interface. This help in data security. Other objects can change the state of an object in an interaction by using only those methods that are exposed to the outer world through a public interface.
A class is a group of objects that has mutual methods. It can be considered as the blueprint using which objects are created.
Classes being passive do not communicate with each other but are used to instantiate objects that interact with each other.
Inheritance as in general terms is the process of acquiring properties. In OOP one object inherit the properties of another object.
Polymorphism is the process of using same method name by multiple classes and redefines methods for the derived classes.
Example
Object oriented interface unites users with the real world manipulating software objects for designing purpose. Let us see the diagram.
Interface design strive to make successful accomplishment of user’s goals with the help of interaction tasks and manipulation.
While creating the OOM for interface design, first of all analysis of user requirements is done. The design specifies the structure and components required for each dialogue. After that, interfaces are developed and tested against the Use Case. Example − Personal banking application.
The sequence of processes documented for every Use Case are then analyzed for key objects. This results into an object model. Key objects are called analysis objects and any diagram showing relationships between these objects is called object diagram.
We have now learnt the basic aspects of human computer interface in this tutorial. From here onwards, we can refer complete reference books and guides that will give in-depth knowledge on programming aspects of this subject. We hope that this tutorial has helped you in understanding the topic and you have gained interest in this subject.
We hope to see the birth of new professions in HCI designing in the future that would take help from the current designing practices. The HCI designer of tomorrow would definitely adopt many skills that are the domain of specialists today. And for the current practice of specialists, we wish them to evolve, as others have done in the past.
In the future, we hope to reinvent the software development tools, making programming useful to people’s work and hobbies. We also hope to understand the software development as a collaborative work and study the impact of software on society.
81 Lectures
9.5 hours
Abhishek And Pukhraj
30 Lectures
1.5 hours
Brad Merrill
63 Lectures
4 hours
Akaaro Consulting And Training
14 Lectures
7 hours
Adrian
10 Lectures
2 hours
Dr Swati Chakraborty
6 Lectures
1 hours
Prabh Kirpa Classes
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1997,
"s": 1772,
"text": "Human Computer Interface (HCI) was previously known as the man-machine studies or man-machine interaction. It deals with the design, execution and assessment of computer systems and related phenomenon that are for human use."
},
{
"code": null,
"e": 2187,
"s": 1997,
"text": "HCI can be used in all disciplines wherever there is a possibility of computer installation. Some of the areas where HCI can be implemented with distinctive importance are mentioned below −"
},
{
"code": null,
"e": 2246,
"s": 2187,
"text": "Computer Science − For application design and engineering."
},
{
"code": null,
"e": 2305,
"s": 2246,
"text": "Computer Science − For application design and engineering."
},
{
"code": null,
"e": 2370,
"s": 2305,
"text": "Psychology − For application of theories and analytical purpose."
},
{
"code": null,
"e": 2435,
"s": 2370,
"text": "Psychology − For application of theories and analytical purpose."
},
{
"code": null,
"e": 2500,
"s": 2435,
"text": "Sociology − For interaction between technology and organization."
},
{
"code": null,
"e": 2565,
"s": 2500,
"text": "Sociology − For interaction between technology and organization."
},
{
"code": null,
"e": 2651,
"s": 2565,
"text": "Industrial Design − For interactive products like mobile phones, microwave oven, etc."
},
{
"code": null,
"e": 2737,
"s": 2651,
"text": "Industrial Design − For interactive products like mobile phones, microwave oven, etc."
},
{
"code": null,
"e": 3054,
"s": 2737,
"text": "The world’s leading organization in HCI is ACM − SIGCHI, which stands for Association for Computer Machinery − Special Interest Group on Computer–Human Interaction. SIGCHI defines Computer Science to be the core discipline of HCI. In India, it emerged as an interaction proposal, mostly based in the field of Design."
},
{
"code": null,
"e": 3209,
"s": 3054,
"text": "The intention of this subject is to learn the ways of designing user-friendly interfaces or interactions. Considering which, we will learn the following −"
},
{
"code": null,
"e": 3256,
"s": 3209,
"text": "Ways to design and assess interactive systems."
},
{
"code": null,
"e": 3303,
"s": 3256,
"text": "Ways to design and assess interactive systems."
},
{
"code": null,
"e": 3372,
"s": 3303,
"text": "Ways to reduce design time through cognitive system and task models."
},
{
"code": null,
"e": 3441,
"s": 3372,
"text": "Ways to reduce design time through cognitive system and task models."
},
{
"code": null,
"e": 3498,
"s": 3441,
"text": "Procedures and heuristics for interactive system design."
},
{
"code": null,
"e": 3555,
"s": 3498,
"text": "Procedures and heuristics for interactive system design."
},
{
"code": null,
"e": 3696,
"s": 3555,
"text": "From the initial computers performing batch processing to the user-centric design, there were several milestones which are mentioned below −"
},
{
"code": null,
"e": 3856,
"s": 3696,
"text": "Early computer (e.g. ENIAC, 1946) − Improvement in the H/W technology brought massive increase in computing power. People started thinking on innovative ideas."
},
{
"code": null,
"e": 4016,
"s": 3856,
"text": "Early computer (e.g. ENIAC, 1946) − Improvement in the H/W technology brought massive increase in computing power. People started thinking on innovative ideas."
},
{
"code": null,
"e": 4155,
"s": 4016,
"text": "Visual Display Unit (1950s) − SAGE (semi-automatic ground environment), an air defense system of the USA used the earliest version of VDU."
},
{
"code": null,
"e": 4294,
"s": 4155,
"text": "Visual Display Unit (1950s) − SAGE (semi-automatic ground environment), an air defense system of the USA used the earliest version of VDU."
},
{
"code": null,
"e": 4436,
"s": 4294,
"text": "Development of the Sketchpad (1962) − Ivan Sutherland developed Sketchpad and proved that computer can be used for more than data processing."
},
{
"code": null,
"e": 4578,
"s": 4436,
"text": "Development of the Sketchpad (1962) − Ivan Sutherland developed Sketchpad and proved that computer can be used for more than data processing."
},
{
"code": null,
"e": 4704,
"s": 4578,
"text": "Douglas Engelbart introduced the idea of programming toolkits (1963) − Smaller systems created larger systems and components."
},
{
"code": null,
"e": 4830,
"s": 4704,
"text": "Douglas Engelbart introduced the idea of programming toolkits (1963) − Smaller systems created larger systems and components."
},
{
"code": null,
"e": 4908,
"s": 4830,
"text": "Introduction of Word Processor, Mouse (1968) − Design of NLS (oNLine System)."
},
{
"code": null,
"e": 4986,
"s": 4908,
"text": "Introduction of Word Processor, Mouse (1968) − Design of NLS (oNLine System)."
},
{
"code": null,
"e": 5074,
"s": 4986,
"text": "Introduction of personal computer Dynabook (1970s) − Developed smalltalk at Xerox PARC."
},
{
"code": null,
"e": 5162,
"s": 5074,
"text": "Introduction of personal computer Dynabook (1970s) − Developed smalltalk at Xerox PARC."
},
{
"code": null,
"e": 5286,
"s": 5162,
"text": "Windows and WIMP interfaces − Simultaneous jobs at one desktop, switching between work and screens, sequential interaction."
},
{
"code": null,
"e": 5410,
"s": 5286,
"text": "Windows and WIMP interfaces − Simultaneous jobs at one desktop, switching between work and screens, sequential interaction."
},
{
"code": null,
"e": 5552,
"s": 5410,
"text": "The idea of metaphor − Xerox star and alto were the first systems to use the concept of metaphors, which led to spontaneity of the interface."
},
{
"code": null,
"e": 5694,
"s": 5552,
"text": "The idea of metaphor − Xerox star and alto were the first systems to use the concept of metaphors, which led to spontaneity of the interface."
},
{
"code": null,
"e": 5834,
"s": 5694,
"text": "Direct Manipulation introduced by Ben Shneiderman (1982) − First used in Apple Mac PC (1984) that reduced the chances for syntactic errors."
},
{
"code": null,
"e": 5974,
"s": 5834,
"text": "Direct Manipulation introduced by Ben Shneiderman (1982) − First used in Apple Mac PC (1984) that reduced the chances for syntactic errors."
},
{
"code": null,
"e": 6062,
"s": 5974,
"text": "Vannevar Bush introduced Hypertext (1945) − To denote the non-linear structure of text."
},
{
"code": null,
"e": 6150,
"s": 6062,
"text": "Vannevar Bush introduced Hypertext (1945) − To denote the non-linear structure of text."
},
{
"code": null,
"e": 6178,
"s": 6150,
"text": "Multimodality (late 1980s)."
},
{
"code": null,
"e": 6206,
"s": 6178,
"text": "Multimodality (late 1980s)."
},
{
"code": null,
"e": 6286,
"s": 6206,
"text": "Computer Supported Cooperative Work (1990’s) − Computer mediated communication."
},
{
"code": null,
"e": 6366,
"s": 6286,
"text": "Computer Supported Cooperative Work (1990’s) − Computer mediated communication."
},
{
"code": null,
"e": 6430,
"s": 6366,
"text": "WWW (1989) − The first graphical browser (Mosaic) came in 1993."
},
{
"code": null,
"e": 6494,
"s": 6430,
"text": "WWW (1989) − The first graphical browser (Mosaic) came in 1993."
},
{
"code": null,
"e": 6637,
"s": 6494,
"text": "Ubiquitous Computing − Currently the most active research area in HCI. Sensor based/context aware computing also known as pervasive computing."
},
{
"code": null,
"e": 6780,
"s": 6637,
"text": "Ubiquitous Computing − Currently the most active research area in HCI. Sensor based/context aware computing also known as pervasive computing."
},
{
"code": null,
"e": 7072,
"s": 6780,
"text": "Some ground-breaking Creation and Graphic Communication designers started showing interest in the field of HCI from the late 80s. Others crossed the threshold by designing program for CD ROM titles. Some of them entered the field by designing for the web and by providing computer trainings."
},
{
"code": null,
"e": 7348,
"s": 7072,
"text": "Even though India is running behind in offering an established course in HCI, there are designers in India who in addition to creativity and artistic expression, consider design to be a problem-solving activity and prefer to work in an area where the demand has not been met."
},
{
"code": null,
"e": 7604,
"s": 7348,
"text": "This urge for designing has often led them to get into innovative fields and get the knowledge through self-study. Later, when HCI prospects arrived in India, designers adopted techniques from usability assessment, user studies, software prototyping, etc."
},
{
"code": null,
"e": 7759,
"s": 7604,
"text": "Ben Shneiderman, an American computer scientist consolidated some implicit facts about designing and came up with the following eight general guidelines −"
},
{
"code": null,
"e": 7783,
"s": 7759,
"text": "Strive for Consistency."
},
{
"code": null,
"e": 7813,
"s": 7783,
"text": "Cater to Universal Usability."
},
{
"code": null,
"e": 7841,
"s": 7813,
"text": "Offer Informative feedback."
},
{
"code": null,
"e": 7874,
"s": 7841,
"text": "Design Dialogs to yield closure."
},
{
"code": null,
"e": 7890,
"s": 7874,
"text": "Prevent Errors."
},
{
"code": null,
"e": 7923,
"s": 7890,
"text": "Permit easy reversal of actions."
},
{
"code": null,
"e": 7958,
"s": 7923,
"text": "Support internal locus of control."
},
{
"code": null,
"e": 7989,
"s": 7958,
"text": "Reduce short term memory load."
},
{
"code": null,
"e": 8252,
"s": 7989,
"text": "These guidelines are beneficial for normal designers as well as interface designers. Using these eight guidelines, it is possible to differentiate a good interface design from a bad one. These are beneficial in experimental assessment of identifying better GUIs."
},
{
"code": null,
"e": 8479,
"s": 8252,
"text": "To assess the interaction between human and computers, Donald Norman in 1988 proposed seven principles. He proposed the seven stages that can be used to transform difficult tasks. Following are the seven principles of Norman −"
},
{
"code": null,
"e": 8532,
"s": 8479,
"text": "Use both knowledge in world & knowledge in the head."
},
{
"code": null,
"e": 8585,
"s": 8532,
"text": "Use both knowledge in world & knowledge in the head."
},
{
"code": null,
"e": 8611,
"s": 8585,
"text": "Simplify task structures."
},
{
"code": null,
"e": 8637,
"s": 8611,
"text": "Simplify task structures."
},
{
"code": null,
"e": 8658,
"s": 8637,
"text": "Make things visible."
},
{
"code": null,
"e": 8679,
"s": 8658,
"text": "Make things visible."
},
{
"code": null,
"e": 8758,
"s": 8679,
"text": "Get the mapping right (User mental model = Conceptual model = Designed model)."
},
{
"code": null,
"e": 8837,
"s": 8758,
"text": "Get the mapping right (User mental model = Conceptual model = Designed model)."
},
{
"code": null,
"e": 8945,
"s": 8837,
"text": "Convert constrains into advantages (Physical constraints, Cultural constraints, Technological constraints)."
},
{
"code": null,
"e": 9053,
"s": 8945,
"text": "Convert constrains into advantages (Physical constraints, Cultural constraints, Technological constraints)."
},
{
"code": null,
"e": 9071,
"s": 9053,
"text": "Design for Error."
},
{
"code": null,
"e": 9089,
"s": 9071,
"text": "Design for Error."
},
{
"code": null,
"e": 9124,
"s": 9089,
"text": "When all else fails − Standardize."
},
{
"code": null,
"e": 9159,
"s": 9124,
"text": "When all else fails − Standardize."
},
{
"code": null,
"e": 9478,
"s": 9159,
"text": "Heuristics evaluation is a methodical procedure to check user interface for usability problems. Once a usability problem is detected in design, they are attended as an integral part of constant design processes. Heuristic evaluation method includes some usability principles such as Nielsen’s ten Usability principles."
},
{
"code": null,
"e": 9507,
"s": 9478,
"text": "Visibility of system status."
},
{
"code": null,
"e": 9544,
"s": 9507,
"text": "Match between system and real world."
},
{
"code": null,
"e": 9570,
"s": 9544,
"text": "User control and freedom."
},
{
"code": null,
"e": 9597,
"s": 9570,
"text": "Consistency and standards."
},
{
"code": null,
"e": 9615,
"s": 9597,
"text": "Error prevention."
},
{
"code": null,
"e": 9647,
"s": 9615,
"text": "Recognition rather than Recall."
},
{
"code": null,
"e": 9682,
"s": 9647,
"text": "Flexibility and efficiency of use."
},
{
"code": null,
"e": 9715,
"s": 9682,
"text": "Aesthetic and minimalist design."
},
{
"code": null,
"e": 9757,
"s": 9715,
"text": "Help, diagnosis and recovery from errors."
},
{
"code": null,
"e": 9780,
"s": 9757,
"text": "Documentation and Help"
},
{
"code": null,
"e": 9955,
"s": 9780,
"text": "The above mentioned ten principles of Nielsen serve as a checklist in evaluating and explaining problems for the heuristic evaluator while auditing an interface or a product."
},
{
"code": null,
"e": 10157,
"s": 9955,
"text": "Some more important HCI design guidelines are presented in this section. General interaction, information display, and data entry are three categories of HCI design guidelines that are explained below."
},
{
"code": null,
"e": 10263,
"s": 10157,
"text": "Guidelines for general interaction are comprehensive advices that focus on general instructions such as −"
},
{
"code": null,
"e": 10278,
"s": 10263,
"text": "Be consistent."
},
{
"code": null,
"e": 10293,
"s": 10278,
"text": "Be consistent."
},
{
"code": null,
"e": 10321,
"s": 10293,
"text": "Offer significant feedback."
},
{
"code": null,
"e": 10349,
"s": 10321,
"text": "Offer significant feedback."
},
{
"code": null,
"e": 10408,
"s": 10349,
"text": "Ask for authentication of any non-trivial critical action."
},
{
"code": null,
"e": 10467,
"s": 10408,
"text": "Ask for authentication of any non-trivial critical action."
},
{
"code": null,
"e": 10508,
"s": 10467,
"text": "Authorize easy reversal of most actions."
},
{
"code": null,
"e": 10549,
"s": 10508,
"text": "Authorize easy reversal of most actions."
},
{
"code": null,
"e": 10626,
"s": 10549,
"text": "Lessen the amount of information that must be remembered in between actions."
},
{
"code": null,
"e": 10703,
"s": 10626,
"text": "Lessen the amount of information that must be remembered in between actions."
},
{
"code": null,
"e": 10752,
"s": 10703,
"text": "Seek competence in dialogue, motion and thought."
},
{
"code": null,
"e": 10801,
"s": 10752,
"text": "Seek competence in dialogue, motion and thought."
},
{
"code": null,
"e": 10818,
"s": 10801,
"text": "Excuse mistakes."
},
{
"code": null,
"e": 10835,
"s": 10818,
"text": "Excuse mistakes."
},
{
"code": null,
"e": 10911,
"s": 10835,
"text": "Classify activities by function and establish screen geography accordingly."
},
{
"code": null,
"e": 10987,
"s": 10911,
"text": "Classify activities by function and establish screen geography accordingly."
},
{
"code": null,
"e": 11037,
"s": 10987,
"text": "Deliver help services that are context sensitive."
},
{
"code": null,
"e": 11087,
"s": 11037,
"text": "Deliver help services that are context sensitive."
},
{
"code": null,
"e": 11151,
"s": 11087,
"text": "Use simple action verbs or short verb phrases to name commands."
},
{
"code": null,
"e": 11215,
"s": 11151,
"text": "Use simple action verbs or short verb phrases to name commands."
},
{
"code": null,
"e": 11418,
"s": 11215,
"text": "Information provided by the HCI should not be incomplete or unclear or else the application will not meet the requirements of the user. To provide better display, the following guidelines are prepared −"
},
{
"code": null,
"e": 11491,
"s": 11418,
"text": "Exhibit only that information that is applicable to the present context."
},
{
"code": null,
"e": 11564,
"s": 11491,
"text": "Exhibit only that information that is applicable to the present context."
},
{
"code": null,
"e": 11669,
"s": 11564,
"text": "Don't burden the user with data, use a presentation layout that allows rapid integration of information."
},
{
"code": null,
"e": 11774,
"s": 11669,
"text": "Don't burden the user with data, use a presentation layout that allows rapid integration of information."
},
{
"code": null,
"e": 11839,
"s": 11774,
"text": "Use standard labels, standard abbreviations and probable colors."
},
{
"code": null,
"e": 11904,
"s": 11839,
"text": "Use standard labels, standard abbreviations and probable colors."
},
{
"code": null,
"e": 11948,
"s": 11904,
"text": "Permit the user to maintain visual context."
},
{
"code": null,
"e": 11992,
"s": 11948,
"text": "Permit the user to maintain visual context."
},
{
"code": null,
"e": 12028,
"s": 11992,
"text": "Generate meaningful error messages."
},
{
"code": null,
"e": 12064,
"s": 12028,
"text": "Generate meaningful error messages."
},
{
"code": null,
"e": 12145,
"s": 12064,
"text": "Use upper and lower case, indentation and text grouping to aid in understanding."
},
{
"code": null,
"e": 12226,
"s": 12145,
"text": "Use upper and lower case, indentation and text grouping to aid in understanding."
},
{
"code": null,
"e": 12297,
"s": 12226,
"text": "Use windows (if available) to classify different types of information."
},
{
"code": null,
"e": 12368,
"s": 12297,
"text": "Use windows (if available) to classify different types of information."
},
{
"code": null,
"e": 12481,
"s": 12368,
"text": "Use analog displays to characterize information that is more easily integrated with this form of representation."
},
{
"code": null,
"e": 12594,
"s": 12481,
"text": "Use analog displays to characterize information that is more easily integrated with this form of representation."
},
{
"code": null,
"e": 12673,
"s": 12594,
"text": "Consider the available geography of the display screen and use it efficiently."
},
{
"code": null,
"e": 12752,
"s": 12673,
"text": "Consider the available geography of the display screen and use it efficiently."
},
{
"code": null,
"e": 12839,
"s": 12752,
"text": "The following guidelines focus on data entry that is another important aspect of HCI −"
},
{
"code": null,
"e": 12896,
"s": 12839,
"text": "Reduce the number of input actions required of the user."
},
{
"code": null,
"e": 12953,
"s": 12896,
"text": "Reduce the number of input actions required of the user."
},
{
"code": null,
"e": 13015,
"s": 12953,
"text": "Uphold steadiness between information display and data input."
},
{
"code": null,
"e": 13077,
"s": 13015,
"text": "Uphold steadiness between information display and data input."
},
{
"code": null,
"e": 13111,
"s": 13077,
"text": "Let the user customize the input."
},
{
"code": null,
"e": 13145,
"s": 13111,
"text": "Let the user customize the input."
},
{
"code": null,
"e": 13228,
"s": 13145,
"text": "Interaction should be flexible but also tuned to the user's favored mode of input."
},
{
"code": null,
"e": 13311,
"s": 13228,
"text": "Interaction should be flexible but also tuned to the user's favored mode of input."
},
{
"code": null,
"e": 13383,
"s": 13311,
"text": "Disable commands that are unsuitable in the context of current actions."
},
{
"code": null,
"e": 13455,
"s": 13383,
"text": "Disable commands that are unsuitable in the context of current actions."
},
{
"code": null,
"e": 13503,
"s": 13455,
"text": "Allow the user to control the interactive flow."
},
{
"code": null,
"e": 13551,
"s": 13503,
"text": "Allow the user to control the interactive flow."
},
{
"code": null,
"e": 13596,
"s": 13551,
"text": "Offer help to assist with all input actions."
},
{
"code": null,
"e": 13641,
"s": 13596,
"text": "Offer help to assist with all input actions."
},
{
"code": null,
"e": 13670,
"s": 13641,
"text": "Remove \"mickey mouse\" input."
},
{
"code": null,
"e": 13699,
"s": 13670,
"text": "Remove \"mickey mouse\" input."
},
{
"code": null,
"e": 14155,
"s": 13699,
"text": "The objective of this chapter is to learn all the aspects of design and development of interactive systems, which are now an important part of our lives. The design and usability of these systems leaves an effect on the quality of people’s relationship to technology. Web applications, games, embedded devices, etc., are all a part of this system, which has become an integral part of our lives. Let us now discuss on some major components of this system."
},
{
"code": null,
"e": 14398,
"s": 14155,
"text": "Usability Engineering is a method in the progress of software and systems, which includes user contribution from the inception of the process and assures the effectiveness of the product through the use of a usability requirement and metrics."
},
{
"code": null,
"e": 14648,
"s": 14398,
"text": "It thus refers to the Usability Function features of the entire process of abstracting, implementing & testing hardware and software products. Requirements gathering stage to installation, marketing and testing of products, all fall in this process."
},
{
"code": null,
"e": 14678,
"s": 14648,
"text": "Effective to use − Functional"
},
{
"code": null,
"e": 14707,
"s": 14678,
"text": "Efficient to use − Efficient"
},
{
"code": null,
"e": 14732,
"s": 14707,
"text": "Error free in use − Safe"
},
{
"code": null,
"e": 14755,
"s": 14732,
"text": "Easy to use − Friendly"
},
{
"code": null,
"e": 14796,
"s": 14755,
"text": "Enjoyable in use − Delightful Experience"
},
{
"code": null,
"e": 14988,
"s": 14796,
"text": "Usability has three components − effectiveness, efficiency and satisfaction, using which, users accomplish their goals in particular environments. Let us look in brief about these components."
},
{
"code": null,
"e": 15059,
"s": 14988,
"text": "Effectiveness − The completeness with which users achieve their goals."
},
{
"code": null,
"e": 15130,
"s": 15059,
"text": "Effectiveness − The completeness with which users achieve their goals."
},
{
"code": null,
"e": 15220,
"s": 15130,
"text": "Efficiency − The competence used in using the resources to effectively achieve the goals."
},
{
"code": null,
"e": 15310,
"s": 15220,
"text": "Efficiency − The competence used in using the resources to effectively achieve the goals."
},
{
"code": null,
"e": 15367,
"s": 15310,
"text": "Satisfaction − The ease of the work system to its users."
},
{
"code": null,
"e": 15424,
"s": 15367,
"text": "Satisfaction − The ease of the work system to its users."
},
{
"code": null,
"e": 15586,
"s": 15424,
"text": "The methodical study on the interaction between people, products, and environment based on experimental assessment. Example: Psychology, Behavioral Science, etc."
},
{
"code": null,
"e": 15758,
"s": 15586,
"text": "The scientific evaluation of the stated usability parameters as per the user’s requirements, competences, prospects, safety and satisfaction is known as usability testing."
},
{
"code": null,
"e": 15988,
"s": 15758,
"text": "Acceptance testing also known as User Acceptance Testing (UAT), is a testing procedure that is performed by the users as a final checkpoint before signing off from a vendor. Let us take an example of the handheld barcode scanner."
},
{
"code": null,
"e": 16176,
"s": 15988,
"text": "A software tool is a programmatic software used to create, maintain, or otherwise support other programs and applications. Some of the commonly used software tools in HCI are as follows −"
},
{
"code": null,
"e": 16319,
"s": 16176,
"text": "Specification Methods − The methods used to specify the GUI. Even though these are lengthy and ambiguous methods, they are easy to understand."
},
{
"code": null,
"e": 16462,
"s": 16319,
"text": "Specification Methods − The methods used to specify the GUI. Even though these are lengthy and ambiguous methods, they are easy to understand."
},
{
"code": null,
"e": 16603,
"s": 16462,
"text": "Grammars − Written Instructions or Expressions that a program would understand. They provide confirmations for completeness and correctness."
},
{
"code": null,
"e": 16744,
"s": 16603,
"text": "Grammars − Written Instructions or Expressions that a program would understand. They provide confirmations for completeness and correctness."
},
{
"code": null,
"e": 16943,
"s": 16744,
"text": "Transition Diagram − Set of nodes and links that can be displayed in text, link frequency, state diagram, etc. They are difficult in evaluating usability, visibility, modularity and synchronization."
},
{
"code": null,
"e": 17142,
"s": 16943,
"text": "Transition Diagram − Set of nodes and links that can be displayed in text, link frequency, state diagram, etc. They are difficult in evaluating usability, visibility, modularity and synchronization."
},
{
"code": null,
"e": 17298,
"s": 17142,
"text": "Statecharts − Chart methods developed for simultaneous user activities and external actions. They provide link-specification with interface building tools."
},
{
"code": null,
"e": 17454,
"s": 17298,
"text": "Statecharts − Chart methods developed for simultaneous user activities and external actions. They provide link-specification with interface building tools."
},
{
"code": null,
"e": 17574,
"s": 17454,
"text": "Interface Building Tools − Design methods that help in designing command languages, data-entry structures, and widgets."
},
{
"code": null,
"e": 17694,
"s": 17574,
"text": "Interface Building Tools − Design methods that help in designing command languages, data-entry structures, and widgets."
},
{
"code": null,
"e": 17807,
"s": 17694,
"text": "Interface Mockup Tools − Tools to develop a quick sketch of GUI. E.g., Microsoft Visio, Visual Studio .Net, etc."
},
{
"code": null,
"e": 17920,
"s": 17807,
"text": "Interface Mockup Tools − Tools to develop a quick sketch of GUI. E.g., Microsoft Visio, Visual Studio .Net, etc."
},
{
"code": null,
"e": 18022,
"s": 17920,
"text": "Software Engineering Tools − Extensive programming tools to provide user interface management system."
},
{
"code": null,
"e": 18124,
"s": 18022,
"text": "Software Engineering Tools − Extensive programming tools to provide user interface management system."
},
{
"code": null,
"e": 18207,
"s": 18124,
"text": "Evaluation Tools − Tools to evaluate the correctness and completeness of programs."
},
{
"code": null,
"e": 18290,
"s": 18207,
"text": "Evaluation Tools − Tools to evaluate the correctness and completeness of programs."
},
{
"code": null,
"e": 18479,
"s": 18290,
"text": "Software engineering is the study of designing, development and preservation of software. It comes in contact with HCI to make the man and machine interaction more vibrant and interactive."
},
{
"code": null,
"e": 18561,
"s": 18479,
"text": "Let us see the following model in software engineering for interactive designing."
},
{
"code": null,
"e": 18782,
"s": 18561,
"text": "The uni-directional movement of the waterfall model of Software Engineering shows that every phase depends on the preceding phase and not vice-versa. However, this model is not suitable for the interactive system design."
},
{
"code": null,
"e": 19070,
"s": 18782,
"text": "The interactive system design shows that every phase depends on each other to serve the purpose of designing and product creation. It is a continuous process as there is so much to know and users keep changing all the time. An interactive system designer should recognize this diversity."
},
{
"code": null,
"e": 19204,
"s": 19070,
"text": "Prototyping is another type of software engineering models that can have a complete range of functionalities of the projected system."
},
{
"code": null,
"e": 19332,
"s": 19204,
"text": "In HCI, prototyping is a trial and partial design that helps users in testing design ideas without executing a complete system."
},
{
"code": null,
"e": 19478,
"s": 19332,
"text": "Example of a prototype can be Sketches. Sketches of interactive design can later be produced into graphical interface. See the following diagram."
},
{
"code": null,
"e": 19598,
"s": 19478,
"text": "The above diagram can be considered as a Low Fidelity Prototype as it uses manual procedures like sketching in a paper."
},
{
"code": null,
"e": 19707,
"s": 19598,
"text": "A Medium Fidelity Prototype involves some but not all procedures of the system. E.g., first screen of a GUI."
},
{
"code": null,
"e": 19854,
"s": 19707,
"text": "Finally, a Hi Fidelity Prototype simulates all the functionalities of the system in a design. This prototype requires, time, money and work force."
},
{
"code": null,
"e": 19963,
"s": 19854,
"text": "The process of collecting feedback from users to improve the design is known as user centered design or UCD."
},
{
"code": null,
"e": 19989,
"s": 19963,
"text": "Passive user involvement."
},
{
"code": null,
"e": 20053,
"s": 19989,
"text": "User’s perception about the new interface may be inappropriate."
},
{
"code": null,
"e": 20101,
"s": 20053,
"text": "Designers may ask incorrect questions to users."
},
{
"code": null,
"e": 20181,
"s": 20101,
"text": "The stages in the following diagram are repeated until the solution is reached."
},
{
"code": null,
"e": 20189,
"s": 20181,
"text": "Diagram"
},
{
"code": null,
"e": 20400,
"s": 20189,
"text": "Graphic User Interface (GUI) is the interface from where a user can operate programs, applications or devices in a computer system. This is where the icons, menus, widgets, labels exist for the users to access."
},
{
"code": null,
"e": 20630,
"s": 20400,
"text": "It is significant that everything in the GUI is arranged in a way that is recognizable and pleasing to the eye, which shows the aesthetic sense of the GUI designer. GUI aesthetics provides a character and identity to any product."
},
{
"code": null,
"e": 20992,
"s": 20630,
"text": "For the past couple of years, majority IT companies in India are hiring designers for HCI related activities. Even multi-national companies started hiring for HCI from India as Indian designers have proven their capabilities in architectural, visual and interaction designs. Thus, Indian HCI designers are not only making a mark in the country, but also abroad."
},
{
"code": null,
"e": 21177,
"s": 20992,
"text": "The profession has boomed in the last decade even when the usability has been there forever. And since new products are developed frequently, the durability prognosis also looks great."
},
{
"code": null,
"e": 21404,
"s": 21177,
"text": "As per an estimation made on usability specialists, there are mere 1,000 experts in India. The overall requirement is around 60,000. Out of all the designers working in the country, HCI designers count for approximately 2.77%."
},
{
"code": null,
"e": 21686,
"s": 21404,
"text": "Let us take a known analogy that can be understood by everyone. A film director is a person who with his/her experience can work on script writing, acting, editing, and cinematography. He/She can be considered as the only person accountable for all the creative phases of the film."
},
{
"code": null,
"e": 21905,
"s": 21686,
"text": "Similarly, HCI can be considered as the film director whose job is part creative and part technical. An HCI designer have substantial understanding of all areas of designing. The following diagram depicts the analogy −"
},
{
"code": null,
"e": 22161,
"s": 21905,
"text": "Several interactive devices are used for the human computer interaction. Some of them are known tools and some are recently developed or are a concept to be developed in the future. In this chapter, we will discuss on some new and old interactive devices."
},
{
"code": null,
"e": 22407,
"s": 22161,
"text": "The touch screen concept was prophesized decades ago, however the platform was acquired recently. Today there are many devices that use touch screen. After vigilant selection of these devices, developers customize their touch screen experiences."
},
{
"code": null,
"e": 22683,
"s": 22407,
"text": "The cheapest and relatively easy way of manufacturing touch screens are the ones using electrodes and a voltage association. Other than the hardware differences, software alone can bring major differences from one touch device to another, even when the same hardware is used."
},
{
"code": null,
"e": 22897,
"s": 22683,
"text": "Along with the innovative designs and new hardware and software, touch screens are likely to grow in a big way in the future. A further development can be made by making a sync between the touch and other devices."
},
{
"code": null,
"e": 22965,
"s": 22897,
"text": "In HCI, touch screen can be considered as a new interactive device."
},
{
"code": null,
"e": 23196,
"s": 22965,
"text": "Gesture recognition is a subject in language technology that has the objective of understanding human movement via mathematical procedures.\nHand gesture recognition is currently the field of focus. This technology is future based."
},
{
"code": null,
"e": 23444,
"s": 23196,
"text": "This new technology magnitudes an advanced association between human and computer where no mechanical devices are used. This new interactive device might terminate the old devices like keyboards and is also heavy on new devices like touch screens."
},
{
"code": null,
"e": 23792,
"s": 23444,
"text": "The technology of transcribing spoken phrases into written text is Speech Recognition. Such technologies can be used in advanced control of many devices such as switching on and off the electrical appliances. Only certain commands are required to be recognized for a complete transcription. However, this cannot be beneficial for big vocabularies."
},
{
"code": null,
"e": 23914,
"s": 23792,
"text": "This HCI device help the user in hands free movement and keep the instruction based technology up to date with the users."
},
{
"code": null,
"e": 24164,
"s": 23914,
"text": "A keyboard can be considered as a primitive device known to all of us today. Keyboard uses an organization of keys/buttons that serves as a mechanical device for a computer. Each key in a keyboard corresponds to a single written symbol or character."
},
{
"code": null,
"e": 24414,
"s": 24164,
"text": "This is the most effective and ancient interactive device between man and machine that has given ideas to develop many more interactive devices as well as has made advancements in itself such as soft screen keyboards for computers and mobile phones."
},
{
"code": null,
"e": 24722,
"s": 24414,
"text": "Response time is the time taken by a device to respond to a request. The request can be anything from a database query to loading a web page. The response time is the sum of the service time and wait time. Transmission time becomes a part of the response time when the response has to travel over a network."
},
{
"code": null,
"e": 25064,
"s": 24722,
"text": "In modern HCI devices, there are several applications installed and most of them function simultaneously or as per the user’s usage. This makes a busier response time. All of that increase in the response time is caused by increase in the wait time. The wait time is due to the running of the requests and the queue of requests following it."
},
{
"code": null,
"e": 25189,
"s": 25064,
"text": "So, it is significant that the response time of a device is faster for which advanced processors are used in modern devices."
},
{
"code": null,
"e": 25405,
"s": 25189,
"text": "HCI design is considered as a problem solving process that has components like planned usage, target area, resources, cost, and viability. It decides on the requirement of product similarities to balance trade-offs."
},
{
"code": null,
"e": 25480,
"s": 25405,
"text": "The following points are the four basic activities of interaction design −"
},
{
"code": null,
"e": 25505,
"s": 25480,
"text": "Identifying requirements"
},
{
"code": null,
"e": 25534,
"s": 25505,
"text": "Building alternative designs"
},
{
"code": null,
"e": 25581,
"s": 25534,
"text": "Developing interactive versions of the designs"
},
{
"code": null,
"e": 25600,
"s": 25581,
"text": "Evaluating designs"
},
{
"code": null,
"e": 25650,
"s": 25600,
"text": "Three principles for user-centered approach are −"
},
{
"code": null,
"e": 25681,
"s": 25650,
"text": "Early focus on users and tasks"
},
{
"code": null,
"e": 25703,
"s": 25681,
"text": "Empirical Measurement"
},
{
"code": null,
"e": 25720,
"s": 25703,
"text": "Iterative Design"
},
{
"code": null,
"e": 25881,
"s": 25720,
"text": "Various methodologies have materialized since the inception that outline the techniques for human–computer interaction. Following are few design methodologies −"
},
{
"code": null,
"e": 26078,
"s": 25881,
"text": "Activity Theory − This is an HCI method that describes the framework where the human-computer interactions take place. Activity theory provides reasoning, analytical tools and interaction designs."
},
{
"code": null,
"e": 26275,
"s": 26078,
"text": "Activity Theory − This is an HCI method that describes the framework where the human-computer interactions take place. Activity theory provides reasoning, analytical tools and interaction designs."
},
{
"code": null,
"e": 26429,
"s": 26275,
"text": "User-Centered Design − It provides users the center-stage in designing where they get the opportunity to work with designers and technical practitioners."
},
{
"code": null,
"e": 26583,
"s": 26429,
"text": "User-Centered Design − It provides users the center-stage in designing where they get the opportunity to work with designers and technical practitioners."
},
{
"code": null,
"e": 26758,
"s": 26583,
"text": "Principles of User Interface Design − Tolerance, simplicity, visibility, affordance, consistency, structure and feedback are the seven principles used in interface designing."
},
{
"code": null,
"e": 26933,
"s": 26758,
"text": "Principles of User Interface Design − Tolerance, simplicity, visibility, affordance, consistency, structure and feedback are the seven principles used in interface designing."
},
{
"code": null,
"e": 27444,
"s": 26933,
"text": "Value Sensitive Design − This method is used for developing technology and includes three types of studies − conceptual, empirical and technical.\n\nConceptual investigations works towards understanding the values of the investors who use technology.\nEmpirical investigations are qualitative or quantitative design research studies that shows the designer’s understanding of the users’ values.\nTechnical investigations contain the use of technologies and designs in the conceptual and empirical investigations.\n\n"
},
{
"code": null,
"e": 27590,
"s": 27444,
"text": "Value Sensitive Design − This method is used for developing technology and includes three types of studies − conceptual, empirical and technical."
},
{
"code": null,
"e": 27692,
"s": 27590,
"text": "Conceptual investigations works towards understanding the values of the investors who use technology."
},
{
"code": null,
"e": 27794,
"s": 27692,
"text": "Conceptual investigations works towards understanding the values of the investors who use technology."
},
{
"code": null,
"e": 27937,
"s": 27794,
"text": "Empirical investigations are qualitative or quantitative design research studies that shows the designer’s understanding of the users’ values."
},
{
"code": null,
"e": 28080,
"s": 27937,
"text": "Empirical investigations are qualitative or quantitative design research studies that shows the designer’s understanding of the users’ values."
},
{
"code": null,
"e": 28197,
"s": 28080,
"text": "Technical investigations contain the use of technologies and designs in the conceptual and empirical investigations."
},
{
"code": null,
"e": 28314,
"s": 28197,
"text": "Technical investigations contain the use of technologies and designs in the conceptual and empirical investigations."
},
{
"code": null,
"e": 28641,
"s": 28314,
"text": "Participatory design process involves all stakeholders in the design process, so that the end result meets the needs they are desiring. This design is used in various areas such as software design, architecture, landscape architecture, product design, sustainability, graphic design, planning, urban design, and even medicine."
},
{
"code": null,
"e": 28814,
"s": 28641,
"text": "Participatory design is not a style, but focus on processes and procedures of designing. It is seen as a way of removing design accountability and origination by designers."
},
{
"code": null,
"e": 28883,
"s": 28814,
"text": "Task Analysis plays an important part in User Requirements Analysis."
},
{
"code": null,
"e": 29135,
"s": 28883,
"text": "Task analysis is the procedure to learn the users and abstract frameworks, the patterns used in workflows, and the chronological implementation of interaction with the GUI. It analyzes the ways in which the user partitions the tasks and sequence them."
},
{
"code": null,
"e": 29281,
"s": 29135,
"text": "Human actions that contributes to a useful objective, aiming at the system, is a task. Task analysis defines performance of users, not computers."
},
{
"code": null,
"e": 29492,
"s": 29281,
"text": "Hierarchical Task Analysis is the procedure of disintegrating tasks into subtasks that could be analyzed using the logical sequence for execution. This would help in achieving the goal in the best possible way."
},
{
"code": null,
"e": 29561,
"s": 29492,
"text": "Task decomposition − Splitting tasks into sub-tasks and in sequence."
},
{
"code": null,
"e": 29630,
"s": 29561,
"text": "Task decomposition − Splitting tasks into sub-tasks and in sequence."
},
{
"code": null,
"e": 29701,
"s": 29630,
"text": "Knowledge-based techniques − Any instructions that users need to know."
},
{
"code": null,
"e": 29772,
"s": 29701,
"text": "Knowledge-based techniques − Any instructions that users need to know."
},
{
"code": null,
"e": 29821,
"s": 29772,
"text": "‘User’ is always the beginning point for a task."
},
{
"code": null,
"e": 29886,
"s": 29821,
"text": "Ethnography − Observation of users’ behavior in the use context."
},
{
"code": null,
"e": 29951,
"s": 29886,
"text": "Ethnography − Observation of users’ behavior in the use context."
},
{
"code": null,
"e": 30164,
"s": 29951,
"text": "Protocol analysis − Observation and documentation of actions of the user. This is achieved by authenticating the user’s thinking. The user is made to think aloud so that the user’s mental logic can be understood."
},
{
"code": null,
"e": 30377,
"s": 30164,
"text": "Protocol analysis − Observation and documentation of actions of the user. This is achieved by authenticating the user’s thinking. The user is made to think aloud so that the user’s mental logic can be understood."
},
{
"code": null,
"e": 30483,
"s": 30377,
"text": "Unlike Hierarchical Task Analysis, Engineering Task Models can be specified formally and are more useful."
},
{
"code": null,
"e": 30581,
"s": 30483,
"text": "Engineering task models have flexible notations, which describes the possible activities clearly."
},
{
"code": null,
"e": 30679,
"s": 30581,
"text": "Engineering task models have flexible notations, which describes the possible activities clearly."
},
{
"code": null,
"e": 30786,
"s": 30679,
"text": "They have organized approaches to support the requirement, analysis, and use of task models in the design."
},
{
"code": null,
"e": 30893,
"s": 30786,
"text": "They have organized approaches to support the requirement, analysis, and use of task models in the design."
},
{
"code": null,
"e": 31000,
"s": 30893,
"text": "They support the recycle of in-condition design solutions to problems that happen throughout applications."
},
{
"code": null,
"e": 31107,
"s": 31000,
"text": "They support the recycle of in-condition design solutions to problems that happen throughout applications."
},
{
"code": null,
"e": 31209,
"s": 31107,
"text": "Finally, they let the automatic tools accessible to support the different phases of the design cycle."
},
{
"code": null,
"e": 31311,
"s": 31209,
"text": "Finally, they let the automatic tools accessible to support the different phases of the design cycle."
},
{
"code": null,
"e": 31528,
"s": 31311,
"text": "CTT is an engineering methodology used for modeling a task and consists of tasks and operators. Operators in CTT are used to portray chronological associations between tasks. Following are the key features of a CTT −"
},
{
"code": null,
"e": 31576,
"s": 31528,
"text": "Focus on actions that users wish to accomplish."
},
{
"code": null,
"e": 31600,
"s": 31576,
"text": "Hierarchical structure."
},
{
"code": null,
"e": 31618,
"s": 31600,
"text": "Graphical syntax."
},
{
"code": null,
"e": 31652,
"s": 31618,
"text": "Rich set of sequential operators."
},
{
"code": null,
"e": 31781,
"s": 31652,
"text": "A dialog is the construction of interaction between two or more beings or systems. In HCI, a dialog is studied at three levels −"
},
{
"code": null,
"e": 31859,
"s": 31781,
"text": "Lexical − Shape of icons, actual keys pressed, etc., are dealt at this level."
},
{
"code": null,
"e": 31937,
"s": 31859,
"text": "Lexical − Shape of icons, actual keys pressed, etc., are dealt at this level."
},
{
"code": null,
"e": 32028,
"s": 31937,
"text": "Syntactic − The order of inputs and outputs in an interaction are described at this level."
},
{
"code": null,
"e": 32119,
"s": 32028,
"text": "Syntactic − The order of inputs and outputs in an interaction are described at this level."
},
{
"code": null,
"e": 32217,
"s": 32119,
"text": "Semantic − At this level, the effect of dialog on the internal application/data is taken care of."
},
{
"code": null,
"e": 32315,
"s": 32217,
"text": "Semantic − At this level, the effect of dialog on the internal application/data is taken care of."
},
{
"code": null,
"e": 32390,
"s": 32315,
"text": "To represent dialogs, we need formal techniques that serves two purposes −"
},
{
"code": null,
"e": 32453,
"s": 32390,
"text": "It helps in understanding the proposed design in a better way."
},
{
"code": null,
"e": 32516,
"s": 32453,
"text": "It helps in understanding the proposed design in a better way."
},
{
"code": null,
"e": 32658,
"s": 32516,
"text": "It helps in analyzing dialogs to identify usability issues. E.g., Questions such as “does the design actually support undo?” can be answered."
},
{
"code": null,
"e": 32800,
"s": 32658,
"text": "It helps in analyzing dialogs to identify usability issues. E.g., Questions such as “does the design actually support undo?” can be answered."
},
{
"code": null,
"e": 32957,
"s": 32800,
"text": "There are many formalism techniques that we can use to signify dialogs. In this chapter, we will discuss on three of these formalism techniques, which are −"
},
{
"code": null,
"e": 32993,
"s": 32957,
"text": "The state transition networks (STN)"
},
{
"code": null,
"e": 33010,
"s": 32993,
"text": "The state charts"
},
{
"code": null,
"e": 33035,
"s": 33010,
"text": "The classical Petri nets"
},
{
"code": null,
"e": 33173,
"s": 33035,
"text": "STNs are the most spontaneous, which knows that a dialog fundamentally denotes to a progression from one state of the system to the next."
},
{
"code": null,
"e": 33235,
"s": 33173,
"text": "The syntax of an STN consists of the following two entities −"
},
{
"code": null,
"e": 33335,
"s": 33235,
"text": "Circles − A circle refers to a state of the system, which is branded by giving a name to the state."
},
{
"code": null,
"e": 33435,
"s": 33335,
"text": "Circles − A circle refers to a state of the system, which is branded by giving a name to the state."
},
{
"code": null,
"e": 33606,
"s": 33435,
"text": "Arcs − The circles are connected with arcs that refers to the action/event resulting in the transition from the state where the arc initiates, to the state where it ends."
},
{
"code": null,
"e": 33777,
"s": 33606,
"text": "Arcs − The circles are connected with arcs that refers to the action/event resulting in the transition from the state where the arc initiates, to the state where it ends."
},
{
"code": null,
"e": 34000,
"s": 33777,
"text": "StateCharts represent complex reactive systems that extends Finite State Machines (FSM), handle concurrency, and adds memory to FSM. It also simplifies complex system representations. StateCharts has the following states −"
},
{
"code": null,
"e": 34056,
"s": 34000,
"text": "Active state − The present state of the underlying FSM."
},
{
"code": null,
"e": 34112,
"s": 34056,
"text": "Active state − The present state of the underlying FSM."
},
{
"code": null,
"e": 34193,
"s": 34112,
"text": "Basic states − These are individual states and are not composed of other states."
},
{
"code": null,
"e": 34274,
"s": 34193,
"text": "Basic states − These are individual states and are not composed of other states."
},
{
"code": null,
"e": 34332,
"s": 34274,
"text": "Super states − These states are composed of other states."
},
{
"code": null,
"e": 34390,
"s": 34332,
"text": "Super states − These states are composed of other states."
},
{
"code": null,
"e": 34484,
"s": 34390,
"text": "Let us see the StateChart Construction of a machine that dispense bottles on inserting coins."
},
{
"code": null,
"e": 34921,
"s": 34484,
"text": "The above diagram explains the entire procedure of a bottle dispensing machine. On pressing the button after inserting coin, the machine will toggle between bottle filling and dispensing modes. When a required request bottle is available, it dispense the bottle. In the background, another procedure runs where any stuck bottle will be cleared. The ‘H’ symbol in Step 4, indicates that a procedure is added to History for future access."
},
{
"code": null,
"e": 35117,
"s": 34921,
"text": "Petri Net is a simple model of active behavior, which has four behavior elements such as − places, transitions, arcs and tokens. Petri Nets provide a graphical explanation for easy understanding."
},
{
"code": null,
"e": 35236,
"s": 35117,
"text": "Place − This element is used to symbolize passive elements of the reactive system. A place is represented by a circle."
},
{
"code": null,
"e": 35355,
"s": 35236,
"text": "Place − This element is used to symbolize passive elements of the reactive system. A place is represented by a circle."
},
{
"code": null,
"e": 35493,
"s": 35355,
"text": "Transition − This element is used to symbolize active elements of the reactive system. Transitions are represented by squares/rectangles."
},
{
"code": null,
"e": 35631,
"s": 35493,
"text": "Transition − This element is used to symbolize active elements of the reactive system. Transitions are represented by squares/rectangles."
},
{
"code": null,
"e": 35719,
"s": 35631,
"text": "Arc − This element is used to represent causal relations. Arc is represented by arrows."
},
{
"code": null,
"e": 35807,
"s": 35719,
"text": "Arc − This element is used to represent causal relations. Arc is represented by arrows."
},
{
"code": null,
"e": 35898,
"s": 35807,
"text": "Token − This element is subject to change. Tokens are represented by small filled circles."
},
{
"code": null,
"e": 35989,
"s": 35898,
"text": "Token − This element is subject to change. Tokens are represented by small filled circles."
},
{
"code": null,
"e": 36509,
"s": 35989,
"text": "Visual materials has assisted in the communication process since ages in form of paintings, sketches, maps, diagrams, photographs, etc. In today’s world, with the invention of technology and its further growth, new potentials are offered for visual information such as thinking and reasoning. As per studies, the command of visual thinking in human-computer interaction (HCI) design is still not discovered completely. So, let us learn the theories that support visual thinking in sense-making activities in HCI design."
},
{
"code": null,
"e": 36764,
"s": 36509,
"text": "An initial terminology for talking about visual thinking was discovered that included concepts such as visual immediacy, visual impetus, visual impedance, and visual metaphors, analogies and associations, in the context of information design for the web."
},
{
"code": null,
"e": 36928,
"s": 36764,
"text": "As such, this design process became well suited as a logical and collaborative method during the design process. Let us discuss in brief the concepts individually."
},
{
"code": null,
"e": 37181,
"s": 36928,
"text": "It is a reasoning process that helps in understanding of information in the visual representation. The term is chosen to highlight its time related quality, which also serves as an indicator of how well the reasoning has been facilitated by the design."
},
{
"code": null,
"e": 37310,
"s": 37181,
"text": "Visual impetus is defined as a stimulus that aims at the increase in engagement in the contextual aspects of the representation."
},
{
"code": null,
"e": 37496,
"s": 37310,
"text": "It is perceived as the opposite of visual immediacy as it is a hindrance in the design of the representation. In relation to reasoning, impedance can be expressed as a slower cognition."
},
{
"code": null,
"e": 37620,
"s": 37496,
"text": "When a visual demonstration is used to understand an idea in terms of another familiar idea it is called a visual metaphor."
},
{
"code": null,
"e": 37744,
"s": 37620,
"text": "When a visual demonstration is used to understand an idea in terms of another familiar idea it is called a visual metaphor."
},
{
"code": null,
"e": 37988,
"s": 37744,
"text": "Visual analogy and conceptual blending are similar to metaphors. Analogy can be defined as an implication from one particular to another. Conceptual blending can be defined as combination of elements and vital relations from varied situations."
},
{
"code": null,
"e": 38232,
"s": 37988,
"text": "Visual analogy and conceptual blending are similar to metaphors. Analogy can be defined as an implication from one particular to another. Conceptual blending can be defined as combination of elements and vital relations from varied situations."
},
{
"code": null,
"e": 38427,
"s": 38232,
"text": "The HCI design can be highly benefited with the use of above mentioned concepts. The concepts are pragmatic in supporting the use of visual procedures in HCI, as well as in the design processes."
},
{
"code": null,
"e": 38679,
"s": 38427,
"text": "Direct manipulation has been acclaimed as a good form of interface design, and are well received by users. Such processes use many source to get the input and finally convert them into an output as desired by the user using inbuilt tools and programs."
},
{
"code": null,
"e": 38819,
"s": 38679,
"text": "“Directness” has been considered as a phenomena that contributes majorly to the manipulation programming. It has the following two aspects."
},
{
"code": null,
"e": 38828,
"s": 38819,
"text": "Distance"
},
{
"code": null,
"e": 38846,
"s": 38828,
"text": "Direct Engagement"
},
{
"code": null,
"e": 39073,
"s": 38846,
"text": "Distance is an interface that decides the gulfs between a user’s goal and the level of explanation delivered by the systems, with which the user deals. These are referred to as the Gulf of Execution and the Gulf of Evaluation."
},
{
"code": null,
"e": 39095,
"s": 39073,
"text": "The Gulf of Execution"
},
{
"code": null,
"e": 39404,
"s": 39095,
"text": "The Gulf of Execution defines the gap/gulf between a user's goal and the device to implement that goal. One of the principal objective of Usability is to diminish this gap by removing barriers and follow steps to minimize the user’s distraction from the intended task that would prevent the flow of the work."
},
{
"code": null,
"e": 39427,
"s": 39404,
"text": "The Gulf of Evaluation"
},
{
"code": null,
"e": 39746,
"s": 39427,
"text": "The Gulf of Evaluation is the representation of expectations that the user has interpreted from the system in a design. As per Donald Norman, The gulf is small when the system provides information about its state in a form that is easy to get, is easy to interpret, and matches the way the person thinks of the system."
},
{
"code": null,
"e": 39911,
"s": 39746,
"text": "It is described as a programming where the design directly takes care of the controls of the objects presented by the user and makes a system less difficult to use."
},
{
"code": null,
"e": 40086,
"s": 39911,
"text": "The scrutiny of the execution and evaluation process illuminates the efforts in using a system. It also gives the ways to minimize the mental effort required to use a system."
},
{
"code": null,
"e": 40329,
"s": 40086,
"text": "Even though the immediacy of response and the conversion of objectives to actions has made some tasks easy, all tasks should not be done easily. For example, a repetitive operation is probably best done via a script and not through immediacy."
},
{
"code": null,
"e": 40572,
"s": 40329,
"text": "Even though the immediacy of response and the conversion of objectives to actions has made some tasks easy, all tasks should not be done easily. For example, a repetitive operation is probably best done via a script and not through immediacy."
},
{
"code": null,
"e": 40701,
"s": 40572,
"text": "Direct manipulation interfaces finds it hard to manage variables, or illustration of discrete elements from a class of elements."
},
{
"code": null,
"e": 40830,
"s": 40701,
"text": "Direct manipulation interfaces finds it hard to manage variables, or illustration of discrete elements from a class of elements."
},
{
"code": null,
"e": 40941,
"s": 40830,
"text": "Direct manipulation interfaces may not be accurate as the dependency is on the user rather than on the system."
},
{
"code": null,
"e": 41052,
"s": 40941,
"text": "Direct manipulation interfaces may not be accurate as the dependency is on the user rather than on the system."
},
{
"code": null,
"e": 41171,
"s": 41052,
"text": "An important problem with direct manipulation interfaces is that it directly supports the techniques, the user thinks."
},
{
"code": null,
"e": 41290,
"s": 41171,
"text": "An important problem with direct manipulation interfaces is that it directly supports the techniques, the user thinks."
},
{
"code": null,
"e": 41501,
"s": 41290,
"text": "In HCI, the presentation sequence can be planned according to the task or application requirements. The natural sequence of items in the menu should be taken care of. Main factors in presentation sequence are −"
},
{
"code": null,
"e": 41506,
"s": 41501,
"text": "Time"
},
{
"code": null,
"e": 41523,
"s": 41506,
"text": "Numeric ordering"
},
{
"code": null,
"e": 41543,
"s": 41523,
"text": "Physical properties"
},
{
"code": null,
"e": 41643,
"s": 41543,
"text": "A designer must select one of the following prospects when there are no task-related arrangements −"
},
{
"code": null,
"e": 41672,
"s": 41643,
"text": "Alphabetic sequence of terms"
},
{
"code": null,
"e": 41698,
"s": 41672,
"text": "Grouping of related items"
},
{
"code": null,
"e": 41731,
"s": 41698,
"text": "Most frequently used items first"
},
{
"code": null,
"e": 41758,
"s": 41731,
"text": "Most important items first"
},
{
"code": null,
"e": 41806,
"s": 41758,
"text": "Menus should be organized using task semantics."
},
{
"code": null,
"e": 41856,
"s": 41806,
"text": "Broad-shallow should be preferred to narrow-deep."
},
{
"code": null,
"e": 41914,
"s": 41856,
"text": "Positions should be shown by graphics, numbers or titles."
},
{
"code": null,
"e": 41951,
"s": 41914,
"text": "Subtrees should use items as titles."
},
{
"code": null,
"e": 41989,
"s": 41951,
"text": "Items should be grouped meaningfully."
},
{
"code": null,
"e": 42029,
"s": 41989,
"text": "Items should be sequenced meaningfully."
},
{
"code": null,
"e": 42057,
"s": 42029,
"text": "Brief items should be used."
},
{
"code": null,
"e": 42115,
"s": 42057,
"text": "Consistent grammar, layout and technology should be used."
},
{
"code": null,
"e": 42177,
"s": 42115,
"text": "Type ahead, jump ahead, or other shortcuts should be allowed."
},
{
"code": null,
"e": 42228,
"s": 42177,
"text": "Jumps to previous and main menu should be allowed."
},
{
"code": null,
"e": 42262,
"s": 42228,
"text": "Online help should be considered."
},
{
"code": null,
"e": 42338,
"s": 42262,
"text": "Guidelines for consistency should be defined for the following components −"
},
{
"code": null,
"e": 42345,
"s": 42338,
"text": "Titles"
},
{
"code": null,
"e": 42360,
"s": 42345,
"text": "Item placement"
},
{
"code": null,
"e": 42373,
"s": 42360,
"text": "Instructions"
},
{
"code": null,
"e": 42388,
"s": 42373,
"text": "Error messages"
},
{
"code": null,
"e": 42403,
"s": 42388,
"text": "Status reports"
},
{
"code": null,
"e": 42451,
"s": 42403,
"text": "Appropriate for multiple entry of data fields −"
},
{
"code": null,
"e": 42503,
"s": 42451,
"text": "Complete information should be visible to the user."
},
{
"code": null,
"e": 42553,
"s": 42503,
"text": "The display should resemble familiar paper forms."
},
{
"code": null,
"e": 42619,
"s": 42553,
"text": "Some instructions should be given for different types of entries."
},
{
"code": null,
"e": 42649,
"s": 42619,
"text": "Users must be familiar with −"
},
{
"code": null,
"e": 42659,
"s": 42649,
"text": "Keyboards"
},
{
"code": null,
"e": 42702,
"s": 42659,
"text": "Use of TAB key or mouse to move the cursor"
},
{
"code": null,
"e": 42727,
"s": 42702,
"text": "Error correction methods"
},
{
"code": null,
"e": 42748,
"s": 42727,
"text": "Field-label meanings"
},
{
"code": null,
"e": 42775,
"s": 42748,
"text": "Permissible field contents"
},
{
"code": null,
"e": 42811,
"s": 42775,
"text": "Use of the ENTER and/or RETURN key."
},
{
"code": null,
"e": 42844,
"s": 42811,
"text": "Form Fill-in Design Guidelines −"
},
{
"code": null,
"e": 42872,
"s": 42844,
"text": "Title should be meaningful."
},
{
"code": null,
"e": 42911,
"s": 42872,
"text": "Instructions should be comprehensible."
},
{
"code": null,
"e": 42961,
"s": 42911,
"text": "Fields should be logically grouped and sequenced."
},
{
"code": null,
"e": 43000,
"s": 42961,
"text": "The form should be visually appealing."
},
{
"code": null,
"e": 43042,
"s": 43000,
"text": "Familiar field labels should be provided."
},
{
"code": null,
"e": 43099,
"s": 43042,
"text": "Consistent terminology and abbreviations should be used."
},
{
"code": null,
"e": 43147,
"s": 43099,
"text": "Convenient cursor movement should be available."
},
{
"code": null,
"e": 43237,
"s": 43147,
"text": "Error correction for individual characters and entire field’s facility should be present."
},
{
"code": null,
"e": 43255,
"s": 43237,
"text": "Error prevention."
},
{
"code": null,
"e": 43315,
"s": 43255,
"text": "Error messages for unacceptable values should be populated."
},
{
"code": null,
"e": 43357,
"s": 43315,
"text": "Optional fields should be clearly marked."
},
{
"code": null,
"e": 43410,
"s": 43357,
"text": "Explanatory messages for fields should be available."
},
{
"code": null,
"e": 43445,
"s": 43410,
"text": "Completion signal should populate."
},
{
"code": null,
"e": 43682,
"s": 43445,
"text": "A database query is the principal mechanism to retrieve information from a database. It consists of predefined format of database questions. Many database management systems use the Structured Query Language (SQL) standard query format."
},
{
"code": null,
"e": 43828,
"s": 43682,
"text": "SELECT DOCUMENT#\nFROM JOURNAL-DB\nWHERE (DATE >= 2004 AND DATE <= 2008)\nAND (LANGUAGE = ENGLISH OR FRENCH)\nAND (PUBLISHER = ASIST OR HFES OR ACM)\n"
},
{
"code": null,
"e": 44017,
"s": 43828,
"text": "Users perform better and have better contentment when they can view and control the search. The database query has thus provided substantial amount of help in the human computer interface."
},
{
"code": null,
"e": 44120,
"s": 44017,
"text": "The following points are the five-phase frameworks that clarifies user interfaces for textual search −"
},
{
"code": null,
"e": 44156,
"s": 44120,
"text": "Formulation − expressing the search"
},
{
"code": null,
"e": 44192,
"s": 44156,
"text": "Formulation − expressing the search"
},
{
"code": null,
"e": 44236,
"s": 44192,
"text": "Initiation of action − launching the search"
},
{
"code": null,
"e": 44280,
"s": 44236,
"text": "Initiation of action − launching the search"
},
{
"code": null,
"e": 44330,
"s": 44280,
"text": "Review of results − reading messages and outcomes"
},
{
"code": null,
"e": 44380,
"s": 44330,
"text": "Review of results − reading messages and outcomes"
},
{
"code": null,
"e": 44419,
"s": 44380,
"text": "Refinement − formulating the next step"
},
{
"code": null,
"e": 44458,
"s": 44419,
"text": "Refinement − formulating the next step"
},
{
"code": null,
"e": 44499,
"s": 44458,
"text": "Use − compiling or disseminating insight"
},
{
"code": null,
"e": 44540,
"s": 44499,
"text": "Use − compiling or disseminating insight"
},
{
"code": null,
"e": 44603,
"s": 44540,
"text": "Following are the major multimedia document search categories."
},
{
"code": null,
"e": 45016,
"s": 44603,
"text": "Preforming an image search in common search engines is not an easy thing to do. However there are sites where image search can be done by entering the image of your choice. Mostly, simple drawing tools are used to build templates to search with. For complex searches such as fingerprint matching, special softwares are developed where the user can search the machine for the predefined data of distinct features."
},
{
"code": null,
"e": 45419,
"s": 45016,
"text": "Map search is another form of multimedia search where the online maps are retrieved through mobile devices and search engines. Though a structured database solution is required for complex searches such as searches with longitude/latitude. With the advanced database options, we can retrieve maps for every possible aspect such as cities, states, countries, world maps, weather sheets, directions, etc."
},
{
"code": null,
"e": 45536,
"s": 45419,
"text": "Some design packages support the search of designs or diagrams as well. E.g., diagrams, blueprints, newspapers, etc."
},
{
"code": null,
"e": 45677,
"s": 45536,
"text": "Sound search can also be done easily through audio search of the database. Though user should clearly speak the words or phrases for search."
},
{
"code": null,
"e": 45826,
"s": 45677,
"text": "New projects such as Infomedia helps in retrieving video searches. They provide an overview of the videos or segmentations of frames from the video."
},
{
"code": null,
"e": 45980,
"s": 45826,
"text": "The frequency of animation search has increased with the popularity of Flash. Now it is possible to search for specific animations such as a moving boat."
},
{
"code": null,
"e": 46308,
"s": 45980,
"text": "Information visualization is the interactive visual illustrations of conceptual data that strengthen human understanding. It has emerged from the research in human-computer interaction and is applied as a critical component in varied fields. It allows users to see, discover, and understand huge amounts of information at once."
},
{
"code": null,
"e": 46457,
"s": 46308,
"text": "Information visualization is also an assumption structure, which is typically followed by formal examination such as statistical hypothesis testing."
},
{
"code": null,
"e": 46507,
"s": 46457,
"text": "Following are the advanced filtering procedures −"
},
{
"code": null,
"e": 46546,
"s": 46507,
"text": "Filtering with complex Boolean queries"
},
{
"code": null,
"e": 46566,
"s": 46546,
"text": "Automatic filtering"
},
{
"code": null,
"e": 46582,
"s": 46566,
"text": "Dynamic queries"
},
{
"code": null,
"e": 46606,
"s": 46582,
"text": "Faceted metadata search"
},
{
"code": null,
"e": 46623,
"s": 46606,
"text": "Query by example"
},
{
"code": null,
"e": 46639,
"s": 46623,
"text": "Implicit search"
},
{
"code": null,
"e": 46663,
"s": 46639,
"text": "Collaborative filtering"
},
{
"code": null,
"e": 46685,
"s": 46663,
"text": "Multilingual searches"
},
{
"code": null,
"e": 46712,
"s": 46685,
"text": "Visual field specification"
},
{
"code": null,
"e": 47018,
"s": 46712,
"text": "Hypertext can be defined as the text that has references to hyperlinks with immediate access. Any text that provides a reference to another text can be understood as two nodes of information with the reference forming the link. In hypertext, all the links are active and when clicked, opens something new."
},
{
"code": null,
"e": 47167,
"s": 47018,
"text": "Hypermedia on the other hand, is an information medium that holds different types of media, such as, video, CD, and so forth, as well as hyperlinks."
},
{
"code": null,
"e": 47431,
"s": 47167,
"text": "Hence, both hypertext and hypermedia refers to a system of linked information. A text may refer to links, which may also have visuals or media. So hypertext can be used as a generic term to denote a document, which may in fact be distributed across several media."
},
{
"code": null,
"e": 47604,
"s": 47431,
"text": "Object Action Interface (OAI), can be considered as the next step of the Graphical User Interface (GUI). This model focusses on the priority of the object over the actions."
},
{
"code": null,
"e": 47883,
"s": 47604,
"text": "The OAI model allows the user to perform action on the object. First the object is selected and then the action is performed on the object. Finally, the outcome is shown to the user. In this model, the user does not have to worry about the complexity of any syntactical actions."
},
{
"code": null,
"e": 48086,
"s": 47883,
"text": "The object–action model provides an advantage to the user as they gain a sense of control due to the direct involvement in the design process. The computer serves as a medium to signify different tools."
},
{
"code": null,
"e": 48361,
"s": 48086,
"text": "The Object Oriented programming paradigm plays an important role in human computer interface. It has different components that takes real world objects and performs actions on them, making live interactions between man and the machine. Following are the components of OOPP −"
},
{
"code": null,
"e": 48447,
"s": 48361,
"text": "This paradigm describes a real-life system where interactions are among real objects."
},
{
"code": null,
"e": 48533,
"s": 48447,
"text": "This paradigm describes a real-life system where interactions are among real objects."
},
{
"code": null,
"e": 48617,
"s": 48533,
"text": "It models applications as a group of related objects that interact with each other."
},
{
"code": null,
"e": 48701,
"s": 48617,
"text": "It models applications as a group of related objects that interact with each other."
},
{
"code": null,
"e": 48807,
"s": 48701,
"text": "The programming entity is modeled as a class that signifies the collection of related real world objects."
},
{
"code": null,
"e": 48913,
"s": 48807,
"text": "The programming entity is modeled as a class that signifies the collection of related real world objects."
},
{
"code": null,
"e": 48984,
"s": 48913,
"text": "Programming starts with the concept of real world objects and classes."
},
{
"code": null,
"e": 49055,
"s": 48984,
"text": "Programming starts with the concept of real world objects and classes."
},
{
"code": null,
"e": 49102,
"s": 49055,
"text": "Application is divided into numerous packages."
},
{
"code": null,
"e": 49149,
"s": 49102,
"text": "Application is divided into numerous packages."
},
{
"code": null,
"e": 49187,
"s": 49149,
"text": "A package is a collection of classes."
},
{
"code": null,
"e": 49225,
"s": 49187,
"text": "A package is a collection of classes."
},
{
"code": null,
"e": 49289,
"s": 49225,
"text": "A class is an encapsulated group of similar real world objects."
},
{
"code": null,
"e": 49353,
"s": 49289,
"text": "A class is an encapsulated group of similar real world objects."
},
{
"code": null,
"e": 49500,
"s": 49353,
"text": "Real-world objects share two characteristics − They all have state and behavior. Let us see the following pictorial example to understand Objects."
},
{
"code": null,
"e": 49568,
"s": 49500,
"text": "In the above diagram, the object ‘Dog’ has both state and behavior."
},
{
"code": null,
"e": 49744,
"s": 49568,
"text": "An object stores its information in attributes and discloses its behavior through methods. Let us now discuss in brief the different components of object oriented programming."
},
{
"code": null,
"e": 49984,
"s": 49744,
"text": "Hiding the implementation details of the class from the user through an object’s methods is known as data encapsulation. In object oriented programming, it binds the code and the data together and keeps them safe from outside interference."
},
{
"code": null,
"e": 50306,
"s": 49984,
"text": "The point where the software entities interact with each other either in a single computer or in a network is known as pubic interface. This help in data security. Other objects can change the state of an object in an interaction by using only those methods that are exposed to the outer world through a public interface."
},
{
"code": null,
"e": 50432,
"s": 50306,
"text": "A class is a group of objects that has mutual methods. It can be considered as the blueprint using which objects are created."
},
{
"code": null,
"e": 50556,
"s": 50432,
"text": "Classes being passive do not communicate with each other but are used to instantiate objects that interact with each other."
},
{
"code": null,
"e": 50688,
"s": 50556,
"text": "Inheritance as in general terms is the process of acquiring properties. In OOP one object inherit the properties of another object."
},
{
"code": null,
"e": 50809,
"s": 50688,
"text": "Polymorphism is the process of using same method name by multiple classes and redefines methods for the derived classes."
},
{
"code": null,
"e": 50817,
"s": 50809,
"text": "Example"
},
{
"code": null,
"e": 50953,
"s": 50817,
"text": "Object oriented interface unites users with the real world manipulating software objects for designing purpose. Let us see the diagram."
},
{
"code": null,
"e": 51080,
"s": 50953,
"text": "Interface design strive to make successful accomplishment of user’s goals with the help of interaction tasks and manipulation."
},
{
"code": null,
"e": 51365,
"s": 51080,
"text": "While creating the OOM for interface design, first of all analysis of user requirements is done. The design specifies the structure and components required for each dialogue. After that, interfaces are developed and tested against the Use Case. Example − Personal banking application."
},
{
"code": null,
"e": 51617,
"s": 51365,
"text": "The sequence of processes documented for every Use Case are then analyzed for key objects. This results into an object model. Key objects are called analysis objects and any diagram showing relationships between these objects is called object diagram."
},
{
"code": null,
"e": 51957,
"s": 51617,
"text": "We have now learnt the basic aspects of human computer interface in this tutorial. From here onwards, we can refer complete reference books and guides that will give in-depth knowledge on programming aspects of this subject. We hope that this tutorial has helped you in understanding the topic and you have gained interest in this subject."
},
{
"code": null,
"e": 52299,
"s": 51957,
"text": "We hope to see the birth of new professions in HCI designing in the future that would take help from the current designing practices. The HCI designer of tomorrow would definitely adopt many skills that are the domain of specialists today. And for the current practice of specialists, we wish them to evolve, as others have done in the past."
},
{
"code": null,
"e": 52543,
"s": 52299,
"text": "In the future, we hope to reinvent the software development tools, making programming useful to people’s work and hobbies. We also hope to understand the software development as a collaborative work and study the impact of software on society."
},
{
"code": null,
"e": 52578,
"s": 52543,
"text": "\n 81 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 52600,
"s": 52578,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 52635,
"s": 52600,
"text": "\n 30 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 52649,
"s": 52635,
"text": " Brad Merrill"
},
{
"code": null,
"e": 52682,
"s": 52649,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 52714,
"s": 52682,
"text": " Akaaro Consulting And Training"
},
{
"code": null,
"e": 52747,
"s": 52714,
"text": "\n 14 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 52755,
"s": 52747,
"text": " Adrian"
},
{
"code": null,
"e": 52788,
"s": 52755,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 52810,
"s": 52788,
"text": " Dr Swati Chakraborty"
},
{
"code": null,
"e": 52842,
"s": 52810,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 52863,
"s": 52842,
"text": " Prabh Kirpa Classes"
},
{
"code": null,
"e": 52870,
"s": 52863,
"text": " Print"
},
{
"code": null,
"e": 52881,
"s": 52870,
"text": " Add Notes"
}
] |
Decimal count of a Number in JavaScript | We are required to write a JavaScript function that takes in a number which may be an integer
or a floating-point number.
If it's a floating-point number, we have to return the count of numbers after the decimal point.
Otherwise we should return 0.
The code for this will be −
const num1 = 1.123456789;
const num2 = 123456789;
const decimalCount = num => {
// Convert to String
const numStr = String(num);
// String Contains Decimal
if (numStr.includes('.')) {
return numStr.split('.')[1].length;
};
// String Does Not Contain Decimal
return 0;
}
console.log(decimalCount(num1)) // 9
console.log(decimalCount(num2)) // 0
The output in the console will be −
9
0 | [
{
"code": null,
"e": 1184,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a number which may be an integer\nor a floating-point number."
},
{
"code": null,
"e": 1281,
"s": 1184,
"text": "If it's a floating-point number, we have to return the count of numbers after the decimal point."
},
{
"code": null,
"e": 1311,
"s": 1281,
"text": "Otherwise we should return 0."
},
{
"code": null,
"e": 1339,
"s": 1311,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1710,
"s": 1339,
"text": "const num1 = 1.123456789;\nconst num2 = 123456789;\nconst decimalCount = num => {\n // Convert to String\n const numStr = String(num);\n // String Contains Decimal\n if (numStr.includes('.')) {\n return numStr.split('.')[1].length;\n };\n // String Does Not Contain Decimal\n return 0;\n}\nconsole.log(decimalCount(num1)) // 9\nconsole.log(decimalCount(num2)) // 0"
},
{
"code": null,
"e": 1746,
"s": 1710,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 1750,
"s": 1746,
"text": "9\n0"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.