title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Calculate distance and duration between two places using google distance matrix API in Python?
|
We almost all use google maps to check distance between source and destination and check the travel time. For developers and enthusiasts, google provide ‘google distance matrix API’ to calculate the distance and duration between two places.
To use google distance matrix api, we need google maps API keys, which you can get from below link:
https://developers.google.com/maps/documentation/distance-matrix/get-api-key
We can accomplish this by using different python library, like:
Pandas
googlemaps
Requests
Json
I am using very basic requests and json library. Using pandas you can fill multiple source and destination places at a time and get the result in csv file.
Below is the program to implement the same:
# Import required library
import requests
import json
#Enter your source and destination city
originPoint = input("Please enter your origin city: ")
destinationPoint= input("Please enter your destination city: ")
#Place your google map API_KEY to a variable
apiKey = 'YOUR_API_KEY'
#Store google maps api url in a variable
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'
# call get method of request module and store respose object
r = requests.get(url + 'origins = ' + originPoint + '&destinations = ' + destinationPoint + '&key = ' + apiKey)
#Get json format result from the above response object
res = r.json()
#print the value of res
print(res)
Please enter your origin city: Delhi
Please enter your destination city: Karnataka
{'destination_addresses': [‘Karnataka, India’],'origin_addresses': [‘Delhi, India’], 'rows': [{'elements': [{'distance': {'text': '1,942 km', 'value': 1941907}, 'duration': {'text': '1 day 9 hours', 'value': 120420},
'status': 'OK'}]}], 'status': 'OK'}
|
[
{
"code": null,
"e": 1303,
"s": 1062,
"text": "We almost all use google maps to check distance between source and destination and check the travel time. For developers and enthusiasts, google provide ‘google distance matrix API’ to calculate the distance and duration between two places."
},
{
"code": null,
"e": 1403,
"s": 1303,
"text": "To use google distance matrix api, we need google maps API keys, which you can get from below link:"
},
{
"code": null,
"e": 1480,
"s": 1403,
"text": "https://developers.google.com/maps/documentation/distance-matrix/get-api-key"
},
{
"code": null,
"e": 1544,
"s": 1480,
"text": "We can accomplish this by using different python library, like:"
},
{
"code": null,
"e": 1551,
"s": 1544,
"text": "Pandas"
},
{
"code": null,
"e": 1562,
"s": 1551,
"text": "googlemaps"
},
{
"code": null,
"e": 1571,
"s": 1562,
"text": "Requests"
},
{
"code": null,
"e": 1576,
"s": 1571,
"text": "Json"
},
{
"code": null,
"e": 1732,
"s": 1576,
"text": "I am using very basic requests and json library. Using pandas you can fill multiple source and destination places at a time and get the result in csv file."
},
{
"code": null,
"e": 1776,
"s": 1732,
"text": "Below is the program to implement the same:"
},
{
"code": null,
"e": 2443,
"s": 1776,
"text": "# Import required library\nimport requests\nimport json\n#Enter your source and destination city\noriginPoint = input(\"Please enter your origin city: \")\ndestinationPoint= input(\"Please enter your destination city: \")\n#Place your google map API_KEY to a variable\napiKey = 'YOUR_API_KEY'\n#Store google maps api url in a variable\nurl = 'https://maps.googleapis.com/maps/api/distancematrix/json?'\n# call get method of request module and store respose object\nr = requests.get(url + 'origins = ' + originPoint + '&destinations = ' + destinationPoint + '&key = ' + apiKey)\n#Get json format result from the above response object\nres = r.json()\n#print the value of res\nprint(res)"
},
{
"code": null,
"e": 2779,
"s": 2443,
"text": "Please enter your origin city: Delhi\nPlease enter your destination city: Karnataka\n{'destination_addresses': [‘Karnataka, India’],'origin_addresses': [‘Delhi, India’], 'rows': [{'elements': [{'distance': {'text': '1,942 km', 'value': 1941907}, 'duration': {'text': '1 day 9 hours', 'value': 120420},\n'status': 'OK'}]}], 'status': 'OK'}"
}
] |
Bessel's Interpolation - GeeksforGeeks
|
25 May, 2021
Interpolation is the technique of estimating the value of a function for any intermediate value of the independent variable, while the process of computing the value of the function outside the given range is called extrapolation.
Central differences : The central difference operator d is defined by the relations :
Similarly, high order central differences are defined as :
Note – The central differences on the same horizontal line have the same suffix
Bessel’s Interpolation formula –
It is very useful when u = 1/2. It gives a better estimate when 1/4 < u < 3/4 Here f(0) is the origin point usually taken to be mid point, since Bessel’s is used to interpolate near the center. h is called the interval of difference and u = ( x – f(0) ) / h, Here f(0) is term at the origin chosen.
Examples –Input : Value at 27.4 ?
Output :
Value at 27.4 is 3.64968
Implementation of Bessel’s Interpolation –
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to interpolate using Bessel's interpolation#include <bits/stdc++.h>using namespace std; // calculating u mentioned in the formulafloat ucal(float u, int n){ if (n == 0) return 1; float temp = u; for (int i = 1; i <= n / 2; i++) temp = temp * (u - i); for (int i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // calculating factorial of given number nint fact(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} int main(){ // Number of values given int n = 6; float x[] = { 25, 26, 27, 28, 29, 30 }; // y[][] is used for difference table // with y[][0] used for input float y[n][n]; y[0][0] = 4.000; y[1][0] = 3.846; y[2][0] = 3.704; y[3][0] = 3.571; y[4][0] = 3.448; y[5][0] = 3.333; // Calculating the central difference table for (int i = 1; i < n; i++) for (int j = 0; j < n - i; j++) y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; // Displaying the central difference table for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) cout << setw(4) << y[i][j] << "\t"; cout << endl; } // value to interpolate at float value = 27.4; // Initializing u and sum float sum = (y[2][0] + y[3][0]) / 2; // k is origin thats is f(0) int k; if (n % 2) // origin for odd k = n / 2; else k = n / 2 - 1; // origin for even float u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formula for (int i = 1; i < n; i++) { if (i % 2) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k][i] + y[--k][i]) / (fact(i) * 2)); } cout << "Value at " << value << " is " << sum << endl; return 0;}
// Java Program to interpolate using Bessel's interpolationimport java.text.*;class GFG{// calculating u mentioned in the formulastatic double ucal(double u, int n){ if (n == 0) return 1; double temp = u; for (int i = 1; i <= n / 2; i++) temp = temp * (u - i); for (int i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // calculating factorial of given number nstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} public static void main(String[] args){ // Number of values given int n = 6; double x[] = { 25, 26, 27, 28, 29, 30 }; // y[][] is used for difference table // with y[][0] used for input double[][] y=new double[n][n]; y[0][0] = 4.000; y[1][0] = 3.846; y[2][0] = 3.704; y[3][0] = 3.571; y[4][0] = 3.448; y[5][0] = 3.333; // Calculating the central difference table for (int i = 1; i < n; i++) for (int j = 0; j < n - i; j++) y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; // Displaying the central difference table DecimalFormat df = new DecimalFormat("#.########"); for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) System.out.print(y[i][j]+"\t"); System.out.println(""); } // value to interpolate at double value = 27.4; // Initializing u and sum double sum = (y[2][0] + y[3][0]) / 2; // k is origin thats is f(0) int k; if ((n % 2)>0) // origin for odd k = n / 2; else k = n / 2 - 1; // origin for even double u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formula for (int i = 1; i < n; i++) { if ((i % 2)>0) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k][i] + y[--k][i]) / (fact(i) * 2)); } System.out.printf("Value at "+value+" is %.5f",sum); }}// This code is contributed by mits
# Python3 Program to interpolate# using Bessel's interpolation # calculating u mentioned in the# formuladef ucal(u, n): if (n == 0): return 1; temp = u; for i in range(1, int(n / 2 + 1)): temp = temp * (u - i); for i in range(1, int(n / 2)): temp = temp * (u + i); return temp; # calculating factorial of# given number ndef fact(n): f = 1; for i in range(2, n + 1): f *= i; return f; # Number of values givenn = 6;x = [25, 26, 27, 28, 29, 30]; # y[][] is used for difference# table with y[][0] used for inputy = [[0 for i in range(n)] for j in range(n)];y[0][0] = 4.000;y[1][0] = 3.846;y[2][0] = 3.704;y[3][0] = 3.571;y[4][0] = 3.448;y[5][0] = 3.333; # Calculating the central# difference tablefor i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; # Displaying the central# difference tablefor i in range(n): for j in range(n - i): print(y[i][j], "\t", end = " "); print(""); # value to interpolate atvalue = 27.4; # Initializing u and sumsum = (y[2][0] + y[3][0]) / 2; # k is origin thats is f(0)k = 0;if ((n % 2) > 0): # origin for odd k = int(n / 2);else: k = int(n / 2 - 1); # origin for even u = (value - x[k]) / (x[1] - x[0]); # Solving using bessel's formulafor i in range(1, n): if (i % 2): sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else: sum = sum + (ucal(u, i) * (y[k][i] + y[k - 1][i]) / (fact(i) * 2)); k -= 1; print("Value at", value, "is", round(sum, 5)); # This code is contributed by mits
// C# Program to interpolate using Bessel's interpolation class GFG{// calculating u mentioned in the formulastatic double ucal(double u, int n){ if (n == 0) return 1; double temp = u; for (int i = 1; i <= n / 2; i++) temp = temp * (u - i); for (int i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // calculating factorial of given number nstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} public static void Main(){ // Number of values given int n = 6; double []x = { 25, 26, 27, 28, 29, 30 }; // y[,] is used for difference table // with y[,0] used for input double[,] y=new double[n,n]; y[0,0] = 4.000; y[1,0] = 3.846; y[2,0] = 3.704; y[3,0] = 3.571; y[4,0] = 3.448; y[5,0] = 3.333; // Calculating the central difference table for (int i = 1; i < n; i++) for (int j = 0; j < n - i; j++) y[j,i] = y[j + 1,i - 1] - y[j,i - 1]; // Displaying the central difference table for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) System.Console.Write(y[i,j]+"\t"); System.Console.WriteLine(""); } // value to interpolate at double value = 27.4; // Initializing u and sum double sum = (y[2,0] + y[3,0]) / 2; // k is origin thats is f(0) int k; if ((n % 2)>0) // origin for odd k = n / 2; else k = n / 2 - 1; // origin for even double u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formula for (int i = 1; i < n; i++) { if ((i % 2)>0) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k,i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k,i] + y[--k,i]) / (fact(i) * 2)); } System.Console.WriteLine("Value at "+value+" is "+System.Math.Round(sum,5)); }}// This code is contributed by mits
<?php// PHP Program to interpolate// using Bessel's interpolation // calculating u mentioned// in the formulafunction ucal($u, $n){ if ($n == 0) return 1; $temp = $u; for ($i = 1; $i <= (int)($n / 2); $i++) $temp = $temp * ($u - $i); for ($i = 1; $i < (int)($n / 2); $i++) $temp = $temp * ($u + $i); return $temp;} // calculating factorial// of given number nfunction fact($n){ $f = 1; for ($i = 2; $i <= $n; $i++) $f *= $i; return $f;} // Number of values given$n = 6;$x = array(25, 26, 27, 28, 29, 30); // y[][] is used for difference// table with y[][0] used for input$y;for($i = 0; $i < $n; $i++)for($j = 0; $j < $n; $j++)$y[$i][$j] = 0.0;$y[0][0] = 4.000;$y[1][0] = 3.846;$y[2][0] = 3.704;$y[3][0] = 3.571;$y[4][0] = 3.448;$y[5][0] = 3.333; // Calculating the central// difference tablefor ($i = 1; $i < $n; $i++) for ($j = 0; $j < $n - $i; $j++) $y[$j][$i] = $y[$j + 1][$i - 1] - $y[$j][$i - 1]; // Displaying the central// difference tablefor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n - $i; $j++) echo str_pad($y[$i][$j], 4) . "\t"; echo "\n";} // value to interpolate at$value = 27.4; // Initializing u and sum$sum = ($y[2][0] + $y[3][0]) / 2; // k is origin thats is f(0)$k;if ($n % 2) // origin for odd $k = $n / 2;else $k = $n / 2 - 1; // origin for even $u = ($value - $x[$k]) / ($x[1] - $x[0]); // Solving using// bessel's formulafor ($i = 1; $i < $n; $i++){ if ($i % 2) $sum = $sum + (($u - 0.5) * ucal($u, $i - 1) * $y[$k][$i]) / fact($i); else $sum = $sum + (ucal($u, $i) * ($y[$k][$i] + $y[--$k][$i]) / (fact($i) * 2));} echo "Value at " . $value . " is " . $sum . "\n"; // This code is contributed by mits?>
<script> // Javascript Program to interpolate// using Bessel's interpolation // Calculating u mentioned in the formulafunction ucal(u, n){ if (n == 0) return 1; var temp = u; for(var i = 1; i <= n / 2; i++) temp = temp * (u - i); for(var i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // Calculating factorial of given number nfunction fact(n){ var f = 1; for(var i = 2; i <= n; i++) f *= i; return f;} // Driver code // Number of values givenvar n = 6;var x = [ 25, 26, 27, 28, 29, 30 ]; // y is used for difference table// with y[0] used for inputvar y = Array(n).fill(0.0).map(x => Array(n).fill(0.0));;y[0][0] = 4.000;y[1][0] = 3.846;y[2][0] = 3.704;y[3][0] = 3.571;y[4][0] = 3.448;y[5][0] = 3.333; // Calculating the central difference tablefor(var i = 1; i < n; i++) for(var j = 0; j < n - i; j++) y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; // Displaying the central difference tablefor(var i = 0; i < n; i++){ for(var j = 0; j < n - i; j++) document.write(y[i][j].toFixed(6) + " "); document.write('<br>');} // Value to interpolate atvar value = 27.4; // Initializing u and sumvar sum = (y[2][0] + y[3][0]) / 2; // k is origin thats is f(0)var k; // Origin for oddif ((n % 2) > 0) k = n / 2;else // Origin for even k = n / 2 - 1; var u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formulafor(var i = 1; i < n; i++){ if ((i % 2) > 0) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k][i] + y[--k][i]) / (fact(i) * 2));} document.write("Value at " + value.toFixed(6) + " is " + sum.toFixed(6)); // This code is contributed by Princi Singh </script>
Output:
4 -0.154 0.0120001 -0.00300002 0.00399971 -0.00699902
3.846 -0.142 0.00900006 0.000999689 -0.00299931
3.704 -0.133 0.00999975 -0.00199962
3.571 -0.123 0.00800014
3.448 -0.115
3.333
Value at 27.4 is 3.64968
This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
nidhi_biet
princi singh
statistical-algorithms
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for Decimal to Binary Conversion
Sieve of Eratosthenes
Program for factorial of a number
Operators in C / C++
The Knight's tour problem | Backtracking-1
|
[
{
"code": null,
"e": 24846,
"s": 24818,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 25077,
"s": 24846,
"text": "Interpolation is the technique of estimating the value of a function for any intermediate value of the independent variable, while the process of computing the value of the function outside the given range is called extrapolation."
},
{
"code": null,
"e": 25164,
"s": 25077,
"text": "Central differences : The central difference operator d is defined by the relations : "
},
{
"code": null,
"e": 25224,
"s": 25164,
"text": "Similarly, high order central differences are defined as : "
},
{
"code": null,
"e": 25305,
"s": 25224,
"text": "Note – The central differences on the same horizontal line have the same suffix "
},
{
"code": null,
"e": 25339,
"s": 25305,
"text": "Bessel’s Interpolation formula – "
},
{
"code": null,
"e": 25638,
"s": 25339,
"text": "It is very useful when u = 1/2. It gives a better estimate when 1/4 < u < 3/4 Here f(0) is the origin point usually taken to be mid point, since Bessel’s is used to interpolate near the center. h is called the interval of difference and u = ( x – f(0) ) / h, Here f(0) is term at the origin chosen."
},
{
"code": null,
"e": 25674,
"s": 25638,
"text": "Examples –Input : Value at 27.4 ? "
},
{
"code": null,
"e": 25684,
"s": 25674,
"text": "Output : "
},
{
"code": null,
"e": 25709,
"s": 25684,
"text": "Value at 27.4 is 3.64968"
},
{
"code": null,
"e": 25753,
"s": 25709,
"text": "Implementation of Bessel’s Interpolation – "
},
{
"code": null,
"e": 25757,
"s": 25753,
"text": "C++"
},
{
"code": null,
"e": 25762,
"s": 25757,
"text": "Java"
},
{
"code": null,
"e": 25770,
"s": 25762,
"text": "Python3"
},
{
"code": null,
"e": 25773,
"s": 25770,
"text": "C#"
},
{
"code": null,
"e": 25777,
"s": 25773,
"text": "PHP"
},
{
"code": null,
"e": 25788,
"s": 25777,
"text": "Javascript"
},
{
"code": "// CPP Program to interpolate using Bessel's interpolation#include <bits/stdc++.h>using namespace std; // calculating u mentioned in the formulafloat ucal(float u, int n){ if (n == 0) return 1; float temp = u; for (int i = 1; i <= n / 2; i++) temp = temp * (u - i); for (int i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // calculating factorial of given number nint fact(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} int main(){ // Number of values given int n = 6; float x[] = { 25, 26, 27, 28, 29, 30 }; // y[][] is used for difference table // with y[][0] used for input float y[n][n]; y[0][0] = 4.000; y[1][0] = 3.846; y[2][0] = 3.704; y[3][0] = 3.571; y[4][0] = 3.448; y[5][0] = 3.333; // Calculating the central difference table for (int i = 1; i < n; i++) for (int j = 0; j < n - i; j++) y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; // Displaying the central difference table for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) cout << setw(4) << y[i][j] << \"\\t\"; cout << endl; } // value to interpolate at float value = 27.4; // Initializing u and sum float sum = (y[2][0] + y[3][0]) / 2; // k is origin thats is f(0) int k; if (n % 2) // origin for odd k = n / 2; else k = n / 2 - 1; // origin for even float u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formula for (int i = 1; i < n; i++) { if (i % 2) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k][i] + y[--k][i]) / (fact(i) * 2)); } cout << \"Value at \" << value << \" is \" << sum << endl; return 0;}",
"e": 27646,
"s": 25788,
"text": null
},
{
"code": "// Java Program to interpolate using Bessel's interpolationimport java.text.*;class GFG{// calculating u mentioned in the formulastatic double ucal(double u, int n){ if (n == 0) return 1; double temp = u; for (int i = 1; i <= n / 2; i++) temp = temp * (u - i); for (int i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // calculating factorial of given number nstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} public static void main(String[] args){ // Number of values given int n = 6; double x[] = { 25, 26, 27, 28, 29, 30 }; // y[][] is used for difference table // with y[][0] used for input double[][] y=new double[n][n]; y[0][0] = 4.000; y[1][0] = 3.846; y[2][0] = 3.704; y[3][0] = 3.571; y[4][0] = 3.448; y[5][0] = 3.333; // Calculating the central difference table for (int i = 1; i < n; i++) for (int j = 0; j < n - i; j++) y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; // Displaying the central difference table DecimalFormat df = new DecimalFormat(\"#.########\"); for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) System.out.print(y[i][j]+\"\\t\"); System.out.println(\"\"); } // value to interpolate at double value = 27.4; // Initializing u and sum double sum = (y[2][0] + y[3][0]) / 2; // k is origin thats is f(0) int k; if ((n % 2)>0) // origin for odd k = n / 2; else k = n / 2 - 1; // origin for even double u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formula for (int i = 1; i < n; i++) { if ((i % 2)>0) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k][i] + y[--k][i]) / (fact(i) * 2)); } System.out.printf(\"Value at \"+value+\" is %.5f\",sum); }}// This code is contributed by mits",
"e": 29640,
"s": 27646,
"text": null
},
{
"code": "# Python3 Program to interpolate# using Bessel's interpolation # calculating u mentioned in the# formuladef ucal(u, n): if (n == 0): return 1; temp = u; for i in range(1, int(n / 2 + 1)): temp = temp * (u - i); for i in range(1, int(n / 2)): temp = temp * (u + i); return temp; # calculating factorial of# given number ndef fact(n): f = 1; for i in range(2, n + 1): f *= i; return f; # Number of values givenn = 6;x = [25, 26, 27, 28, 29, 30]; # y[][] is used for difference# table with y[][0] used for inputy = [[0 for i in range(n)] for j in range(n)];y[0][0] = 4.000;y[1][0] = 3.846;y[2][0] = 3.704;y[3][0] = 3.571;y[4][0] = 3.448;y[5][0] = 3.333; # Calculating the central# difference tablefor i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; # Displaying the central# difference tablefor i in range(n): for j in range(n - i): print(y[i][j], \"\\t\", end = \" \"); print(\"\"); # value to interpolate atvalue = 27.4; # Initializing u and sumsum = (y[2][0] + y[3][0]) / 2; # k is origin thats is f(0)k = 0;if ((n % 2) > 0): # origin for odd k = int(n / 2);else: k = int(n / 2 - 1); # origin for even u = (value - x[k]) / (x[1] - x[0]); # Solving using bessel's formulafor i in range(1, n): if (i % 2): sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else: sum = sum + (ucal(u, i) * (y[k][i] + y[k - 1][i]) / (fact(i) * 2)); k -= 1; print(\"Value at\", value, \"is\", round(sum, 5)); # This code is contributed by mits",
"e": 31268,
"s": 29640,
"text": null
},
{
"code": "// C# Program to interpolate using Bessel's interpolation class GFG{// calculating u mentioned in the formulastatic double ucal(double u, int n){ if (n == 0) return 1; double temp = u; for (int i = 1; i <= n / 2; i++) temp = temp * (u - i); for (int i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // calculating factorial of given number nstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} public static void Main(){ // Number of values given int n = 6; double []x = { 25, 26, 27, 28, 29, 30 }; // y[,] is used for difference table // with y[,0] used for input double[,] y=new double[n,n]; y[0,0] = 4.000; y[1,0] = 3.846; y[2,0] = 3.704; y[3,0] = 3.571; y[4,0] = 3.448; y[5,0] = 3.333; // Calculating the central difference table for (int i = 1; i < n; i++) for (int j = 0; j < n - i; j++) y[j,i] = y[j + 1,i - 1] - y[j,i - 1]; // Displaying the central difference table for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) System.Console.Write(y[i,j]+\"\\t\"); System.Console.WriteLine(\"\"); } // value to interpolate at double value = 27.4; // Initializing u and sum double sum = (y[2,0] + y[3,0]) / 2; // k is origin thats is f(0) int k; if ((n % 2)>0) // origin for odd k = n / 2; else k = n / 2 - 1; // origin for even double u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formula for (int i = 1; i < n; i++) { if ((i % 2)>0) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k,i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k,i] + y[--k,i]) / (fact(i) * 2)); } System.Console.WriteLine(\"Value at \"+value+\" is \"+System.Math.Round(sum,5)); }}// This code is contributed by mits",
"e": 33189,
"s": 31268,
"text": null
},
{
"code": "<?php// PHP Program to interpolate// using Bessel's interpolation // calculating u mentioned// in the formulafunction ucal($u, $n){ if ($n == 0) return 1; $temp = $u; for ($i = 1; $i <= (int)($n / 2); $i++) $temp = $temp * ($u - $i); for ($i = 1; $i < (int)($n / 2); $i++) $temp = $temp * ($u + $i); return $temp;} // calculating factorial// of given number nfunction fact($n){ $f = 1; for ($i = 2; $i <= $n; $i++) $f *= $i; return $f;} // Number of values given$n = 6;$x = array(25, 26, 27, 28, 29, 30); // y[][] is used for difference// table with y[][0] used for input$y;for($i = 0; $i < $n; $i++)for($j = 0; $j < $n; $j++)$y[$i][$j] = 0.0;$y[0][0] = 4.000;$y[1][0] = 3.846;$y[2][0] = 3.704;$y[3][0] = 3.571;$y[4][0] = 3.448;$y[5][0] = 3.333; // Calculating the central// difference tablefor ($i = 1; $i < $n; $i++) for ($j = 0; $j < $n - $i; $j++) $y[$j][$i] = $y[$j + 1][$i - 1] - $y[$j][$i - 1]; // Displaying the central// difference tablefor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n - $i; $j++) echo str_pad($y[$i][$j], 4) . \"\\t\"; echo \"\\n\";} // value to interpolate at$value = 27.4; // Initializing u and sum$sum = ($y[2][0] + $y[3][0]) / 2; // k is origin thats is f(0)$k;if ($n % 2) // origin for odd $k = $n / 2;else $k = $n / 2 - 1; // origin for even $u = ($value - $x[$k]) / ($x[1] - $x[0]); // Solving using// bessel's formulafor ($i = 1; $i < $n; $i++){ if ($i % 2) $sum = $sum + (($u - 0.5) * ucal($u, $i - 1) * $y[$k][$i]) / fact($i); else $sum = $sum + (ucal($u, $i) * ($y[$k][$i] + $y[--$k][$i]) / (fact($i) * 2));} echo \"Value at \" . $value . \" is \" . $sum . \"\\n\"; // This code is contributed by mits?>",
"e": 35102,
"s": 33189,
"text": null
},
{
"code": "<script> // Javascript Program to interpolate// using Bessel's interpolation // Calculating u mentioned in the formulafunction ucal(u, n){ if (n == 0) return 1; var temp = u; for(var i = 1; i <= n / 2; i++) temp = temp * (u - i); for(var i = 1; i < n / 2; i++) temp = temp * (u + i); return temp;} // Calculating factorial of given number nfunction fact(n){ var f = 1; for(var i = 2; i <= n; i++) f *= i; return f;} // Driver code // Number of values givenvar n = 6;var x = [ 25, 26, 27, 28, 29, 30 ]; // y is used for difference table// with y[0] used for inputvar y = Array(n).fill(0.0).map(x => Array(n).fill(0.0));;y[0][0] = 4.000;y[1][0] = 3.846;y[2][0] = 3.704;y[3][0] = 3.571;y[4][0] = 3.448;y[5][0] = 3.333; // Calculating the central difference tablefor(var i = 1; i < n; i++) for(var j = 0; j < n - i; j++) y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; // Displaying the central difference tablefor(var i = 0; i < n; i++){ for(var j = 0; j < n - i; j++) document.write(y[i][j].toFixed(6) + \" \"); document.write('<br>');} // Value to interpolate atvar value = 27.4; // Initializing u and sumvar sum = (y[2][0] + y[3][0]) / 2; // k is origin thats is f(0)var k; // Origin for oddif ((n % 2) > 0) k = n / 2;else // Origin for even k = n / 2 - 1; var u = (value - x[k]) / (x[1] - x[0]); // Solving using bessel's formulafor(var i = 1; i < n; i++){ if ((i % 2) > 0) sum = sum + ((u - 0.5) * ucal(u, i - 1) * y[k][i]) / fact(i); else sum = sum + (ucal(u, i) * (y[k][i] + y[--k][i]) / (fact(i) * 2));} document.write(\"Value at \" + value.toFixed(6) + \" is \" + sum.toFixed(6)); // This code is contributed by Princi Singh </script>",
"e": 36922,
"s": 35102,
"text": null
},
{
"code": null,
"e": 36931,
"s": 36922,
"text": "Output: "
},
{
"code": null,
"e": 37210,
"s": 36931,
"text": " 4 -0.154 0.0120001 -0.00300002 0.00399971 -0.00699902 \n3.846 -0.142 0.00900006 0.000999689 -0.00299931 \n3.704 -0.133 0.00999975 -0.00199962 \n3.571 -0.123 0.00800014 \n3.448 -0.115 \n3.333 \nValue at 27.4 is 3.64968"
},
{
"code": null,
"e": 37630,
"s": 37210,
"text": "This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37643,
"s": 37630,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 37654,
"s": 37643,
"text": "nidhi_biet"
},
{
"code": null,
"e": 37667,
"s": 37654,
"text": "princi singh"
},
{
"code": null,
"e": 37690,
"s": 37667,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 37703,
"s": 37690,
"text": "Mathematical"
},
{
"code": null,
"e": 37716,
"s": 37703,
"text": "Mathematical"
},
{
"code": null,
"e": 37814,
"s": 37716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37838,
"s": 37814,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 37880,
"s": 37838,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 37923,
"s": 37880,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 37937,
"s": 37923,
"text": "Prime Numbers"
},
{
"code": null,
"e": 37986,
"s": 37937,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 38027,
"s": 37986,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 38049,
"s": 38027,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 38083,
"s": 38049,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 38104,
"s": 38083,
"text": "Operators in C / C++"
}
] |
Master Apache Airflow: How to Install and Setup the Environment in 10 Minutes | by Dario Radečić | Towards Data Science
|
Apache Airflow is an open-source workflow management platform (source), and is a must-know technology for modern-day data scientists and engineers.
Today you’ll learn how to install the platform on a virtual machine, configure it, and establish an SSH connection through Terminal and Visual Studio Code.
The article is structured as follows:
Step 1: Download and Install Ubuntu Server
Step 2: Establish an SSH Connection Through Terminal
Step 3: Install Apache Airflow
Step 4: Establish an SSH Connection Through Visual Studio Code
Conclusion
Let’s start with the easiest step. I assume you already have VirtualBox installed. If that’s not the case, please install it before proceeding.
We’ll start by downloading the Ubuntu Server ISO file. It’s around 1GB download, so it shouldn’t take too long:
While it’s downloading, you can configure the virtual machine. Go over to VirtualBox and create a new machine according to the following image:
From there, just click on Next a couple of times and choose an appropriate RAM and storage configuration. I’ve gone with 4GB for the RAM and 25GB for the storage — but feel free to allocate differently.
Once done, you’ll have a new virtual machine on your list:
Let’s tweak a couple of more things while the ISO is downloading. Open the Settings for the new machine and go to Network. Under Advanced, click on the Port Forwarding button:
We’ll need to forward two ports:
Guest 8080 to Host 8250 (or any other, the documentation recommends 8080, but that one is occupied on my machine) for Airflow UIGuest 22 to Host 2222 for SSH connection
Guest 8080 to Host 8250 (or any other, the documentation recommends 8080, but that one is occupied on my machine) for Airflow UI
Guest 22 to Host 2222 for SSH connection
Once done, your window should look like this:
And that’s all — configuration-wise. The ISO file has hopefully been downloaded by now, so run the virtual machine and load in the ISO file for the installation. Install the OS as you normally would. You’ll need to create a user — I’ve called mine airflow.
Here’s a screenshot from the installation:
If you see something similar, then you’re on the right track. Once the installation finishes, you can restart the VM and log in with your user. And that’s it — Ubuntu Server installed!
We can now establish an SSH connection from Terminal (or PuTTY if you’re on Windows).
For macOS and Linux, you’ll have to enter the following line into the Terminal:
ssh -p 2222 airflow@localhost
As shown on the image below:
Keep in mind that airflow indicates the username you have to your user upon installation.
The installation of Apache Airflow is a multi-step process. The whole thing is Python-based, and Ubuntu Server doesn’t ship with Python 3. The following command will change that:
sudo apt install python3-pip
Now you have Python 3.8.x installed (or some newer version), so you’re ready to install Airflow. The following Terminal command will do just that:
sudo pip3 install “apache-airflow==2.0.2” — constraint “https://raw.githubusercontent.com/apache/airflow/constraints-2.0.2/constraints-3.8.txt"
Please keep in mind:
Replace 2.0.2 with the version you want
Relace constraints-3.8.txt with your Python version. For example, if you’re using Python 3.9.x, it should be: constraints-3.9.txt
Airflow installed! But that doesn’t mean it’s configured. You’ll also need to initialize the database and create the user. The following command initializes the database for Airflow:
airflow db init
And the following one creates the user:
airflow users create — username admin — firstname <your_first_name> — lastname <your_last_name> — role Admin — email <your_email>
Once done, you can run both Airflow Webserver as a daemon with the following commands:
airflow webserver -D
And that’s it — Apache Airflow is now running!
To verify, open a web browser and go to localhost:8250 (replace 8250 with a host port for Airflow). You should see the following screen:
To continue, enter the database user credentials created a minute ago and click on Sign In. You’ll immediately be presented with the following screen:
And that’s it — you’re in! Don’t worry about a ton of DAGs that are loaded initially. You can quickly delete them from the web application or specify not to load them in the Airflow configuration.
Up next, let’s see how to establish a remote SSH connection to your virtual machine from Visual Studio Code.
If you’re anything like me, a manual file transfer from the host to the client is just too much work. Luckily, a free code editor — Visual Studio Code — can manage the connection for you.
To start, install a free plugin called Remote — SSH:
From there, press on the little blue button on the bottom left corner, and choose the Connect to Host option:
Up next, enter the connection command identical to the one you’ve entered in Terminal:
Visual Studio Code will ask you to add the connection configuration to your list of SSH configurations, so select the first option:
Once again, click on the little blue button to connect to the localhost:
Once you do so, a new Visual Studio Code window will pop up, and you’ll have to enter the password. It’s the same password you’ve chosen for the Ubuntu Server user:
And finally, you can click on the Open Folder button to open any directory on the remote host. Let’s open up the /home/airflow folder:
And that’s it — you’re ready to create your first Airflow DAG. Make sure to put them inside the dags folder (you’ll have to create it first), as that’s where Airflow will try to find them. You can always alter the configuration file, but that’s out of the scope for today.
Let’s wrap things up in the next section.
And there you have it — Apache Airflow installed inside a virtual machine. You could install Airflow locally or with Docker, but I’ve found this approach more common in my professional life.
Up next, we’ll explore how to create and schedule your first DAG, so stay tuned to the blog if you want to learn more.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Top 3 Reasons Why I Sold My M1 Macbook Pro as a Data Scientist
How to Schedule Python Scripts With Cron — The Only Guide You’ll Ever Need
Dask Delayed — How to Parallelize Your Python Code With Ease
How to Create PDF Reports With Python — The Essential Guide
Become a Data Scientist in 2021 Even Without a College Degree
Follow me on Medium for more stories like this
Sign up for my newsletter
Connect on LinkedIn
|
[
{
"code": null,
"e": 320,
"s": 172,
"text": "Apache Airflow is an open-source workflow management platform (source), and is a must-know technology for modern-day data scientists and engineers."
},
{
"code": null,
"e": 476,
"s": 320,
"text": "Today you’ll learn how to install the platform on a virtual machine, configure it, and establish an SSH connection through Terminal and Visual Studio Code."
},
{
"code": null,
"e": 514,
"s": 476,
"text": "The article is structured as follows:"
},
{
"code": null,
"e": 557,
"s": 514,
"text": "Step 1: Download and Install Ubuntu Server"
},
{
"code": null,
"e": 610,
"s": 557,
"text": "Step 2: Establish an SSH Connection Through Terminal"
},
{
"code": null,
"e": 641,
"s": 610,
"text": "Step 3: Install Apache Airflow"
},
{
"code": null,
"e": 704,
"s": 641,
"text": "Step 4: Establish an SSH Connection Through Visual Studio Code"
},
{
"code": null,
"e": 715,
"s": 704,
"text": "Conclusion"
},
{
"code": null,
"e": 859,
"s": 715,
"text": "Let’s start with the easiest step. I assume you already have VirtualBox installed. If that’s not the case, please install it before proceeding."
},
{
"code": null,
"e": 971,
"s": 859,
"text": "We’ll start by downloading the Ubuntu Server ISO file. It’s around 1GB download, so it shouldn’t take too long:"
},
{
"code": null,
"e": 1115,
"s": 971,
"text": "While it’s downloading, you can configure the virtual machine. Go over to VirtualBox and create a new machine according to the following image:"
},
{
"code": null,
"e": 1318,
"s": 1115,
"text": "From there, just click on Next a couple of times and choose an appropriate RAM and storage configuration. I’ve gone with 4GB for the RAM and 25GB for the storage — but feel free to allocate differently."
},
{
"code": null,
"e": 1377,
"s": 1318,
"text": "Once done, you’ll have a new virtual machine on your list:"
},
{
"code": null,
"e": 1553,
"s": 1377,
"text": "Let’s tweak a couple of more things while the ISO is downloading. Open the Settings for the new machine and go to Network. Under Advanced, click on the Port Forwarding button:"
},
{
"code": null,
"e": 1586,
"s": 1553,
"text": "We’ll need to forward two ports:"
},
{
"code": null,
"e": 1755,
"s": 1586,
"text": "Guest 8080 to Host 8250 (or any other, the documentation recommends 8080, but that one is occupied on my machine) for Airflow UIGuest 22 to Host 2222 for SSH connection"
},
{
"code": null,
"e": 1884,
"s": 1755,
"text": "Guest 8080 to Host 8250 (or any other, the documentation recommends 8080, but that one is occupied on my machine) for Airflow UI"
},
{
"code": null,
"e": 1925,
"s": 1884,
"text": "Guest 22 to Host 2222 for SSH connection"
},
{
"code": null,
"e": 1971,
"s": 1925,
"text": "Once done, your window should look like this:"
},
{
"code": null,
"e": 2228,
"s": 1971,
"text": "And that’s all — configuration-wise. The ISO file has hopefully been downloaded by now, so run the virtual machine and load in the ISO file for the installation. Install the OS as you normally would. You’ll need to create a user — I’ve called mine airflow."
},
{
"code": null,
"e": 2271,
"s": 2228,
"text": "Here’s a screenshot from the installation:"
},
{
"code": null,
"e": 2456,
"s": 2271,
"text": "If you see something similar, then you’re on the right track. Once the installation finishes, you can restart the VM and log in with your user. And that’s it — Ubuntu Server installed!"
},
{
"code": null,
"e": 2542,
"s": 2456,
"text": "We can now establish an SSH connection from Terminal (or PuTTY if you’re on Windows)."
},
{
"code": null,
"e": 2622,
"s": 2542,
"text": "For macOS and Linux, you’ll have to enter the following line into the Terminal:"
},
{
"code": null,
"e": 2652,
"s": 2622,
"text": "ssh -p 2222 airflow@localhost"
},
{
"code": null,
"e": 2681,
"s": 2652,
"text": "As shown on the image below:"
},
{
"code": null,
"e": 2771,
"s": 2681,
"text": "Keep in mind that airflow indicates the username you have to your user upon installation."
},
{
"code": null,
"e": 2950,
"s": 2771,
"text": "The installation of Apache Airflow is a multi-step process. The whole thing is Python-based, and Ubuntu Server doesn’t ship with Python 3. The following command will change that:"
},
{
"code": null,
"e": 2979,
"s": 2950,
"text": "sudo apt install python3-pip"
},
{
"code": null,
"e": 3126,
"s": 2979,
"text": "Now you have Python 3.8.x installed (or some newer version), so you’re ready to install Airflow. The following Terminal command will do just that:"
},
{
"code": null,
"e": 3270,
"s": 3126,
"text": "sudo pip3 install “apache-airflow==2.0.2” — constraint “https://raw.githubusercontent.com/apache/airflow/constraints-2.0.2/constraints-3.8.txt\""
},
{
"code": null,
"e": 3291,
"s": 3270,
"text": "Please keep in mind:"
},
{
"code": null,
"e": 3331,
"s": 3291,
"text": "Replace 2.0.2 with the version you want"
},
{
"code": null,
"e": 3461,
"s": 3331,
"text": "Relace constraints-3.8.txt with your Python version. For example, if you’re using Python 3.9.x, it should be: constraints-3.9.txt"
},
{
"code": null,
"e": 3644,
"s": 3461,
"text": "Airflow installed! But that doesn’t mean it’s configured. You’ll also need to initialize the database and create the user. The following command initializes the database for Airflow:"
},
{
"code": null,
"e": 3660,
"s": 3644,
"text": "airflow db init"
},
{
"code": null,
"e": 3700,
"s": 3660,
"text": "And the following one creates the user:"
},
{
"code": null,
"e": 3830,
"s": 3700,
"text": "airflow users create — username admin — firstname <your_first_name> — lastname <your_last_name> — role Admin — email <your_email>"
},
{
"code": null,
"e": 3917,
"s": 3830,
"text": "Once done, you can run both Airflow Webserver as a daemon with the following commands:"
},
{
"code": null,
"e": 3938,
"s": 3917,
"text": "airflow webserver -D"
},
{
"code": null,
"e": 3985,
"s": 3938,
"text": "And that’s it — Apache Airflow is now running!"
},
{
"code": null,
"e": 4122,
"s": 3985,
"text": "To verify, open a web browser and go to localhost:8250 (replace 8250 with a host port for Airflow). You should see the following screen:"
},
{
"code": null,
"e": 4273,
"s": 4122,
"text": "To continue, enter the database user credentials created a minute ago and click on Sign In. You’ll immediately be presented with the following screen:"
},
{
"code": null,
"e": 4470,
"s": 4273,
"text": "And that’s it — you’re in! Don’t worry about a ton of DAGs that are loaded initially. You can quickly delete them from the web application or specify not to load them in the Airflow configuration."
},
{
"code": null,
"e": 4579,
"s": 4470,
"text": "Up next, let’s see how to establish a remote SSH connection to your virtual machine from Visual Studio Code."
},
{
"code": null,
"e": 4767,
"s": 4579,
"text": "If you’re anything like me, a manual file transfer from the host to the client is just too much work. Luckily, a free code editor — Visual Studio Code — can manage the connection for you."
},
{
"code": null,
"e": 4820,
"s": 4767,
"text": "To start, install a free plugin called Remote — SSH:"
},
{
"code": null,
"e": 4930,
"s": 4820,
"text": "From there, press on the little blue button on the bottom left corner, and choose the Connect to Host option:"
},
{
"code": null,
"e": 5017,
"s": 4930,
"text": "Up next, enter the connection command identical to the one you’ve entered in Terminal:"
},
{
"code": null,
"e": 5149,
"s": 5017,
"text": "Visual Studio Code will ask you to add the connection configuration to your list of SSH configurations, so select the first option:"
},
{
"code": null,
"e": 5222,
"s": 5149,
"text": "Once again, click on the little blue button to connect to the localhost:"
},
{
"code": null,
"e": 5387,
"s": 5222,
"text": "Once you do so, a new Visual Studio Code window will pop up, and you’ll have to enter the password. It’s the same password you’ve chosen for the Ubuntu Server user:"
},
{
"code": null,
"e": 5522,
"s": 5387,
"text": "And finally, you can click on the Open Folder button to open any directory on the remote host. Let’s open up the /home/airflow folder:"
},
{
"code": null,
"e": 5795,
"s": 5522,
"text": "And that’s it — you’re ready to create your first Airflow DAG. Make sure to put them inside the dags folder (you’ll have to create it first), as that’s where Airflow will try to find them. You can always alter the configuration file, but that’s out of the scope for today."
},
{
"code": null,
"e": 5837,
"s": 5795,
"text": "Let’s wrap things up in the next section."
},
{
"code": null,
"e": 6028,
"s": 5837,
"text": "And there you have it — Apache Airflow installed inside a virtual machine. You could install Airflow locally or with Docker, but I’ve found this approach more common in my professional life."
},
{
"code": null,
"e": 6147,
"s": 6028,
"text": "Up next, we’ll explore how to create and schedule your first DAG, so stay tuned to the blog if you want to learn more."
},
{
"code": null,
"e": 6330,
"s": 6147,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 6341,
"s": 6330,
"text": "medium.com"
},
{
"code": null,
"e": 6404,
"s": 6341,
"text": "Top 3 Reasons Why I Sold My M1 Macbook Pro as a Data Scientist"
},
{
"code": null,
"e": 6479,
"s": 6404,
"text": "How to Schedule Python Scripts With Cron — The Only Guide You’ll Ever Need"
},
{
"code": null,
"e": 6540,
"s": 6479,
"text": "Dask Delayed — How to Parallelize Your Python Code With Ease"
},
{
"code": null,
"e": 6600,
"s": 6540,
"text": "How to Create PDF Reports With Python — The Essential Guide"
},
{
"code": null,
"e": 6662,
"s": 6600,
"text": "Become a Data Scientist in 2021 Even Without a College Degree"
},
{
"code": null,
"e": 6709,
"s": 6662,
"text": "Follow me on Medium for more stories like this"
},
{
"code": null,
"e": 6735,
"s": 6709,
"text": "Sign up for my newsletter"
}
] |
Java Examples - Reversing an array list
|
How to reverse an array list ?
Following example reverses an array list by using Collections.reverse(ArrayList)method.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
System.out.println("Before Reverse Order: " + arrayList);
Collections.reverse(arrayList);
System.out.println("After Reverse Order: " + arrayList);
}
}
The above code sample will produce the following result.
Before Reverse Order: [A, B, C, D, E]
After Reverse Order: [E, D, C, B, A]
Following example is another example of reverse of array.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("Array before reverse:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
for (int i = 0; i < numbers.length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[numbers.length - 1 - i];
numbers[numbers.length - 1 - i] = temp;
}
System.out.println("\nArray after reverse:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
The above code sample will produce the following result.
Array before reverse:
1 2 3 4 5 6 7 8 9 10
Array after reverse:
10 9 8 7 6 5 4 3 2 1
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2099,
"s": 2068,
"text": "How to reverse an array list ?"
},
{
"code": null,
"e": 2187,
"s": 2099,
"text": "Following example reverses an array list by using Collections.reverse(ArrayList)method."
},
{
"code": null,
"e": 2657,
"s": 2187,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\n\npublic class Main {\n public static void main(String[] args) {\n ArrayList arrayList = new ArrayList();\n arrayList.add(\"A\");\n arrayList.add(\"B\");\n arrayList.add(\"C\");\n arrayList.add(\"D\");\n arrayList.add(\"E\");\n System.out.println(\"Before Reverse Order: \" + arrayList);\n Collections.reverse(arrayList);\n System.out.println(\"After Reverse Order: \" + arrayList);\n }\n}"
},
{
"code": null,
"e": 2714,
"s": 2657,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2790,
"s": 2714,
"text": "Before Reverse Order: [A, B, C, D, E]\nAfter Reverse Order: [E, D, C, B, A]\n"
},
{
"code": null,
"e": 2848,
"s": 2790,
"text": "Following example is another example of reverse of array."
},
{
"code": null,
"e": 3496,
"s": 2848,
"text": "public class HelloWorld {\n public static void main(String[] args) {\n int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n System.out.println(\"Array before reverse:\");\n \n for (int i = 0; i < numbers.length; i++) {\n System.out.print(numbers[i] + \" \");\n } \n for (int i = 0; i < numbers.length / 2; i++) {\n int temp = numbers[i];\n numbers[i] = numbers[numbers.length - 1 - i];\n numbers[numbers.length - 1 - i] = temp;\n } \n System.out.println(\"\\nArray after reverse:\");\n for (int i = 0; i < numbers.length; i++) {\n System.out.print(numbers[i] + \" \");\n } \n }\n}"
},
{
"code": null,
"e": 3553,
"s": 3496,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3641,
"s": 3553,
"text": "Array before reverse:\n1 2 3 4 5 6 7 8 9 10 \nArray after reverse:\n10 9 8 7 6 5 4 3 2 1 \n"
},
{
"code": null,
"e": 3648,
"s": 3641,
"text": " Print"
},
{
"code": null,
"e": 3659,
"s": 3648,
"text": " Add Notes"
}
] |
Why multiple inheritance is not supported in Java
|
In Java, a class cannot extend more than one class. Therefore following is illegal −
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritances.
The reason behind this is to prevent ambiguity.
Consider a case where class B extends class A and Class C and both class A and C have the same method display().
Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java.
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "In Java, a class cannot extend more than one class. Therefore following is illegal −"
},
{
"code": null,
"e": 1185,
"s": 1147,
"text": "public class extends Animal, Mammal{}"
},
{
"code": null,
"e": 1317,
"s": 1185,
"text": "However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritances."
},
{
"code": null,
"e": 1365,
"s": 1317,
"text": "The reason behind this is to prevent ambiguity."
},
{
"code": null,
"e": 1478,
"s": 1365,
"text": "Consider a case where class B extends class A and Class C and both class A and C have the same method display()."
},
{
"code": null,
"e": 1624,
"s": 1478,
"text": "Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java."
}
] |
How to change button label in confirm box using JavaScript?
|
To change button label in confirm box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create a confirm box with different button label that the standard confirm box −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function functionConfirm(msg, myYes, myNo)
{
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.show();
}
</script>
<style>
#confirm
{
display: none;
background-color: #91FF00;
border: 1px solid #aaa;
position: fixed;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #48E5DA;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
padding: 5px;
text-align: center;
width: 100px;
cursor: pointer;
}
#confirm .message
{
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message"></div>
<button class="yes">Like!</button>
<button class="no">No, I Like Cricket!</button>
</div>
<button onclick = 'functionConfirm("Do you like Football?", function yes()
{
alert("Yes")
}, function no()
{
alert("no")
});'>submit</button>
</body>
</html>
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "To change button label in confirm box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create a confirm box with different button label that the standard confirm box −"
},
{
"code": null,
"e": 3021,
"s": 1266,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n </script>\n <script>\n function functionConfirm(msg, myYes, myNo)\n {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes,.no\").unbind().click(function()\n {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.find(\".no\").click(myNo);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm\n {\n display: none;\n background-color: #91FF00;\n border: 1px solid #aaa;\n position: fixed;\n width: 250px;\n left: 50%;\n margin-left: -100px;\n padding: 6px 8px 8px;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #48E5DA;\n display: inline-block;\n border-radius: 5px;\n border: 1px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 100px;\n cursor: pointer;\n }\n #confirm .message\n {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id=\"confirm\">\n <div class=\"message\"></div>\n <button class=\"yes\">Like!</button>\n <button class=\"no\">No, I Like Cricket!</button>\n </div>\n <button onclick = 'functionConfirm(\"Do you like Football?\", function yes()\n {\n alert(\"Yes\")\n }, function no()\n {\n alert(\"no\")\n });'>submit</button>\n </body>\n</html>"
}
] |
How to use jQuery hasAttribute() method to see if there is an attribute on an element?
|
Use jQuery hasAttribute() method to see if there is an attribute for an element.
You can try to run the following code to learn how to use hasAttribute() method:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').on('click', function() {
if (this.hasAttribute("style")) {
alert('True')
} else {
alert('False')
}
})
});
</script>
</head>
<body>
Check for attribute in the button element<br>
<button class='button' style='background-color:blue;'>
Button
</button>
<button class='button'>
Button 2
</button>
</body>
</html>
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Use jQuery hasAttribute() method to see if there is an attribute for an element."
},
{
"code": null,
"e": 1224,
"s": 1143,
"text": "You can try to run the following code to learn how to use hasAttribute() method:"
},
{
"code": null,
"e": 1234,
"s": 1224,
"text": "Live Demo"
},
{
"code": null,
"e": 1908,
"s": 1234,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $('button').on('click', function() {\n\n if (this.hasAttribute(\"style\")) {\n alert('True')\n } else {\n alert('False')\n }\n \n })\n });\n </script>\n </head>\n <body>\n Check for attribute in the button element<br>\n <button class='button' style='background-color:blue;'>\n Button\n </button>\n <button class='button'>\n Button 2\n </button>\n </body>\n</html>"
}
] |
clone() method in Java
|
Java provides an assignment operator to copy the values but no operator to copy the object. Object class has a clone method which can be used to copy the values of an object without any side-effect. Assignment operator has a side-effect that when a reference is assigned to another reference then a new object is not created and both the reference point to the same object. This means if we change the value in one object then same will reflect in another object as well. clone() method handles this problem. See the below example.
Live Demo
public class Tester {
public static void main(String[] args) throws CloneNotSupportedException {
//Scenario 1: Using assignment operator to copy objects
A a1 = new A();
a1.a = 1;
a1.b = 2;
//Print a1 object
System.out.println("a1: [" + a1.a + ", " + a1.b + "]");
//assignment operator copies the reference
A a2 = a1;
//a2 and a1 are now pointing to same object
//modify a2 and changes will reflect in a1
a2.a = 3;
System.out.println("a1: [" + a1.a + ", " + a1.b + "]");
System.out.println("a2: [" + a2.a + ", " + a2.b + "]");
//Scenario 2: Using cloning, we can prevent the above problem
B b1 = new B();
b1.a = 1;
b1.b = 2;
//Print b1 object
System.out.println("b1: [" + b1.a + ", " + b1.b + "]");
//cloning method copies the object
B b2 = b1.clone();
//b2 and b1 are now pointing to different object
//modify b2 and changes will not reflect in b1
b2.a = 3;
System.out.println("b1: [" + b1.a + ", " + b1.b + "]");
System.out.println("b2: [" + b2.a + ", " + b2.b + "]");
}
}
class A {
public int a;
public int b;
}
class B implements Cloneable {
public int a;
public int b;
public B clone() throws CloneNotSupportedException {
B b = (B)super.clone();
return b;
}
}
a1: [1, 2]
a1: [3, 2]
a2: [3, 2]
b1: [1, 2]
b1: [1, 2]
b2: [3, 2]
We can copy an object using the assignment operator as well as use clone() method.
We can copy an object using the assignment operator as well as use clone() method.
Assignment operator has side effects as it only copies the reference, the underlying object remains the same.
Assignment operator has side effects as it only copies the reference, the underlying object remains the same.
clone() method has no side-effects in case of primitives instance variables, as a new object is created during cloning.
clone() method has no side-effects in case of primitives instance variables, as a new object is created during cloning.
clone() method if not implemented properly, too has side-effects in case of objects as instance variables, as a cloned object to has a copy of references. This is termed as a shallow copy.
clone() method if not implemented properly, too has side-effects in case of objects as instance variables, as a cloned object to has a copy of references. This is termed as a shallow copy.
clone() method can be overridden to prevent shallow copy an instance variable objects can be separately created and their properties can be updated. This is termed as a deep copy.
clone() method can be overridden to prevent shallow copy an instance variable objects can be separately created and their properties can be updated. This is termed as a deep copy.
|
[
{
"code": null,
"e": 1594,
"s": 1062,
"text": "Java provides an assignment operator to copy the values but no operator to copy the object. Object class has a clone method which can be used to copy the values of an object without any side-effect. Assignment operator has a side-effect that when a reference is assigned to another reference then a new object is not created and both the reference point to the same object. This means if we change the value in one object then same will reflect in another object as well. clone() method handles this problem. See the below example."
},
{
"code": null,
"e": 1604,
"s": 1594,
"text": "Live Demo"
},
{
"code": null,
"e": 2972,
"s": 1604,
"text": "public class Tester {\n public static void main(String[] args) throws CloneNotSupportedException {\n //Scenario 1: Using assignment operator to copy objects\n A a1 = new A();\n a1.a = 1;\n a1.b = 2;\n //Print a1 object\n System.out.println(\"a1: [\" + a1.a + \", \" + a1.b + \"]\");\n\n //assignment operator copies the reference\n A a2 = a1;\n //a2 and a1 are now pointing to same object\n //modify a2 and changes will reflect in a1\n a2.a = 3;\n System.out.println(\"a1: [\" + a1.a + \", \" + a1.b + \"]\");\n System.out.println(\"a2: [\" + a2.a + \", \" + a2.b + \"]\");\n\n //Scenario 2: Using cloning, we can prevent the above problem\n B b1 = new B();\n b1.a = 1;\n b1.b = 2;\n\n //Print b1 object\n System.out.println(\"b1: [\" + b1.a + \", \" + b1.b + \"]\");\n\n //cloning method copies the object\n B b2 = b1.clone();\n\n //b2 and b1 are now pointing to different object\n //modify b2 and changes will not reflect in b1\n b2.a = 3;\n System.out.println(\"b1: [\" + b1.a + \", \" + b1.b + \"]\");\n System.out.println(\"b2: [\" + b2.a + \", \" + b2.b + \"]\");\n }\n}\n\nclass A {\n public int a;\n public int b;\n}\n\nclass B implements Cloneable { \n public int a;\n public int b;\n\n public B clone() throws CloneNotSupportedException {\n B b = (B)super.clone();\n return b;\n }\n}"
},
{
"code": null,
"e": 3038,
"s": 2972,
"text": "a1: [1, 2]\na1: [3, 2]\na2: [3, 2]\nb1: [1, 2]\nb1: [1, 2]\nb2: [3, 2]"
},
{
"code": null,
"e": 3121,
"s": 3038,
"text": "We can copy an object using the assignment operator as well as use clone() method."
},
{
"code": null,
"e": 3204,
"s": 3121,
"text": "We can copy an object using the assignment operator as well as use clone() method."
},
{
"code": null,
"e": 3314,
"s": 3204,
"text": "Assignment operator has side effects as it only copies the reference, the underlying object remains the same."
},
{
"code": null,
"e": 3424,
"s": 3314,
"text": "Assignment operator has side effects as it only copies the reference, the underlying object remains the same."
},
{
"code": null,
"e": 3544,
"s": 3424,
"text": "clone() method has no side-effects in case of primitives instance variables, as a new object is created during cloning."
},
{
"code": null,
"e": 3664,
"s": 3544,
"text": "clone() method has no side-effects in case of primitives instance variables, as a new object is created during cloning."
},
{
"code": null,
"e": 3853,
"s": 3664,
"text": "clone() method if not implemented properly, too has side-effects in case of objects as instance variables, as a cloned object to has a copy of references. This is termed as a shallow copy."
},
{
"code": null,
"e": 4042,
"s": 3853,
"text": "clone() method if not implemented properly, too has side-effects in case of objects as instance variables, as a cloned object to has a copy of references. This is termed as a shallow copy."
},
{
"code": null,
"e": 4222,
"s": 4042,
"text": "clone() method can be overridden to prevent shallow copy an instance variable objects can be separately created and their properties can be updated. This is termed as a deep copy."
},
{
"code": null,
"e": 4402,
"s": 4222,
"text": "clone() method can be overridden to prevent shallow copy an instance variable objects can be separately created and their properties can be updated. This is termed as a deep copy."
}
] |
Clojure - Strings subs
|
Returns the substring of ‘s’ beginning at start inclusive, and ending at end (defaults to length of string), exclusive.
Following is the syntax.
(subs s start end)
Parameters − ‘S’ is the input string. ‘Start’ is the index position where to start the substring from. ‘End’ is the index position where to end the substring.
Return Value − The substring.
Following is an example of the string formatting in Clojure.
(ns clojure.examples.hello
(:gen-class))
(defn hello-world []
(println (subs "HelloWorld" 2 5))
(println (subs "HelloWorld" 5 7)))
(hello-world)
The above program produces the following output.
llo
Wo
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2494,
"s": 2374,
"text": "Returns the substring of ‘s’ beginning at start inclusive, and ending at end (defaults to length of string), exclusive."
},
{
"code": null,
"e": 2519,
"s": 2494,
"text": "Following is the syntax."
},
{
"code": null,
"e": 2539,
"s": 2519,
"text": "(subs s start end)\n"
},
{
"code": null,
"e": 2698,
"s": 2539,
"text": "Parameters − ‘S’ is the input string. ‘Start’ is the index position where to start the substring from. ‘End’ is the index position where to end the substring."
},
{
"code": null,
"e": 2728,
"s": 2698,
"text": "Return Value − The substring."
},
{
"code": null,
"e": 2789,
"s": 2728,
"text": "Following is an example of the string formatting in Clojure."
},
{
"code": null,
"e": 2943,
"s": 2789,
"text": "(ns clojure.examples.hello\n (:gen-class))\n(defn hello-world []\n (println (subs \"HelloWorld\" 2 5))\n (println (subs \"HelloWorld\" 5 7)))\n(hello-world)"
},
{
"code": null,
"e": 2992,
"s": 2943,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 3000,
"s": 2992,
"text": "llo\nWo\n"
},
{
"code": null,
"e": 3007,
"s": 3000,
"text": " Print"
},
{
"code": null,
"e": 3018,
"s": 3007,
"text": " Add Notes"
}
] |
How to create array of strings in Java?
|
In Java, you can create an array just like an object using the new keyword. The syntax of creating an array in Java using new keyword −
type[] reference = new type[10];
Where,
type is the data type of the elements of the array.
type is the data type of the elements of the array.
reference is the reference that holds the array.
reference is the reference that holds the array.
And, if you want to populate the array by assigning values to all the elements one by one using the index −
reference [0] = value1;
reference [1] = value2;
You can declare an array of Strings using the new keyword as &mius;
String[] str = new String[5];
And then, you can populate the string using the indices as −
str[0] = "JavaFX";
str[1] = "OpenCV";
str[2] = "ApacheFlume";
str[3] = "Apache Hadoop";
str[4] = "WebGL";
You can also create a String array directly using the curly braces as −
String str = str[0] = {"JavaFX", "OpenCV", "ApacheFlume", "Apache Hadoop", "WebGL"}
|
[
{
"code": null,
"e": 1198,
"s": 1062,
"text": "In Java, you can create an array just like an object using the new keyword. The syntax of creating an array in Java using new keyword −"
},
{
"code": null,
"e": 1231,
"s": 1198,
"text": "type[] reference = new type[10];"
},
{
"code": null,
"e": 1238,
"s": 1231,
"text": "Where,"
},
{
"code": null,
"e": 1290,
"s": 1238,
"text": "type is the data type of the elements of the array."
},
{
"code": null,
"e": 1342,
"s": 1290,
"text": "type is the data type of the elements of the array."
},
{
"code": null,
"e": 1391,
"s": 1342,
"text": "reference is the reference that holds the array."
},
{
"code": null,
"e": 1440,
"s": 1391,
"text": "reference is the reference that holds the array."
},
{
"code": null,
"e": 1548,
"s": 1440,
"text": "And, if you want to populate the array by assigning values to all the elements one by one using the index −"
},
{
"code": null,
"e": 1596,
"s": 1548,
"text": "reference [0] = value1;\nreference [1] = value2;"
},
{
"code": null,
"e": 1664,
"s": 1596,
"text": "You can declare an array of Strings using the new keyword as &mius;"
},
{
"code": null,
"e": 1695,
"s": 1664,
"text": "String[] str = new String[5];\n"
},
{
"code": null,
"e": 1756,
"s": 1695,
"text": "And then, you can populate the string using the indices as −"
},
{
"code": null,
"e": 1862,
"s": 1756,
"text": "str[0] = \"JavaFX\";\nstr[1] = \"OpenCV\";\nstr[2] = \"ApacheFlume\";\nstr[3] = \"Apache Hadoop\";\nstr[4] = \"WebGL\";"
},
{
"code": null,
"e": 1934,
"s": 1862,
"text": "You can also create a String array directly using the curly braces as −"
},
{
"code": null,
"e": 2019,
"s": 1934,
"text": "String str = str[0] = {\"JavaFX\", \"OpenCV\", \"ApacheFlume\", \"Apache Hadoop\", \"WebGL\"}\n"
}
] |
Generate Grey Code Sequences | Practice | GeeksforGeeks
|
Given a number N, your task is to complete the function which generates all n-bit grey code sequences, a grey code sequence is a sequence such that successive patterns in it differ by one bit.
Example 1:
Input:
N = 2
Output: 00 01 11 10
Explanation: All 2-bit gray codes are
00, 01, 11, 10 such that successive
patterns in it differ by one bit.
Example 2:
Input:
N = 1
Output: 0 1
Your Task:
Complete the function generateCode() which takes an integer as input parameter and retruns an array of all N bit grey code sequence such that successive patterns in it differ by one bit.
Expected Time Complexity: O(N * 2N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 16
0
vishnu12654 days ago
ArrayList<String> res = new ArrayList<String>();
void greyCode(String s , int value , int level , int n){
if(level == n){
res.add(s);
return;
}
if(value == 0){
greyCode(s+"0",0,level+1,n);
greyCode(s+"1",1,level+1,n);
}
else if(value == 1){
greyCode(s+"1",0,level+1,n);
greyCode(s+"0",1,level+1,n);
}
}
ArrayList <String> generateCode(int n)
{
if(res.isEmpty()==false){
res.clear();
}
greyCode("",0,0,n);
return res;
}
0
awektoppo2 weeks ago
void getCode(int N,int pos,vector<string>& ans){ if(N==pos){ return; } vector<string> L1(ans.size()),L2(ans.size()); for(int i=0;i<ans.size();i++){ L1[i] ='0' + ans[i]; L2[i] = '1'+ans[ans.size()-i-1]; } for(int i=0;i<L1.size();i++){ ans[i]=L1[i]; } for(int i=0;i<L2.size();i++){ ans.push_back(L2[i]); } getCode(N,pos+1,ans); } vector <string> generateCode(int N) { //Your code here string s=""; vector<string> ans={"0","1"}; getCode(N,1,ans); return ans; }
0
geminicode3 months ago
is it compulsory to print the answer in the same sequence as given in the description? isn't 00 01 and 00 10 both correct ?? can anyone explain ?
0
pramodpawarkp3 months ago
//time 0.3/1.4
string str_make(int i) //fuction for dec to bin { string s=""; while(i) { s+=i%2+'0'; i/=2; } return s; } vector <string> generateCode(int N) { vector<string>ans; int count=pow(2,N); int i=0; while(i<count) { int gray=i^(i>>1); //gray conversion string temp=str_make(gray); //function for dec to bin if(temp.length()<N) { int k=N-temp.length(); while(k--) { temp.push_back('0'); } } reverse(temp.begin(),temp.end()); ans.push_back(temp); i++; } return ans; }
0
amukherjee98am3 months ago
//CPP solution
//Time taken 0.3
class Solution{
public:
vector <string> generateCode(int N)
{
//Your code here
vector<string> v;
if(N<1)
return v;
v.push_back("0");
v.push_back("1");
if(N==1)
return v;
for(int i=2;i<=N;i++)
{
for(int j=0;j<pow(2,i-1);j++)
{
v.push_back(v[pow(2,i-1)-1-j]);
}
for(int j=0;j<pow(2,i);j++)
{
if(j<pow(2,i-1))
{
v[j]='0'+v[j];
}
else
{
v[j]='1'+v[j];
}
}
}
return v;
}
};
-1
chessnoobdj4 months ago
Iterative c++
vector <string> generateCode(int N)
{
vector <string> res;
int num = pow(2, N);
for(int i=0; i<num; i++){
string str = "";
int gray = i^(i>>1);
str = bitset<16>(gray).to_string();
str = str.substr(16-N, N);
res.push_back(str);
}
return res;
}
0
kronizerdeltac4 months ago
JAVA RECURSIVE SOLUTION
class Solution{ ArrayList <String> generateCode(int n) { if(n == 1) { ArrayList <String> base = new ArrayList<>(); base.add("0"); base.add("1"); return base; } ArrayList <String> ans = generateCode(n - 1); ArrayList <String> myAns = new ArrayList<>(); for(int i = 0; i < ans.size(); i++) { myAns.add("0" + ans.get(i)); } for(int i = ans.size() - 1; i >= 0; i--) { myAns.add("1" + ans.get(i)); } return myAns; }}
0
uav21122projects6 months ago
//C approach
int grayCode(int n)
{
return (n ^ n>>1);
}
void decToBinary(int n, int r){
for(int i=r-1; i>=0; i--)
(n & (1<<i)) ? printf("1") : printf("0");
//printf("\n");
}
int generateCode(int n)
{
int a = 0;
for (int i = 0; i < 2*n; i++)
{
a = grayCode(i);
decToBinary(a, n);
printf(" ");
}
}
0
rohitshah4083
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 431,
"s": 238,
"text": "Given a number N, your task is to complete the function which generates all n-bit grey code sequences, a grey code sequence is a sequence such that successive patterns in it differ by one bit."
},
{
"code": null,
"e": 442,
"s": 431,
"text": "Example 1:"
},
{
"code": null,
"e": 584,
"s": 442,
"text": "Input:\nN = 2\nOutput: 00 01 11 10\nExplanation: All 2-bit gray codes are\n00, 01, 11, 10 such that successive\npatterns in it differ by one bit.\n"
},
{
"code": null,
"e": 595,
"s": 584,
"text": "Example 2:"
},
{
"code": null,
"e": 620,
"s": 595,
"text": "Input:\nN = 1\nOutput: 0 1"
},
{
"code": null,
"e": 820,
"s": 622,
"text": "Your Task:\nComplete the function generateCode() which takes an integer as input parameter and retruns an array of all N bit grey code sequence such that successive patterns in it differ by one bit."
},
{
"code": null,
"e": 887,
"s": 820,
"text": "Expected Time Complexity: O(N * 2N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 911,
"s": 887,
"text": "Constraints:\n1 ≤ N ≤ 16"
},
{
"code": null,
"e": 913,
"s": 911,
"text": "0"
},
{
"code": null,
"e": 934,
"s": 913,
"text": "vishnu12654 days ago"
},
{
"code": null,
"e": 1538,
"s": 934,
"text": "ArrayList<String> res = new ArrayList<String>();\n \n void greyCode(String s , int value , int level , int n){\n if(level == n){\n res.add(s);\n return;\n }\n if(value == 0){\n greyCode(s+\"0\",0,level+1,n);\n greyCode(s+\"1\",1,level+1,n);\n }\n else if(value == 1){\n greyCode(s+\"1\",0,level+1,n);\n greyCode(s+\"0\",1,level+1,n);\n }\n }\n \n ArrayList <String> generateCode(int n)\n {\n\t if(res.isEmpty()==false){\n\t res.clear();\n\t }\n\t greyCode(\"\",0,0,n);\n\t return res;\n\t \n }"
},
{
"code": null,
"e": 1540,
"s": 1538,
"text": "0"
},
{
"code": null,
"e": 1561,
"s": 1540,
"text": "awektoppo2 weeks ago"
},
{
"code": null,
"e": 2132,
"s": 1561,
"text": " void getCode(int N,int pos,vector<string>& ans){ if(N==pos){ return; } vector<string> L1(ans.size()),L2(ans.size()); for(int i=0;i<ans.size();i++){ L1[i] ='0' + ans[i]; L2[i] = '1'+ans[ans.size()-i-1]; } for(int i=0;i<L1.size();i++){ ans[i]=L1[i]; } for(int i=0;i<L2.size();i++){ ans.push_back(L2[i]); } getCode(N,pos+1,ans); } vector <string> generateCode(int N) { //Your code here string s=\"\"; vector<string> ans={\"0\",\"1\"}; getCode(N,1,ans); return ans; }"
},
{
"code": null,
"e": 2134,
"s": 2132,
"text": "0"
},
{
"code": null,
"e": 2157,
"s": 2134,
"text": "geminicode3 months ago"
},
{
"code": null,
"e": 2303,
"s": 2157,
"text": "is it compulsory to print the answer in the same sequence as given in the description? isn't 00 01 and 00 10 both correct ?? can anyone explain ?"
},
{
"code": null,
"e": 2307,
"s": 2305,
"text": "0"
},
{
"code": null,
"e": 2333,
"s": 2307,
"text": "pramodpawarkp3 months ago"
},
{
"code": null,
"e": 2348,
"s": 2333,
"text": "//time 0.3/1.4"
},
{
"code": null,
"e": 3077,
"s": 2348,
"text": " string str_make(int i) //fuction for dec to bin { string s=\"\"; while(i) { s+=i%2+'0'; i/=2; } return s; } vector <string> generateCode(int N) { vector<string>ans; int count=pow(2,N); int i=0; while(i<count) { int gray=i^(i>>1); //gray conversion string temp=str_make(gray); //function for dec to bin if(temp.length()<N) { int k=N-temp.length(); while(k--) { temp.push_back('0'); } } reverse(temp.begin(),temp.end()); ans.push_back(temp); i++; } return ans; }"
},
{
"code": null,
"e": 3079,
"s": 3077,
"text": "0"
},
{
"code": null,
"e": 3106,
"s": 3079,
"text": "amukherjee98am3 months ago"
},
{
"code": null,
"e": 3978,
"s": 3106,
"text": "//CPP solution\n//Time taken 0.3\nclass Solution{\n public:\n \n vector <string> generateCode(int N)\n {\n //Your code here\n vector<string> v;\n if(N<1)\n return v;\n v.push_back(\"0\");\n v.push_back(\"1\");\n if(N==1)\n return v;\n for(int i=2;i<=N;i++)\n {\n for(int j=0;j<pow(2,i-1);j++)\n {\n v.push_back(v[pow(2,i-1)-1-j]);\n }\n for(int j=0;j<pow(2,i);j++)\n {\n if(j<pow(2,i-1))\n {\n v[j]='0'+v[j];\n }\n else\n {\n v[j]='1'+v[j];\n }\n }\n }\n return v;\n }\n};"
},
{
"code": null,
"e": 3981,
"s": 3978,
"text": "-1"
},
{
"code": null,
"e": 4005,
"s": 3981,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 4019,
"s": 4005,
"text": "Iterative c++"
},
{
"code": null,
"e": 4370,
"s": 4019,
"text": "vector <string> generateCode(int N)\n {\n vector <string> res;\n int num = pow(2, N);\n for(int i=0; i<num; i++){\n string str = \"\";\n int gray = i^(i>>1);\n str = bitset<16>(gray).to_string();\n str = str.substr(16-N, N);\n res.push_back(str);\n }\n return res;\n }"
},
{
"code": null,
"e": 4372,
"s": 4370,
"text": "0"
},
{
"code": null,
"e": 4399,
"s": 4372,
"text": "kronizerdeltac4 months ago"
},
{
"code": null,
"e": 4423,
"s": 4399,
"text": "JAVA RECURSIVE SOLUTION"
},
{
"code": null,
"e": 4976,
"s": 4423,
"text": "class Solution{ ArrayList <String> generateCode(int n) { if(n == 1) { ArrayList <String> base = new ArrayList<>(); base.add(\"0\"); base.add(\"1\"); return base; } ArrayList <String> ans = generateCode(n - 1); ArrayList <String> myAns = new ArrayList<>(); for(int i = 0; i < ans.size(); i++) { myAns.add(\"0\" + ans.get(i)); } for(int i = ans.size() - 1; i >= 0; i--) { myAns.add(\"1\" + ans.get(i)); } return myAns; }}"
},
{
"code": null,
"e": 4978,
"s": 4976,
"text": "0"
},
{
"code": null,
"e": 5007,
"s": 4978,
"text": "uav21122projects6 months ago"
},
{
"code": null,
"e": 5374,
"s": 5007,
"text": "//C approach \n\nint grayCode(int n)\n{\n return (n ^ n>>1);\n}\n\nvoid decToBinary(int n, int r){\n\n for(int i=r-1; i>=0; i--)\n (n & (1<<i)) ? printf(\"1\") : printf(\"0\");\n\n //printf(\"\\n\");\n}\n\nint generateCode(int n)\n{\n int a = 0;\n for (int i = 0; i < 2*n; i++)\n {\n a = grayCode(i);\n decToBinary(a, n);\n printf(\" \");\n }\n \n}"
},
{
"code": null,
"e": 5376,
"s": 5374,
"text": "0"
},
{
"code": null,
"e": 5390,
"s": 5376,
"text": "rohitshah4083"
},
{
"code": null,
"e": 5416,
"s": 5390,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5562,
"s": 5416,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5598,
"s": 5562,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5608,
"s": 5598,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5618,
"s": 5608,
"text": "\nContest\n"
},
{
"code": null,
"e": 5681,
"s": 5618,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5829,
"s": 5681,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6037,
"s": 5829,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6143,
"s": 6037,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How do I make a dotted/dashed line in Android?
|
This example demonstrates how do I make a dotted/dashed line in Android.
Step 1 - Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 - Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:background="#33FFFF00"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:textSize="18sp"
android:textAlignment="center"
android:text="click to show toast at top"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="5dp"
android:src="@drawable/dotted"
android:layerType="software" />
</LinearLayout>
In the above code, we have text view with image view. Image view contains a dotted background. So create dotted.xml in drawable as shown below -
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/white" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
<padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/>
</shape>
Step 3 - Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView text;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
text = findViewById(R.id.text);
text.setText("Dotted line for text view ");
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -
The above result contains a dotted line.
Click here to download the project code
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "This example demonstrates how do I make a dotted/dashed line in Android."
},
{
"code": null,
"e": 1264,
"s": 1135,
"text": "Step 1 - Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1329,
"s": 1264,
"text": "Step 2 - Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2192,
"s": 1329,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/parent\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:gravity=\"center\"\n android:background=\"#33FFFF00\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"18sp\"\n android:textAlignment=\"center\"\n android:text=\"click to show toast at top\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n <ImageView\n android:layout_width=\"match_parent\"\n android:layout_marginTop=\"10dp\"\n android:layout_height=\"5dp\"\n android:src=\"@drawable/dotted\"\n android:layerType=\"software\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2337,
"s": 2192,
"text": "In the above code, we have text view with image view. Image view contains a dotted background. So create dotted.xml in drawable as shown below -"
},
{
"code": null,
"e": 2683,
"s": 2337,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\" >\n <solid android:color=\"@android:color/white\" />\n <stroke android:width=\"1dip\" android:color=\"#4fa5d5\"/>\n <padding android:bottom=\"10dp\" android:left=\"10dp\" android:right=\"10dp\" android:top=\"10dp\"/>\n</shape>"
},
{
"code": null,
"e": 2740,
"s": 2683,
"text": "Step 3 - Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3357,
"s": 2740,
"text": "package com.example.andy.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView text;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n text = findViewById(R.id.text);\n text.setText(\"Dotted line for text view \");\n }\n}"
},
{
"code": null,
"e": 3704,
"s": 3357,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -"
},
{
"code": null,
"e": 3745,
"s": 3704,
"text": "The above result contains a dotted line."
},
{
"code": null,
"e": 3785,
"s": 3745,
"text": "Click here to download the project code"
}
] |
Minimizing array sum by applying XOR operation on all elements of the array - GeeksforGeeks
|
27 Apr, 2021
Given an array arr[] of N integer elements, the task is to choose an element X and apply XOR operation on every element of the array with X such that the array sum is minimized.
Input: arr[] = {3, 5, 7, 11, 15} Output: 26 Binary representation of the array elements are {0011, 0101, 0111, 1011, 1111} We take xor of every element with 7 in order to minimize the sum. 3 XOR 7 = 0100 (4) 5 XOR 7 = 0010 (2) 7 XOR 7 = 0000 (0) 11 XOR 7 = 1100 (12) 15 XOR 7 = 1000 (8) Sum = 4 + 2 + 0 + 12 + 8 = 26Input: arr[] = {1, 2, 3, 4, 5} Output: 14
Approach: The task is to find the element X with which we have to take xor of each element.
Convert each number into binary form and update the frequency of bit (0 or 1) in an array corresponding to the position of each bit in the element in the array.
Now, Traverse the array and check whether the element at index is more than n/2 (for ‘n’ elements, we check whether the set bit appears more than n/2 at index), and subsequently, we obtain element ‘X’
Now, take xor of ‘X’ with all the elements and return the sum.
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;const int MAX = 25; // Function to return the minimized sumint getMinSum(int arr[], int n){ int bits_count[MAX], max_bit = 0, sum = 0, ans = 0; memset(bits_count, 0, sizeof(bits_count)); // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum;} // Driver codeint main(){ int arr[] = { 3, 5, 7, 11, 15 }; int n = sizeof(arr) / sizeof(arr[0]); cout << getMinSum(arr, n); return 0;}
// Java implementation of the approachclass GFG { static int MAX = 25; // Function to return the minimized sum static int getMinSum(int arr[], int n) { int bits_count[] = new int[MAX], max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = (int)Math.pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code public static void main(String[] args) { int arr[] = { 3, 5, 7, 11, 15 }; int n = arr.length; System.out.println(getMinSum(arr, n)); }} // This code has been contributed by 29AjayKumar
# Python3 implementation of the approach MAX = 25; # Function to return the minimized sumdef getMinSum(arr, n) : bits_count = [0]* MAX max_bit = 0; sum = 0; ans = 0; # To store the frequency # of bit in every element for d in range(n) : e = arr[d]; f = 0; while (e > 0) : rem = e % 2; e = e // 2; if (rem == 1) : bits_count[f] += rem; f += 1 max_bit = max(max_bit, f); # Finding element X for d in range(max_bit) : temp = pow(2, d); if (bits_count[d] > n // 2) : ans = ans + temp; # Taking XOR of elements and finding sum for d in range(n) : arr[d] = arr[d] ^ ans; sum = sum + arr[d]; return sum # Driver codeif __name__ == "__main__" : arr = [ 3, 5, 7, 11, 15 ]; n = len(arr); print(getMinSum(arr, n)) # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG { static int MAX = 25; // Function to return the minimized sum static int getMinSum(int[] arr, int n) { int[] bits_count = new int[MAX]; int max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.Max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = (int)Math.Pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code public static void Main(String[] args) { int[] arr = { 3, 5, 7, 11, 15 }; int n = arr.Length; Console.WriteLine(getMinSum(arr, n)); }} /* This code contributed by PrinciRaj1992 */
<script>// Javascript implementation of the approach const MAX = 25; // Function to return the minimized sumfunction getMinSum(arr, n){ let bits_count = new Array(MAX).fill(0), max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (let d = 0; d < n; d++) { let e = arr[d], f = 0; while (e > 0) { let rem = e % 2; e = parseInt(e / 2); if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.max(max_bit, f); } // Finding element X for (let d = 0; d < max_bit; d++) { let temp = Math.pow(2, d); if (bits_count[d] > parseInt(n / 2)) ans = ans + temp; } // Taking XOR of elements and finding sum for (let d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum;} // Driver code let arr = [ 3, 5, 7, 11, 15 ]; let n = arr.length; document.write(getMinSum(arr, n)); </script>
26
ankthon
29AjayKumar
princiraj1992
subhammahato348
binary-representation
Bitwise-XOR
Algorithms
Arrays
Greedy
Arrays
Greedy
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
Difference between Informed and Uninformed Search in AI
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 24612,
"s": 24584,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 24791,
"s": 24612,
"text": "Given an array arr[] of N integer elements, the task is to choose an element X and apply XOR operation on every element of the array with X such that the array sum is minimized. "
},
{
"code": null,
"e": 25151,
"s": 24791,
"text": "Input: arr[] = {3, 5, 7, 11, 15} Output: 26 Binary representation of the array elements are {0011, 0101, 0111, 1011, 1111} We take xor of every element with 7 in order to minimize the sum. 3 XOR 7 = 0100 (4) 5 XOR 7 = 0010 (2) 7 XOR 7 = 0000 (0) 11 XOR 7 = 1100 (12) 15 XOR 7 = 1000 (8) Sum = 4 + 2 + 0 + 12 + 8 = 26Input: arr[] = {1, 2, 3, 4, 5} Output: 14 "
},
{
"code": null,
"e": 25247,
"s": 25153,
"text": "Approach: The task is to find the element X with which we have to take xor of each element. "
},
{
"code": null,
"e": 25408,
"s": 25247,
"text": "Convert each number into binary form and update the frequency of bit (0 or 1) in an array corresponding to the position of each bit in the element in the array."
},
{
"code": null,
"e": 25609,
"s": 25408,
"text": "Now, Traverse the array and check whether the element at index is more than n/2 (for ‘n’ elements, we check whether the set bit appears more than n/2 at index), and subsequently, we obtain element ‘X’"
},
{
"code": null,
"e": 25672,
"s": 25609,
"text": "Now, take xor of ‘X’ with all the elements and return the sum."
},
{
"code": null,
"e": 25725,
"s": 25672,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25729,
"s": 25725,
"text": "C++"
},
{
"code": null,
"e": 25734,
"s": 25729,
"text": "Java"
},
{
"code": null,
"e": 25742,
"s": 25734,
"text": "Python3"
},
{
"code": null,
"e": 25745,
"s": 25742,
"text": "C#"
},
{
"code": null,
"e": 25756,
"s": 25745,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int MAX = 25; // Function to return the minimized sumint getMinSum(int arr[], int n){ int bits_count[MAX], max_bit = 0, sum = 0, ans = 0; memset(bits_count, 0, sizeof(bits_count)); // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum;} // Driver codeint main(){ int arr[] = { 3, 5, 7, 11, 15 }; int n = sizeof(arr) / sizeof(arr[0]); cout << getMinSum(arr, n); return 0;}",
"e": 26835,
"s": 25756,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { static int MAX = 25; // Function to return the minimized sum static int getMinSum(int arr[], int n) { int bits_count[] = new int[MAX], max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = (int)Math.pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code public static void main(String[] args) { int arr[] = { 3, 5, 7, 11, 15 }; int n = arr.length; System.out.println(getMinSum(arr, n)); }} // This code has been contributed by 29AjayKumar",
"e": 28095,
"s": 26835,
"text": null
},
{
"code": "# Python3 implementation of the approach MAX = 25; # Function to return the minimized sumdef getMinSum(arr, n) : bits_count = [0]* MAX max_bit = 0; sum = 0; ans = 0; # To store the frequency # of bit in every element for d in range(n) : e = arr[d]; f = 0; while (e > 0) : rem = e % 2; e = e // 2; if (rem == 1) : bits_count[f] += rem; f += 1 max_bit = max(max_bit, f); # Finding element X for d in range(max_bit) : temp = pow(2, d); if (bits_count[d] > n // 2) : ans = ans + temp; # Taking XOR of elements and finding sum for d in range(n) : arr[d] = arr[d] ^ ans; sum = sum + arr[d]; return sum # Driver codeif __name__ == \"__main__\" : arr = [ 3, 5, 7, 11, 15 ]; n = len(arr); print(getMinSum(arr, n)) # This code is contributed by Ryuga",
"e": 29052,
"s": 28095,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { static int MAX = 25; // Function to return the minimized sum static int getMinSum(int[] arr, int n) { int[] bits_count = new int[MAX]; int max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.Max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = (int)Math.Pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code public static void Main(String[] args) { int[] arr = { 3, 5, 7, 11, 15 }; int n = arr.Length; Console.WriteLine(getMinSum(arr, n)); }} /* This code contributed by PrinciRaj1992 */",
"e": 30319,
"s": 29052,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach const MAX = 25; // Function to return the minimized sumfunction getMinSum(arr, n){ let bits_count = new Array(MAX).fill(0), max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (let d = 0; d < n; d++) { let e = arr[d], f = 0; while (e > 0) { let rem = e % 2; e = parseInt(e / 2); if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.max(max_bit, f); } // Finding element X for (let d = 0; d < max_bit; d++) { let temp = Math.pow(2, d); if (bits_count[d] > parseInt(n / 2)) ans = ans + temp; } // Taking XOR of elements and finding sum for (let d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum;} // Driver code let arr = [ 3, 5, 7, 11, 15 ]; let n = arr.length; document.write(getMinSum(arr, n)); </script>",
"e": 31339,
"s": 30319,
"text": null
},
{
"code": null,
"e": 31342,
"s": 31339,
"text": "26"
},
{
"code": null,
"e": 31352,
"s": 31344,
"text": "ankthon"
},
{
"code": null,
"e": 31364,
"s": 31352,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31378,
"s": 31364,
"text": "princiraj1992"
},
{
"code": null,
"e": 31394,
"s": 31378,
"text": "subhammahato348"
},
{
"code": null,
"e": 31416,
"s": 31394,
"text": "binary-representation"
},
{
"code": null,
"e": 31428,
"s": 31416,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 31439,
"s": 31428,
"text": "Algorithms"
},
{
"code": null,
"e": 31446,
"s": 31439,
"text": "Arrays"
},
{
"code": null,
"e": 31453,
"s": 31446,
"text": "Greedy"
},
{
"code": null,
"e": 31460,
"s": 31453,
"text": "Arrays"
},
{
"code": null,
"e": 31467,
"s": 31460,
"text": "Greedy"
},
{
"code": null,
"e": 31478,
"s": 31467,
"text": "Algorithms"
},
{
"code": null,
"e": 31576,
"s": 31478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31585,
"s": 31576,
"text": "Comments"
},
{
"code": null,
"e": 31598,
"s": 31585,
"text": "Old Comments"
},
{
"code": null,
"e": 31623,
"s": 31598,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31657,
"s": 31623,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 31700,
"s": 31657,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 31729,
"s": 31700,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 31785,
"s": 31729,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 31800,
"s": 31785,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31816,
"s": 31800,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 31843,
"s": 31816,
"text": "Program for array rotation"
},
{
"code": null,
"e": 31891,
"s": 31843,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
C Program for Selection Sort
|
09 Jun, 2022
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
The subarray which is already sorted.
Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass:
For the first position in the sorted array, the whole array is traversed from index 0 to 4 sequentially. The first position where 64 is stored presently, after traversing whole array it is clear that 11 is the lowest value.
Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the array, tends to appear in the first position of the sorted list.
Second Pass:
For the second position, where 25 is present, again traverse the rest of the array in a sequential manner.
After traversing, we found that 12 is the second lowest value in the array and it should appear at the second place in the array, thus swap these values.
Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array and find the third least value present in the array.
While traversing, 22 came out to be the third least value and it should appear at the third place in the array, thus swap 22 with element present at third position.
Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth least element in the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
Fifth Pass:
At last the largest value present in the array automatically get placed at the last position in the array
The resulted array is the sorted array.
Initialize minimum value(min_idx) to location 0
Traverse the array to find the minimum element in the array
While traversing if any element smaller than min_idx is found then swap both the values.
Then, increment min_idx to point to next element
Repeat until array is sorted
Below is the implementation of the above approach:
C
// C program for implementation of selection sort#include <stdio.h> void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionsint main(){ int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0;}
Sorted array:
11 12 22 25 64
Time Complexity: The time complexity of Selection Sort is O(N2) as there are two nested loops:
One loop to select an element of Array one by one = O(N)
Another loop to compare that element with every other Array element = O(N)
Therefore overall complexity = O(N)*O(N) = O(N*N) = O(N2)
Auxiliary Space: O(1) as the only extra memory used is for temporary variable while swapping two values in Array. The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation.
Stability : The default implementation is not stable. However it can be made stable. Please see stable selection sort for details.
Yes, it does not require extra space.
Please refer complete article on Selection Sort for more details!
subhammahato348
reshmapatil2772
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
Exit codes in C/C++ with Examples
C Hello World Program
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
C Program for Tower of Hanoi
Conditional wait and signal in multi-threading
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 276,
"s": 52,
"text": "The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array."
},
{
"code": null,
"e": 315,
"s": 276,
"text": "The subarray which is already sorted. "
},
{
"code": null,
"e": 353,
"s": 315,
"text": "Remaining subarray which is unsorted."
},
{
"code": null,
"e": 513,
"s": 353,
"text": "In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. "
},
{
"code": null,
"e": 591,
"s": 513,
"text": "Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}"
},
{
"code": null,
"e": 603,
"s": 591,
"text": "First pass:"
},
{
"code": null,
"e": 827,
"s": 603,
"text": "For the first position in the sorted array, the whole array is traversed from index 0 to 4 sequentially. The first position where 64 is stored presently, after traversing whole array it is clear that 11 is the lowest value."
},
{
"code": null,
"e": 985,
"s": 827,
"text": "Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the array, tends to appear in the first position of the sorted list."
},
{
"code": null,
"e": 998,
"s": 985,
"text": "Second Pass:"
},
{
"code": null,
"e": 1105,
"s": 998,
"text": "For the second position, where 25 is present, again traverse the rest of the array in a sequential manner."
},
{
"code": null,
"e": 1259,
"s": 1105,
"text": "After traversing, we found that 12 is the second lowest value in the array and it should appear at the second place in the array, thus swap these values."
},
{
"code": null,
"e": 1271,
"s": 1259,
"text": "Third Pass:"
},
{
"code": null,
"e": 1403,
"s": 1271,
"text": "Now, for third place, where 25 is present again traverse the rest of the array and find the third least value present in the array."
},
{
"code": null,
"e": 1568,
"s": 1403,
"text": "While traversing, 22 came out to be the third least value and it should appear at the third place in the array, thus swap 22 with element present at third position."
},
{
"code": null,
"e": 1581,
"s": 1568,
"text": "Fourth pass:"
},
{
"code": null,
"e": 1691,
"s": 1581,
"text": "Similarly, for fourth position traverse the rest of the array and find the fourth least element in the array "
},
{
"code": null,
"e": 1766,
"s": 1691,
"text": "As 25 is the 4th lowest value hence, it will place at the fourth position."
},
{
"code": null,
"e": 1778,
"s": 1766,
"text": "Fifth Pass:"
},
{
"code": null,
"e": 1884,
"s": 1778,
"text": "At last the largest value present in the array automatically get placed at the last position in the array"
},
{
"code": null,
"e": 1924,
"s": 1884,
"text": "The resulted array is the sorted array."
},
{
"code": null,
"e": 1972,
"s": 1924,
"text": "Initialize minimum value(min_idx) to location 0"
},
{
"code": null,
"e": 2032,
"s": 1972,
"text": "Traverse the array to find the minimum element in the array"
},
{
"code": null,
"e": 2121,
"s": 2032,
"text": "While traversing if any element smaller than min_idx is found then swap both the values."
},
{
"code": null,
"e": 2170,
"s": 2121,
"text": "Then, increment min_idx to point to next element"
},
{
"code": null,
"e": 2199,
"s": 2170,
"text": "Repeat until array is sorted"
},
{
"code": null,
"e": 2250,
"s": 2199,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2252,
"s": 2250,
"text": "C"
},
{
"code": "// C program for implementation of selection sort#include <stdio.h> void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionsint main(){ int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}",
"e": 3204,
"s": 2252,
"text": null
},
{
"code": null,
"e": 3235,
"s": 3204,
"text": "Sorted array: \n11 12 22 25 64 "
},
{
"code": null,
"e": 3330,
"s": 3235,
"text": "Time Complexity: The time complexity of Selection Sort is O(N2) as there are two nested loops:"
},
{
"code": null,
"e": 3387,
"s": 3330,
"text": "One loop to select an element of Array one by one = O(N)"
},
{
"code": null,
"e": 3462,
"s": 3387,
"text": "Another loop to compare that element with every other Array element = O(N)"
},
{
"code": null,
"e": 3520,
"s": 3462,
"text": "Therefore overall complexity = O(N)*O(N) = O(N*N) = O(N2)"
},
{
"code": null,
"e": 3769,
"s": 3520,
"text": "Auxiliary Space: O(1) as the only extra memory used is for temporary variable while swapping two values in Array. The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation. "
},
{
"code": null,
"e": 3900,
"s": 3769,
"text": "Stability : The default implementation is not stable. However it can be made stable. Please see stable selection sort for details."
},
{
"code": null,
"e": 3939,
"s": 3900,
"text": "Yes, it does not require extra space. "
},
{
"code": null,
"e": 4005,
"s": 3939,
"text": "Please refer complete article on Selection Sort for more details!"
},
{
"code": null,
"e": 4021,
"s": 4005,
"text": "subhammahato348"
},
{
"code": null,
"e": 4037,
"s": 4021,
"text": "reshmapatil2772"
},
{
"code": null,
"e": 4048,
"s": 4037,
"text": "C Programs"
},
{
"code": null,
"e": 4146,
"s": 4048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4187,
"s": 4146,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 4218,
"s": 4187,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 4271,
"s": 4218,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 4305,
"s": 4271,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 4327,
"s": 4305,
"text": "C Hello World Program"
},
{
"code": null,
"e": 4417,
"s": 4327,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 4458,
"s": 4417,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 4529,
"s": 4458,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 4558,
"s": 4529,
"text": "C Program for Tower of Hanoi"
}
] |
PLSQL | INITCAP Function
|
20 Sep, 2019
The INITCAP function in PLSQl is used for setting the first character in each word to uppercase and the rest to lowercase.Words are delimited by white space or characters that are not alphanumeric.The INITCAP function in PLSQL can accept char can of any of the datatypes such as CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value returned by the INITCAP function is of the same datatype as char. The database sets the case of the initial characters based on the binary mapping defined for the underlying character set.
Syntax:
INITCAP(string)
Parameters Used:
string:It is used to specify the string whose first character in each word will be converted to uppercase and all remaining characters converted to lowercase.
Return Value:The INITCAP function in PLSQL returns a string value.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE
Test_String string(20) := 'geeksforgeeks';
BEGIN
dbms_output.put_line(INITCAP(Test_String));
END;
Output:
Geeksforgeeks
Example-2:
DECLARE
Test_String string(40) := 'Hello, welcome to geeksforgeeks.';
BEGIN
dbms_output.put_line(INITCAP(Test_String));
END;
Output:
Hello, Welcome To Geeksforgeeks.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Sep, 2019"
},
{
"code": null,
"e": 543,
"s": 28,
"text": "The INITCAP function in PLSQl is used for setting the first character in each word to uppercase and the rest to lowercase.Words are delimited by white space or characters that are not alphanumeric.The INITCAP function in PLSQL can accept char can of any of the datatypes such as CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value returned by the INITCAP function is of the same datatype as char. The database sets the case of the initial characters based on the binary mapping defined for the underlying character set."
},
{
"code": null,
"e": 551,
"s": 543,
"text": "Syntax:"
},
{
"code": null,
"e": 567,
"s": 551,
"text": "INITCAP(string)"
},
{
"code": null,
"e": 584,
"s": 567,
"text": "Parameters Used:"
},
{
"code": null,
"e": 743,
"s": 584,
"text": "string:It is used to specify the string whose first character in each word will be converted to uppercase and all remaining characters converted to lowercase."
},
{
"code": null,
"e": 810,
"s": 743,
"text": "Return Value:The INITCAP function in PLSQL returns a string value."
},
{
"code": null,
"e": 846,
"s": 810,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 895,
"s": 846,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 906,
"s": 895,
"text": "Oracle 12c"
},
{
"code": null,
"e": 917,
"s": 906,
"text": "Oracle 11g"
},
{
"code": null,
"e": 928,
"s": 917,
"text": "Oracle 10g"
},
{
"code": null,
"e": 938,
"s": 928,
"text": "Oracle 9i"
},
{
"code": null,
"e": 948,
"s": 938,
"text": "Oracle 8i"
},
{
"code": null,
"e": 959,
"s": 948,
"text": "Example-1:"
},
{
"code": null,
"e": 1086,
"s": 959,
"text": "DECLARE \n Test_String string(20) := 'geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(INITCAP(Test_String)); \n \nEND; "
},
{
"code": null,
"e": 1094,
"s": 1086,
"text": "Output:"
},
{
"code": null,
"e": 1109,
"s": 1094,
"text": "Geeksforgeeks "
},
{
"code": null,
"e": 1120,
"s": 1109,
"text": "Example-2:"
},
{
"code": null,
"e": 1266,
"s": 1120,
"text": "DECLARE \n Test_String string(40) := 'Hello, welcome to geeksforgeeks.';\n \nBEGIN \n dbms_output.put_line(INITCAP(Test_String)); \n \nEND; "
},
{
"code": null,
"e": 1274,
"s": 1266,
"text": "Output:"
},
{
"code": null,
"e": 1308,
"s": 1274,
"text": "Hello, Welcome To Geeksforgeeks. "
},
{
"code": null,
"e": 1319,
"s": 1308,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 1323,
"s": 1319,
"text": "SQL"
},
{
"code": null,
"e": 1327,
"s": 1323,
"text": "SQL"
}
] |
Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
|
06 May, 2022
The test cases are an extremely important part of any “Software/Project Testing Process”. Hence this Set will be very important for all aspiring software developers. The following are the programs to generate test cases.
Generating Random Numbers
C++
Java
Python3
C#
Javascript
// A C++ Program to generate test cases for// random number#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated#define MAX 10000000 int main(){ // Uncomment the below line to store // the test data in a file // freopen("Test_Cases.in", "w", stdout); // For random values every time srand(time(NULL)); for (int i=1; i<=RUN; i++) printf("%d\n", rand() % MAX); // Uncomment the below line to store // the test data in a file //fclose(stdout); return(0);}
// A Java Program to generate test cases// for random numberimport java.io.*;import java.util.Random; class GeneratingRandomNumbers{ // the number of runs // for the test data generated static int requiredNumbers = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // Driver Code public static void main (String[] args) throws IOException { Random random = new Random(); for(int i = 0; i < requiredNumbers; i++) { int a = random.nextInt(upperBound - lowerBound) + lowerBound; System.out.println(a); } }} // This code is contributed by Madfrost
# A Python3 Program to generate test cases# for random numberimport random # the number of runs# for the test data generatedrequiredNumbers = 5; # minimum range of random numberslowerBound = 0; # maximum range of random numbersupperBound = 1000; # Driver Codeif __name__ == '__main__': for i in range(requiredNumbers): a = random.randrange(0, upperBound - lowerBound) + lowerBound; print(a); # This code is contributed by 29AjayKumar
// A C# Program to generate test cases// for random numberusing System; class GeneratingRandomNumbers{ // the number of runs // for the test data generated static int requiredNumbers = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // Driver Code public static void Main(String[] args) { Random random = new Random(); for(int i = 0; i < requiredNumbers; i++) { int a = random.Next(upperBound - lowerBound) + lowerBound; Console.WriteLine(a); } }} // This code is contributed by Rajput-Ji
<script> let requiredNumbers = 5;let lowerBound = 0;let upperBound = 1000; for(let i = 0; i < requiredNumbers; i++){ let a = Math.floor(Math.random() * (upperBound - lowerBound)) + lowerBound; document.write(a+"<br>");} // This code is contributed by rag2127 </script>
Generating Random Arrays
C++
Java
Python3
C#
Javascript
// A C++ Program to generate test cases for// array filled with random numbers#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated#define MAX 10000000 // Define the maximum number of array elements#define MAXNUM 100 int main(){ // Uncomment the below line to store // the test data in a file //freopen ("Test_Cases_Random_Array.in", "w", stdout); //For random values every time srand(time(NULL)); for (int i=1; i<=RUN; i++) { // Number of array elements int NUM = 1 + rand() % MAXNUM; // First print the number of array elements printf("%d\n", NUM); // Then print the array elements separated // by space for (int j=1; j<=NUM; j++) printf("%d ", rand() % MAX); printf("\n"); } // Uncomment the below line to store // the test data in a file //fclose(stdout); return(0);}
// A Java Program to generate test cases// for array filled with random numbersimport java.io.*;import java.util.Random; class GeneratingRandomArrays{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // minimum size of reqd array static int minSize = 10; // maximum size of reqd array static int maxSize = 20; // Driver Code public static void main (String[] args) throws IOException { Random random = new Random(); for(int i = 0; i < RUN; i++) { int size = random.nextInt(maxSize - minSize) + minSize; int[] array = new int[size]; System.out.println(size); for(int j = 0; j < size; j++) { int a = random.nextInt(upperBound - lowerBound) + lowerBound; System.out.print(a + " "); } System.out.println(); } }} // This code is contributed by Madfrost
# A Python3 Program to generate test cases# for array filled with random numbersimport random # the number of runs# for the test data generatedRUN = 5; # minimum range of random numberslowerBound = 0; # maximum range of random numbersupperBound = 1000; # minimum size of reqd arrayminSize = 10; # maximum size of reqd arraymaxSize = 20; # Driver Codeif __name__ == '__main__': for i in range(RUN): size = random.randrange(0, maxSize - minSize) + minSize; array = [0]*size; print(size); for j in range(size): a = random.randrange(0, upperBound - lowerBound) + lowerBound; print(a, end=" "); print(); # This code is contributed by 29AjayKumar
// A C# Program to generate test cases// for array filled with random numbersusing System; class GeneratingRandomArrays{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // minimum size of reqd array static int minSize = 10; // maximum size of reqd array static int maxSize = 20; // Driver Code public static void Main(String[] args) { Random random = new Random(); for(int i = 0; i < RUN; i++) { int size = random.Next(maxSize - minSize) + minSize; int[] array = new int[size]; Console.WriteLine(size); for(int j = 0; j < size; j++) { int a = random.Next(upperBound - lowerBound) + lowerBound; Console.Write(a + " "); } Console.WriteLine(); } }} // This code is contributed by 29AjayKumar
<script> // A JavaScript Program to generate test cases// for array filled with random numbers // the number of runs// for the test data generatedlet RUN = 5; // minimum range of random numberslet lowerBound = 0; // maximum range of random numberslet upperBound = 1000; // minimum size of reqd arraylet minSize = 10; // maximum size of reqd arraylet maxSize = 20; for(let i = 0; i < RUN; i++) { let size = Math.floor(Math.random() * (maxSize - minSize)) + minSize; let array = new Array(size); document.write(size+"<br>"); for(let j = 0; j < size; j++) { let a = Math.floor(Math.random() * (upperBound - lowerBound)) + lowerBound; document.write(a + " "); } document.write("<br>"); } // This code is contributed by avanitrachhadiya2155 </script>
Generating Random Matrix
C++
Java
Python3
C#
// A C++ Program to generate test cases for// matrix filled with random numbers#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 3 // Define the range of the test data generated#define MAX 100000 // Define the maximum rows in matrix#define MAXROW 10 // Define the maximum columns in matrix#define MAXCOL 10 int main(){ // Uncomment the below line to store // the test data in a file // freopen ("Test_Cases_Random_Matrix.in", "w", stdout); // For random values every time srand(time(NULL)); for (int i=1; i<=RUN; i++) { // Number of rows and columns int row = 1 + rand() % MAXROW; int col = 1 + rand() % MAXCOL; // First print the number of rows and columns printf("%d %d\n", row, col); // Then print the matrix for (int j=1; j<=row; j++) { for (int k=1; k<=col; k++) printf("%d ", rand() % MAX); printf("\n"); } printf("\n"); } // Uncomment the below line to store // the test data in a file // fclose(stdout); return(0);}
// A Java Program to generate test cases for// matrix filled with random numbersimport java.io.*;import java.util.Random; class GeneratingRandomMatrix{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // maximum size of column static int maxColumn = 10; // minimum size of column static int minColumn = 1; // minimum size of row static int minRow = 1; // maximum size of row static int maxRow = 10; // Driver Code public static void main (String[] args) throws IOException { Random random = new Random(); for(int i = 0; i < RUN; i++) { int row = random.nextInt(maxRow - minRow) + minRow; int column = random.nextInt(maxColumn - minColumn) + minColumn; int[][] matrix = new int[row][column]; System.out.println(row + " " + column); for(int j = 0; j < row; j++) { for(int k = 0; k < column; k++) { int a = random.nextInt(upperBound - lowerBound) + lowerBound; System.out.print(a + " "); } System.out.println(); } System.out.println(); } }} // This code is contributed by Madfrost
# A Python3 Program to generate test cases# for matrix filled with random numbersimport random # the number of runs# for the test data generatedRUN = 5; # minimum range of random numberslowerBound = 0; # maximum range of random numbersupperBound = 1000; # maximum size of columnmaxColumn = 10; # minimum size of columnminColumn = 1; # minimum size of rowminRow = 1; # maximum size of rowmaxRow = 10; # Driver Codeif __name__ == '__main__': for i in range(RUN): row = random.randrange(0, maxRow - minRow) + minRow column = random.randrange(0, maxColumn - minColumn) + minColumn matrix = [[0 for i in range(column)] for j in range(row)] print(row, column) for j in range(row): for k in range(column): a = random.randrange(0, upperBound - lowerBound) + lowerBound print(a ,end = " ") print() print() # This code is contributed by Shubham Singh
// A C# Program to generate test cases for// matrix filled with random numbersusing System; public class GeneratingRandomMatrix{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // maximum size of column static int maxColumn = 10; // minimum size of column static int minColumn = 1; // minimum size of row static int minRow = 1; // maximum size of row static int maxRow = 10; // Driver Code public static void Main(String[] args) { Random random = new Random(); for(int i = 0; i < RUN; i++) { int row = random.Next(maxRow - minRow) + minRow; int column = random.Next(maxColumn - minColumn) + minColumn; int[,] matrix = new int[row, column]; Console.WriteLine(row + " " + column); for(int j = 0; j < row; j++) { for(int k = 0; k < column; k++) { int a = random.Next(upperBound - lowerBound) + lowerBound; Console.Write(a + " "); } Console.WriteLine(); } Console.WriteLine(); } }} // This code is contributed by 29AjayKumar
rand() Function– -> Generate random numbers from the range 0 to RAND_MAX (32767) -> Defined in <stdlib.h>/<cstdlib> header -> If we want to assign a random number in the range – m to n [n >= m] to a variable var, then use-var = m + ( rand() % ( n – m + 1 ) ); -> This function is a run-time function. So the values – n, m must be declared before compiling just like we have to declare the size of array before compiling. -> Call this function every time you want to generate a random numbertime() Function -> Return the number of seconds from [00:00:00 UTC, January 1, 1970] -> Defined in <time.h> headersrand(seed) -> Generates random number according to the seed passed to it. -> If this function is not used and we use rand() function then every time we run the program the same random numbers gets generated. -> To overcome the above limitation, we pass time(NULL) as a seed. Hence srand(time(NULL)) is used to generate random values every time the program is made to run. -> Always use this at the beginning of the program, i.e- just after int main() { -> No need to call this function every time you generate a random number -> Defined in <stdlib.h>/<cstdlib> headerfreopen(“output.txt”, “w”, stdout) -> Writes (that’s why we passed “w” as the second argument) all the data to output.txt file (The file must be in the same file as the program is in). -> Used to redirect stdout to a file. -> If the output.txt file is not created before then it gets created in the same file as the program is in.fclose(stdout) -> Closes the standard output stream file to avoid leaks. -> Always use this at the end of the program, i.e- just before return(0) in the int main() function.
rand() Function– -> Generate random numbers from the range 0 to RAND_MAX (32767) -> Defined in <stdlib.h>/<cstdlib> header -> If we want to assign a random number in the range – m to n [n >= m] to a variable var, then use-var = m + ( rand() % ( n – m + 1 ) ); -> This function is a run-time function. So the values – n, m must be declared before compiling just like we have to declare the size of array before compiling. -> Call this function every time you want to generate a random number
time() Function -> Return the number of seconds from [00:00:00 UTC, January 1, 1970] -> Defined in <time.h> header
srand(seed) -> Generates random number according to the seed passed to it. -> If this function is not used and we use rand() function then every time we run the program the same random numbers gets generated. -> To overcome the above limitation, we pass time(NULL) as a seed. Hence srand(time(NULL)) is used to generate random values every time the program is made to run. -> Always use this at the beginning of the program, i.e- just after int main() { -> No need to call this function every time you generate a random number -> Defined in <stdlib.h>/<cstdlib> header
freopen(“output.txt”, “w”, stdout) -> Writes (that’s why we passed “w” as the second argument) all the data to output.txt file (The file must be in the same file as the program is in). -> Used to redirect stdout to a file. -> If the output.txt file is not created before then it gets created in the same file as the program is in.
fclose(stdout) -> Closes the standard output stream file to avoid leaks. -> Always use this at the end of the program, i.e- just before return(0) in the int main() function.
This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Madfrost
Rajput-Ji
29AjayKumar
rag2127
avanitrachhadiya2155
surindertarika1234
SHUBHAMSINGH10
simmytarika5
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 276,
"s": 54,
"text": "The test cases are an extremely important part of any “Software/Project Testing Process”. Hence this Set will be very important for all aspiring software developers. The following are the programs to generate test cases. "
},
{
"code": null,
"e": 304,
"s": 276,
"text": "Generating Random Numbers "
},
{
"code": null,
"e": 308,
"s": 304,
"text": "C++"
},
{
"code": null,
"e": 313,
"s": 308,
"text": "Java"
},
{
"code": null,
"e": 321,
"s": 313,
"text": "Python3"
},
{
"code": null,
"e": 324,
"s": 321,
"text": "C#"
},
{
"code": null,
"e": 335,
"s": 324,
"text": "Javascript"
},
{
"code": "// A C++ Program to generate test cases for// random number#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated#define MAX 10000000 int main(){ // Uncomment the below line to store // the test data in a file // freopen(\"Test_Cases.in\", \"w\", stdout); // For random values every time srand(time(NULL)); for (int i=1; i<=RUN; i++) printf(\"%d\\n\", rand() % MAX); // Uncomment the below line to store // the test data in a file //fclose(stdout); return(0);}",
"e": 937,
"s": 335,
"text": null
},
{
"code": "// A Java Program to generate test cases// for random numberimport java.io.*;import java.util.Random; class GeneratingRandomNumbers{ // the number of runs // for the test data generated static int requiredNumbers = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // Driver Code public static void main (String[] args) throws IOException { Random random = new Random(); for(int i = 0; i < requiredNumbers; i++) { int a = random.nextInt(upperBound - lowerBound) + lowerBound; System.out.println(a); } }} // This code is contributed by Madfrost",
"e": 1704,
"s": 937,
"text": null
},
{
"code": "# A Python3 Program to generate test cases# for random numberimport random # the number of runs# for the test data generatedrequiredNumbers = 5; # minimum range of random numberslowerBound = 0; # maximum range of random numbersupperBound = 1000; # Driver Codeif __name__ == '__main__': for i in range(requiredNumbers): a = random.randrange(0, upperBound - lowerBound) + lowerBound; print(a); # This code is contributed by 29AjayKumar",
"e": 2175,
"s": 1704,
"text": null
},
{
"code": "// A C# Program to generate test cases// for random numberusing System; class GeneratingRandomNumbers{ // the number of runs // for the test data generated static int requiredNumbers = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // Driver Code public static void Main(String[] args) { Random random = new Random(); for(int i = 0; i < requiredNumbers; i++) { int a = random.Next(upperBound - lowerBound) + lowerBound; Console.WriteLine(a); } }} // This code is contributed by Rajput-Ji",
"e": 2889,
"s": 2175,
"text": null
},
{
"code": "<script> let requiredNumbers = 5;let lowerBound = 0;let upperBound = 1000; for(let i = 0; i < requiredNumbers; i++){ let a = Math.floor(Math.random() * (upperBound - lowerBound)) + lowerBound; document.write(a+\"<br>\");} // This code is contributed by rag2127 </script>",
"e": 3168,
"s": 2889,
"text": null
},
{
"code": null,
"e": 3194,
"s": 3168,
"text": "Generating Random Arrays "
},
{
"code": null,
"e": 3198,
"s": 3194,
"text": "C++"
},
{
"code": null,
"e": 3203,
"s": 3198,
"text": "Java"
},
{
"code": null,
"e": 3211,
"s": 3203,
"text": "Python3"
},
{
"code": null,
"e": 3214,
"s": 3211,
"text": "C#"
},
{
"code": null,
"e": 3225,
"s": 3214,
"text": "Javascript"
},
{
"code": "// A C++ Program to generate test cases for// array filled with random numbers#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated#define MAX 10000000 // Define the maximum number of array elements#define MAXNUM 100 int main(){ // Uncomment the below line to store // the test data in a file //freopen (\"Test_Cases_Random_Array.in\", \"w\", stdout); //For random values every time srand(time(NULL)); for (int i=1; i<=RUN; i++) { // Number of array elements int NUM = 1 + rand() % MAXNUM; // First print the number of array elements printf(\"%d\\n\", NUM); // Then print the array elements separated // by space for (int j=1; j<=NUM; j++) printf(\"%d \", rand() % MAX); printf(\"\\n\"); } // Uncomment the below line to store // the test data in a file //fclose(stdout); return(0);}",
"e": 4215,
"s": 3225,
"text": null
},
{
"code": "// A Java Program to generate test cases// for array filled with random numbersimport java.io.*;import java.util.Random; class GeneratingRandomArrays{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // minimum size of reqd array static int minSize = 10; // maximum size of reqd array static int maxSize = 20; // Driver Code public static void main (String[] args) throws IOException { Random random = new Random(); for(int i = 0; i < RUN; i++) { int size = random.nextInt(maxSize - minSize) + minSize; int[] array = new int[size]; System.out.println(size); for(int j = 0; j < size; j++) { int a = random.nextInt(upperBound - lowerBound) + lowerBound; System.out.print(a + \" \"); } System.out.println(); } }} // This code is contributed by Madfrost",
"e": 5401,
"s": 4215,
"text": null
},
{
"code": "# A Python3 Program to generate test cases# for array filled with random numbersimport random # the number of runs# for the test data generatedRUN = 5; # minimum range of random numberslowerBound = 0; # maximum range of random numbersupperBound = 1000; # minimum size of reqd arrayminSize = 10; # maximum size of reqd arraymaxSize = 20; # Driver Codeif __name__ == '__main__': for i in range(RUN): size = random.randrange(0, maxSize - minSize) + minSize; array = [0]*size; print(size); for j in range(size): a = random.randrange(0, upperBound - lowerBound) + lowerBound; print(a, end=\" \"); print(); # This code is contributed by 29AjayKumar",
"e": 6107,
"s": 5401,
"text": null
},
{
"code": "// A C# Program to generate test cases// for array filled with random numbersusing System; class GeneratingRandomArrays{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // minimum size of reqd array static int minSize = 10; // maximum size of reqd array static int maxSize = 20; // Driver Code public static void Main(String[] args) { Random random = new Random(); for(int i = 0; i < RUN; i++) { int size = random.Next(maxSize - minSize) + minSize; int[] array = new int[size]; Console.WriteLine(size); for(int j = 0; j < size; j++) { int a = random.Next(upperBound - lowerBound) + lowerBound; Console.Write(a + \" \"); } Console.WriteLine(); } }} // This code is contributed by 29AjayKumar",
"e": 7183,
"s": 6107,
"text": null
},
{
"code": "<script> // A JavaScript Program to generate test cases// for array filled with random numbers // the number of runs// for the test data generatedlet RUN = 5; // minimum range of random numberslet lowerBound = 0; // maximum range of random numberslet upperBound = 1000; // minimum size of reqd arraylet minSize = 10; // maximum size of reqd arraylet maxSize = 20; for(let i = 0; i < RUN; i++) { let size = Math.floor(Math.random() * (maxSize - minSize)) + minSize; let array = new Array(size); document.write(size+\"<br>\"); for(let j = 0; j < size; j++) { let a = Math.floor(Math.random() * (upperBound - lowerBound)) + lowerBound; document.write(a + \" \"); } document.write(\"<br>\"); } // This code is contributed by avanitrachhadiya2155 </script>",
"e": 8099,
"s": 7183,
"text": null
},
{
"code": null,
"e": 8126,
"s": 8099,
"text": "Generating Random Matrix "
},
{
"code": null,
"e": 8130,
"s": 8126,
"text": "C++"
},
{
"code": null,
"e": 8135,
"s": 8130,
"text": "Java"
},
{
"code": null,
"e": 8143,
"s": 8135,
"text": "Python3"
},
{
"code": null,
"e": 8146,
"s": 8143,
"text": "C#"
},
{
"code": "// A C++ Program to generate test cases for// matrix filled with random numbers#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 3 // Define the range of the test data generated#define MAX 100000 // Define the maximum rows in matrix#define MAXROW 10 // Define the maximum columns in matrix#define MAXCOL 10 int main(){ // Uncomment the below line to store // the test data in a file // freopen (\"Test_Cases_Random_Matrix.in\", \"w\", stdout); // For random values every time srand(time(NULL)); for (int i=1; i<=RUN; i++) { // Number of rows and columns int row = 1 + rand() % MAXROW; int col = 1 + rand() % MAXCOL; // First print the number of rows and columns printf(\"%d %d\\n\", row, col); // Then print the matrix for (int j=1; j<=row; j++) { for (int k=1; k<=col; k++) printf(\"%d \", rand() % MAX); printf(\"\\n\"); } printf(\"\\n\"); } // Uncomment the below line to store // the test data in a file // fclose(stdout); return(0);}",
"e": 9282,
"s": 8146,
"text": null
},
{
"code": "// A Java Program to generate test cases for// matrix filled with random numbersimport java.io.*;import java.util.Random; class GeneratingRandomMatrix{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // maximum size of column static int maxColumn = 10; // minimum size of column static int minColumn = 1; // minimum size of row static int minRow = 1; // maximum size of row static int maxRow = 10; // Driver Code public static void main (String[] args) throws IOException { Random random = new Random(); for(int i = 0; i < RUN; i++) { int row = random.nextInt(maxRow - minRow) + minRow; int column = random.nextInt(maxColumn - minColumn) + minColumn; int[][] matrix = new int[row][column]; System.out.println(row + \" \" + column); for(int j = 0; j < row; j++) { for(int k = 0; k < column; k++) { int a = random.nextInt(upperBound - lowerBound) + lowerBound; System.out.print(a + \" \"); } System.out.println(); } System.out.println(); } }} // This code is contributed by Madfrost",
"e": 10844,
"s": 9282,
"text": null
},
{
"code": "# A Python3 Program to generate test cases# for matrix filled with random numbersimport random # the number of runs# for the test data generatedRUN = 5; # minimum range of random numberslowerBound = 0; # maximum range of random numbersupperBound = 1000; # maximum size of columnmaxColumn = 10; # minimum size of columnminColumn = 1; # minimum size of rowminRow = 1; # maximum size of rowmaxRow = 10; # Driver Codeif __name__ == '__main__': for i in range(RUN): row = random.randrange(0, maxRow - minRow) + minRow column = random.randrange(0, maxColumn - minColumn) + minColumn matrix = [[0 for i in range(column)] for j in range(row)] print(row, column) for j in range(row): for k in range(column): a = random.randrange(0, upperBound - lowerBound) + lowerBound print(a ,end = \" \") print() print() # This code is contributed by Shubham Singh",
"e": 11836,
"s": 10844,
"text": null
},
{
"code": "// A C# Program to generate test cases for// matrix filled with random numbersusing System; public class GeneratingRandomMatrix{ // the number of runs // for the test data generated static int RUN = 5; // minimum range of random numbers static int lowerBound = 0; // maximum range of random numbers static int upperBound = 1000; // maximum size of column static int maxColumn = 10; // minimum size of column static int minColumn = 1; // minimum size of row static int minRow = 1; // maximum size of row static int maxRow = 10; // Driver Code public static void Main(String[] args) { Random random = new Random(); for(int i = 0; i < RUN; i++) { int row = random.Next(maxRow - minRow) + minRow; int column = random.Next(maxColumn - minColumn) + minColumn; int[,] matrix = new int[row, column]; Console.WriteLine(row + \" \" + column); for(int j = 0; j < row; j++) { for(int k = 0; k < column; k++) { int a = random.Next(upperBound - lowerBound) + lowerBound; Console.Write(a + \" \"); } Console.WriteLine(); } Console.WriteLine(); } }} // This code is contributed by 29AjayKumar",
"e": 13340,
"s": 11836,
"text": null
},
{
"code": null,
"e": 15018,
"s": 13342,
"text": "rand() Function– -> Generate random numbers from the range 0 to RAND_MAX (32767) -> Defined in <stdlib.h>/<cstdlib> header -> If we want to assign a random number in the range – m to n [n >= m] to a variable var, then use-var = m + ( rand() % ( n – m + 1 ) ); -> This function is a run-time function. So the values – n, m must be declared before compiling just like we have to declare the size of array before compiling. -> Call this function every time you want to generate a random numbertime() Function -> Return the number of seconds from [00:00:00 UTC, January 1, 1970] -> Defined in <time.h> headersrand(seed) -> Generates random number according to the seed passed to it. -> If this function is not used and we use rand() function then every time we run the program the same random numbers gets generated. -> To overcome the above limitation, we pass time(NULL) as a seed. Hence srand(time(NULL)) is used to generate random values every time the program is made to run. -> Always use this at the beginning of the program, i.e- just after int main() { -> No need to call this function every time you generate a random number -> Defined in <stdlib.h>/<cstdlib> headerfreopen(“output.txt”, “w”, stdout) -> Writes (that’s why we passed “w” as the second argument) all the data to output.txt file (The file must be in the same file as the program is in). -> Used to redirect stdout to a file. -> If the output.txt file is not created before then it gets created in the same file as the program is in.fclose(stdout) -> Closes the standard output stream file to avoid leaks. -> Always use this at the end of the program, i.e- just before return(0) in the int main() function."
},
{
"code": null,
"e": 15509,
"s": 15018,
"text": "rand() Function– -> Generate random numbers from the range 0 to RAND_MAX (32767) -> Defined in <stdlib.h>/<cstdlib> header -> If we want to assign a random number in the range – m to n [n >= m] to a variable var, then use-var = m + ( rand() % ( n – m + 1 ) ); -> This function is a run-time function. So the values – n, m must be declared before compiling just like we have to declare the size of array before compiling. -> Call this function every time you want to generate a random number"
},
{
"code": null,
"e": 15624,
"s": 15509,
"text": "time() Function -> Return the number of seconds from [00:00:00 UTC, January 1, 1970] -> Defined in <time.h> header"
},
{
"code": null,
"e": 16193,
"s": 15624,
"text": "srand(seed) -> Generates random number according to the seed passed to it. -> If this function is not used and we use rand() function then every time we run the program the same random numbers gets generated. -> To overcome the above limitation, we pass time(NULL) as a seed. Hence srand(time(NULL)) is used to generate random values every time the program is made to run. -> Always use this at the beginning of the program, i.e- just after int main() { -> No need to call this function every time you generate a random number -> Defined in <stdlib.h>/<cstdlib> header"
},
{
"code": null,
"e": 16524,
"s": 16193,
"text": "freopen(“output.txt”, “w”, stdout) -> Writes (that’s why we passed “w” as the second argument) all the data to output.txt file (The file must be in the same file as the program is in). -> Used to redirect stdout to a file. -> If the output.txt file is not created before then it gets created in the same file as the program is in."
},
{
"code": null,
"e": 16698,
"s": 16524,
"text": "fclose(stdout) -> Closes the standard output stream file to avoid leaks. -> Always use this at the end of the program, i.e- just before return(0) in the int main() function."
},
{
"code": null,
"e": 17093,
"s": 16698,
"text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 17102,
"s": 17093,
"text": "Madfrost"
},
{
"code": null,
"e": 17112,
"s": 17102,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 17124,
"s": 17112,
"text": "29AjayKumar"
},
{
"code": null,
"e": 17132,
"s": 17124,
"text": "rag2127"
},
{
"code": null,
"e": 17153,
"s": 17132,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 17172,
"s": 17153,
"text": "surindertarika1234"
},
{
"code": null,
"e": 17187,
"s": 17172,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 17200,
"s": 17187,
"text": "simmytarika5"
},
{
"code": null,
"e": 17224,
"s": 17200,
"text": "Competitive Programming"
}
] |
strtok() and strtok_r() functions in C with examples
|
17 Jun, 2022
C provides two functions strtok() and strtok_r() for splitting a string by some delimiter. Splitting a string is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array.
strtok() Method: Splits str[] according to given delimiters and returns the next token. It needs to be called in a loop to get all tokens. It returns NULL when there are no more tokens.
char * strtok(char str[], const char *delims);
Example:
C
// C/C++ program for splitting a string// using strtok()#include& lt; stdio.h & gt;#include& lt; string.h & gt; int main(){ char str[] = "Geeks-for-Geeks" ; // Returns first token char* token = strtok(str, " - "); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf(" % s\n & quot;, token); token = strtok(NULL, " - "); } return 0;}
Output:
Geeks
for
Geeks
strtok_r(): Just like strtok() function in C, strtok_r() does the same task of parsing a string into a sequence of tokens. strtok_r() is a reentrant version of strtok(). There are two ways we can call strtok_r()
// The third argument saveptr is a pointer to a char *
// variable that is used internally by strtok_r() in
// order to maintain context between successive calls
// that parse the same string.
char *strtok_r(char *str, const char *delim, char **saveptr);
Below is a simple C program to show the use of strtok_r() :
CPP
// C program to demonstrate working of strtok_r()// by splitting string based on space character.#include <stdio.h>#include <string.h> int main(){ char str[] = "Geeks for Geeks"; char* token; char* rest = str; while ((token = strtok_r(rest, " ", &rest))) printf("%s\n", token); return (0);}
Output:
Geeks
for
Geeks
Example 2
C
// C code to demonstrate working of// strtok#include <stdio.h>#include <string.h> // Driver functionint main(){ // Declaration of string char gfg[100] = " Geeks - for - geeks - Contribute"; // Declaration of delimiter const char s[4] = "-"; char* tok; // Use of strtok // get first token tok = strtok(gfg, s); // Checks for delimiter while (tok != 0) { printf(" %s\n", tok); // Use of strtok // go through other tokens tok = strtok(0, s); } return (0);}
Output:
Geeks
for
geeks
Contribute
Practical Application: strtok can be used to split a string in multiple strings based on some separators. A simple CSV file support might be implemented using this function. CSV files have commas as delimiters.
Example:
C
// C code to demonstrate practical application of// strtok#include <stdio.h>#include <string.h> // Driver functionint main(){ // Declaration of string // Information to be converted into CSV file char gfg[100] = " 1997 Ford E350 ac 3000.00"; // Declaration of delimiter const char s[4] = " "; char* tok; // Use of strtok // get first token tok = strtok(gfg, s); // Checks for delimiter while (tok != 0) { printf("%s, ", tok); // Use of strtok // go through other tokens tok = strtok(0, s); } return (0);}
Output:
1997, Ford, E350, ac, 3000.00,
Let us see the differences in a tabular form as shown below as follows:
The syntax is as follows:
char *strtok(char *str, const char *delim)
This article is contributed by MAZHAR IMAM KHAN and shantanu_23. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
argone
akshaysingh98088
mayank007rawa
CPP-Library
cpp-string
C++
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
vector erase() and clear() in C++
Substring in C++
C++ Classes and Objects
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Virtual Function in C++
C++ Data Types
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "C provides two functions strtok() and strtok_r() for splitting a string by some delimiter. Splitting a string is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. "
},
{
"code": null,
"e": 482,
"s": 295,
"text": "strtok() Method: Splits str[] according to given delimiters and returns the next token. It needs to be called in a loop to get all tokens. It returns NULL when there are no more tokens."
},
{
"code": null,
"e": 529,
"s": 482,
"text": "char * strtok(char str[], const char *delims);"
},
{
"code": null,
"e": 538,
"s": 529,
"text": "Example:"
},
{
"code": null,
"e": 540,
"s": 538,
"text": "C"
},
{
"code": "// C/C++ program for splitting a string// using strtok()#include& lt; stdio.h & gt;#include& lt; string.h & gt; int main(){ char str[] = \"Geeks-for-Geeks\" ; // Returns first token char* token = strtok(str, \" - \"); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf(\" % s\\n & quot;, token); token = strtok(NULL, \" - \"); } return 0;}",
"e": 969,
"s": 540,
"text": null
},
{
"code": null,
"e": 978,
"s": 969,
"text": "Output: "
},
{
"code": null,
"e": 994,
"s": 978,
"text": "Geeks\nfor\nGeeks"
},
{
"code": null,
"e": 1207,
"s": 994,
"text": "strtok_r(): Just like strtok() function in C, strtok_r() does the same task of parsing a string into a sequence of tokens. strtok_r() is a reentrant version of strtok(). There are two ways we can call strtok_r() "
},
{
"code": null,
"e": 1464,
"s": 1207,
"text": "// The third argument saveptr is a pointer to a char * \n// variable that is used internally by strtok_r() in \n// order to maintain context between successive calls\n// that parse the same string.\nchar *strtok_r(char *str, const char *delim, char **saveptr);"
},
{
"code": null,
"e": 1525,
"s": 1464,
"text": "Below is a simple C program to show the use of strtok_r() : "
},
{
"code": null,
"e": 1529,
"s": 1525,
"text": "CPP"
},
{
"code": "// C program to demonstrate working of strtok_r()// by splitting string based on space character.#include <stdio.h>#include <string.h> int main(){ char str[] = \"Geeks for Geeks\"; char* token; char* rest = str; while ((token = strtok_r(rest, \" \", &rest))) printf(\"%s\\n\", token); return (0);}",
"e": 1844,
"s": 1529,
"text": null
},
{
"code": null,
"e": 1853,
"s": 1844,
"text": "Output: "
},
{
"code": null,
"e": 1869,
"s": 1853,
"text": "Geeks\nfor\nGeeks"
},
{
"code": null,
"e": 1880,
"s": 1869,
"text": "Example 2 "
},
{
"code": null,
"e": 1882,
"s": 1880,
"text": "C"
},
{
"code": "// C code to demonstrate working of// strtok#include <stdio.h>#include <string.h> // Driver functionint main(){ // Declaration of string char gfg[100] = \" Geeks - for - geeks - Contribute\"; // Declaration of delimiter const char s[4] = \"-\"; char* tok; // Use of strtok // get first token tok = strtok(gfg, s); // Checks for delimiter while (tok != 0) { printf(\" %s\\n\", tok); // Use of strtok // go through other tokens tok = strtok(0, s); } return (0);}",
"e": 2405,
"s": 1882,
"text": null
},
{
"code": null,
"e": 2414,
"s": 2405,
"text": "Output: "
},
{
"code": null,
"e": 2441,
"s": 2414,
"text": "Geeks\nfor\ngeeks\nContribute"
},
{
"code": null,
"e": 2652,
"s": 2441,
"text": "Practical Application: strtok can be used to split a string in multiple strings based on some separators. A simple CSV file support might be implemented using this function. CSV files have commas as delimiters."
},
{
"code": null,
"e": 2661,
"s": 2652,
"text": "Example:"
},
{
"code": null,
"e": 2663,
"s": 2661,
"text": "C"
},
{
"code": "// C code to demonstrate practical application of// strtok#include <stdio.h>#include <string.h> // Driver functionint main(){ // Declaration of string // Information to be converted into CSV file char gfg[100] = \" 1997 Ford E350 ac 3000.00\"; // Declaration of delimiter const char s[4] = \" \"; char* tok; // Use of strtok // get first token tok = strtok(gfg, s); // Checks for delimiter while (tok != 0) { printf(\"%s, \", tok); // Use of strtok // go through other tokens tok = strtok(0, s); } return (0);}",
"e": 3240,
"s": 2663,
"text": null
},
{
"code": null,
"e": 3249,
"s": 3240,
"text": "Output: "
},
{
"code": null,
"e": 3280,
"s": 3249,
"text": "1997, Ford, E350, ac, 3000.00,"
},
{
"code": null,
"e": 3353,
"s": 3280,
"text": "Let us see the differences in a tabular form as shown below as follows: "
},
{
"code": null,
"e": 3379,
"s": 3353,
"text": "The syntax is as follows:"
},
{
"code": null,
"e": 3422,
"s": 3379,
"text": "char *strtok(char *str, const char *delim)"
},
{
"code": null,
"e": 3738,
"s": 3422,
"text": "This article is contributed by MAZHAR IMAM KHAN and shantanu_23. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3867,
"s": 3738,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3874,
"s": 3867,
"text": "argone"
},
{
"code": null,
"e": 3891,
"s": 3874,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 3905,
"s": 3891,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3917,
"s": 3905,
"text": "CPP-Library"
},
{
"code": null,
"e": 3928,
"s": 3917,
"text": "cpp-string"
},
{
"code": null,
"e": 3932,
"s": 3928,
"text": "C++"
},
{
"code": null,
"e": 3951,
"s": 3932,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3955,
"s": 3951,
"text": "CPP"
},
{
"code": null,
"e": 4053,
"s": 3955,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4096,
"s": 4053,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4121,
"s": 4096,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 4155,
"s": 4121,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 4172,
"s": 4155,
"text": "Substring in C++"
},
{
"code": null,
"e": 4196,
"s": 4172,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 4250,
"s": 4196,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4274,
"s": 4250,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 4314,
"s": 4274,
"text": "2D Vector In C++ With User Defined Size"
},
{
"code": null,
"e": 4338,
"s": 4314,
"text": "Virtual Function in C++"
}
] |
How to Display Multiple Images in One Window using OpenCV Python?
|
06 Apr, 2022
Prerequisites: Opencv
In this article, we will show how to display Multiple Images In One window using OpenCV in Python.
Import module
Load the Multiple images using cv2.imread()
Concatenate the images using concatenate(), with axis value provided as per orientation requirement
Display all the images using cv2.imshow()
Wait for keyboard button press using cv2.waitKey()
Exit window and destroy all windows using cv2.destroyAllWindows()
cv2.imread(): reads an image file from the given specific location
concatenate((image1,image2), axis): concatenates multiple images along a given mentioned axis (horizontal or vertical), The value of axis is given as 1 for combining them horizontally and 0 for combining them vertically.
cv2.imshow(): displays an image in a window
cv2.waitKey(): is a keyboard binding function. Its argument is the time in milliseconds. The function waits for specified milliseconds for any keyboard event.
cv2.destroyAllWindows(): If you have multiple windows open and you do not need those to be open, you can use cv2.destroyAllWindows() to close those all.
Program:
Python3
import cv2import numpy as np # Read First Imageimg1 = cv2.imread('GFG.png') # Read Second Imageimg2 = cv2.imread('GFG.png') # concatenate image HorizontallyHori = np.concatenate((img1, img2), axis=1) # concatenate image VerticallyVerti = np.concatenate((img1, img2), axis=0) cv2.imshow('HORIZONTAL', Hori)cv2.imshow('VERTICAL', Verti) cv2.waitKey(0)cv2.destroyAllWindows()
Input:
GFG.png
Output:
simmytarika5
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Apr, 2022"
},
{
"code": null,
"e": 75,
"s": 53,
"text": "Prerequisites: Opencv"
},
{
"code": null,
"e": 174,
"s": 75,
"text": "In this article, we will show how to display Multiple Images In One window using OpenCV in Python."
},
{
"code": null,
"e": 188,
"s": 174,
"text": "Import module"
},
{
"code": null,
"e": 232,
"s": 188,
"text": "Load the Multiple images using cv2.imread()"
},
{
"code": null,
"e": 332,
"s": 232,
"text": "Concatenate the images using concatenate(), with axis value provided as per orientation requirement"
},
{
"code": null,
"e": 374,
"s": 332,
"text": "Display all the images using cv2.imshow()"
},
{
"code": null,
"e": 425,
"s": 374,
"text": "Wait for keyboard button press using cv2.waitKey()"
},
{
"code": null,
"e": 491,
"s": 425,
"text": "Exit window and destroy all windows using cv2.destroyAllWindows()"
},
{
"code": null,
"e": 558,
"s": 491,
"text": "cv2.imread(): reads an image file from the given specific location"
},
{
"code": null,
"e": 779,
"s": 558,
"text": "concatenate((image1,image2), axis): concatenates multiple images along a given mentioned axis (horizontal or vertical), The value of axis is given as 1 for combining them horizontally and 0 for combining them vertically."
},
{
"code": null,
"e": 823,
"s": 779,
"text": "cv2.imshow(): displays an image in a window"
},
{
"code": null,
"e": 982,
"s": 823,
"text": "cv2.waitKey(): is a keyboard binding function. Its argument is the time in milliseconds. The function waits for specified milliseconds for any keyboard event."
},
{
"code": null,
"e": 1135,
"s": 982,
"text": "cv2.destroyAllWindows(): If you have multiple windows open and you do not need those to be open, you can use cv2.destroyAllWindows() to close those all."
},
{
"code": null,
"e": 1144,
"s": 1135,
"text": "Program:"
},
{
"code": null,
"e": 1152,
"s": 1144,
"text": "Python3"
},
{
"code": "import cv2import numpy as np # Read First Imageimg1 = cv2.imread('GFG.png') # Read Second Imageimg2 = cv2.imread('GFG.png') # concatenate image HorizontallyHori = np.concatenate((img1, img2), axis=1) # concatenate image VerticallyVerti = np.concatenate((img1, img2), axis=0) cv2.imshow('HORIZONTAL', Hori)cv2.imshow('VERTICAL', Verti) cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 1526,
"s": 1152,
"text": null
},
{
"code": null,
"e": 1533,
"s": 1526,
"text": "Input:"
},
{
"code": null,
"e": 1541,
"s": 1533,
"text": "GFG.png"
},
{
"code": null,
"e": 1549,
"s": 1541,
"text": "Output:"
},
{
"code": null,
"e": 1562,
"s": 1549,
"text": "simmytarika5"
},
{
"code": null,
"e": 1569,
"s": 1562,
"text": "Picked"
},
{
"code": null,
"e": 1583,
"s": 1569,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 1590,
"s": 1583,
"text": "Python"
},
{
"code": null,
"e": 1688,
"s": 1590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1706,
"s": 1688,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1748,
"s": 1706,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1770,
"s": 1748,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1805,
"s": 1770,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1831,
"s": 1805,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1863,
"s": 1831,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1892,
"s": 1863,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1922,
"s": 1892,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1949,
"s": 1922,
"text": "Python Classes and Objects"
}
] |
How to Insert an element at a specific position in an Array in Java
|
02 Aug, 2021
An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in Java.Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos.
Approach 1: Here’s how to do it.
First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posCreate a new array with the size one greater than the previous sizeCopy all the elements from previous array into the new array till the position posInsert the element x at position posInsert the rest of the elements from the previous array into the new array after the pos
First get the element to be inserted, say x
Then get the position at which this element is to be inserted, say pos
Create a new array with the size one greater than the previous size
Copy all the elements from previous array into the new array till the position pos
Insert the element x at position pos
Insert the rest of the elements from the previous array into the new array after the pos
Below is the implementation of the above approach:
Java
// Java Program to Insert an element// at a specific position in an Array import java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to insert x in arr at position pos public static int[] insertX(int n, int arr[], int x, int pos) { int i; // create a new array of size n+1 int newarr[] = new int[n + 1]; // insert the elements from // the old array into the new array // insert all elements till pos // then insert x at pos // then insert rest of the elements for (i = 0; i < n + 1; i++) { if (i < pos - 1) newarr[i] = arr[i]; else if (i == pos - 1) newarr[i] = x; else newarr[i] = arr[i - 1]; } return newarr; } // Driver code public static void main(String[] args) { int n = 10; int i; // initial array of size 10 int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // print the original array System.out.println("Initial Array:\n" + Arrays.toString(arr)); // element to be inserted int x = 50; // position at which element // is to be inserted int pos = 5; // call the method to insert x // in arr at position pos arr = insertX(n, arr, x, pos); // print the updated array System.out.println("\nArray with " + x + " inserted at position " + pos + ":\n" + Arrays.toString(arr)); }}
Initial Array:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array with 50 inserted at position 5:
[1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]
Approach 2: Here’s how to do it.
First get the element to be inserted, say elementThen get the position at which this element is to be inserted, say positionConvert array to ArrayListAdd element at position using list.add(position, element)Convert ArrayList back to array and print
First get the element to be inserted, say element
Then get the position at which this element is to be inserted, say position
Convert array to ArrayList
Add element at position using list.add(position, element)
Convert ArrayList back to array and print
Below is the implementation of the above approach:
Java
// Java Program to Insert an element// at a specific position in an Array// using ArrayListimport java.util.ArrayList;import java.util.Arrays;import java.util.List; public class AddElementAtPositionInArray { // Method to add element at position private static void addElement( Integer[] arr, int element, int position) { // Converting array to ArrayList List<Integer> list = new ArrayList<>( Arrays.asList(arr)); // Adding the element at position list.add(position - 1, element); // Converting the list back to array arr = list.toArray(arr); // Printing the original array System.out.println("Initial Array:\n" + Arrays.toString(arr)); // Printing the updated array System.out.println("\nArray with " + element + " inserted at position " + position + ":\n" + Arrays.toString(arr)); } // Drivers Method public static void main(String[] args) { // Sample array Integer[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Element to be inserted int element = 50; // Position to insert int position = 5; // Calling the function to insert addElement(arr, element, position); }}
Initial Array:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array with 50 inserted at position 5:
[1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]
GauravWable
adnanirshad158
sagartomar9927
Java-Array-Programs
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Aug, 2021"
},
{
"code": null,
"e": 324,
"s": 54,
"text": "An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in Java.Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. "
},
{
"code": null,
"e": 358,
"s": 324,
"text": "Approach 1: Here’s how to do it. "
},
{
"code": null,
"e": 745,
"s": 358,
"text": "First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posCreate a new array with the size one greater than the previous sizeCopy all the elements from previous array into the new array till the position posInsert the element x at position posInsert the rest of the elements from the previous array into the new array after the pos"
},
{
"code": null,
"e": 789,
"s": 745,
"text": "First get the element to be inserted, say x"
},
{
"code": null,
"e": 860,
"s": 789,
"text": "Then get the position at which this element is to be inserted, say pos"
},
{
"code": null,
"e": 928,
"s": 860,
"text": "Create a new array with the size one greater than the previous size"
},
{
"code": null,
"e": 1011,
"s": 928,
"text": "Copy all the elements from previous array into the new array till the position pos"
},
{
"code": null,
"e": 1048,
"s": 1011,
"text": "Insert the element x at position pos"
},
{
"code": null,
"e": 1137,
"s": 1048,
"text": "Insert the rest of the elements from the previous array into the new array after the pos"
},
{
"code": null,
"e": 1189,
"s": 1137,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1194,
"s": 1189,
"text": "Java"
},
{
"code": "// Java Program to Insert an element// at a specific position in an Array import java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to insert x in arr at position pos public static int[] insertX(int n, int arr[], int x, int pos) { int i; // create a new array of size n+1 int newarr[] = new int[n + 1]; // insert the elements from // the old array into the new array // insert all elements till pos // then insert x at pos // then insert rest of the elements for (i = 0; i < n + 1; i++) { if (i < pos - 1) newarr[i] = arr[i]; else if (i == pos - 1) newarr[i] = x; else newarr[i] = arr[i - 1]; } return newarr; } // Driver code public static void main(String[] args) { int n = 10; int i; // initial array of size 10 int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // print the original array System.out.println(\"Initial Array:\\n\" + Arrays.toString(arr)); // element to be inserted int x = 50; // position at which element // is to be inserted int pos = 5; // call the method to insert x // in arr at position pos arr = insertX(n, arr, x, pos); // print the updated array System.out.println(\"\\nArray with \" + x + \" inserted at position \" + pos + \":\\n\" + Arrays.toString(arr)); }}",
"e": 2841,
"s": 1194,
"text": null
},
{
"code": null,
"e": 2963,
"s": 2841,
"text": "Initial Array:\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nArray with 50 inserted at position 5:\n[1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]"
},
{
"code": null,
"e": 2999,
"s": 2965,
"text": "Approach 2: Here’s how to do it. "
},
{
"code": null,
"e": 3248,
"s": 2999,
"text": "First get the element to be inserted, say elementThen get the position at which this element is to be inserted, say positionConvert array to ArrayListAdd element at position using list.add(position, element)Convert ArrayList back to array and print"
},
{
"code": null,
"e": 3298,
"s": 3248,
"text": "First get the element to be inserted, say element"
},
{
"code": null,
"e": 3374,
"s": 3298,
"text": "Then get the position at which this element is to be inserted, say position"
},
{
"code": null,
"e": 3401,
"s": 3374,
"text": "Convert array to ArrayList"
},
{
"code": null,
"e": 3459,
"s": 3401,
"text": "Add element at position using list.add(position, element)"
},
{
"code": null,
"e": 3501,
"s": 3459,
"text": "Convert ArrayList back to array and print"
},
{
"code": null,
"e": 3553,
"s": 3501,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3558,
"s": 3553,
"text": "Java"
},
{
"code": "// Java Program to Insert an element// at a specific position in an Array// using ArrayListimport java.util.ArrayList;import java.util.Arrays;import java.util.List; public class AddElementAtPositionInArray { // Method to add element at position private static void addElement( Integer[] arr, int element, int position) { // Converting array to ArrayList List<Integer> list = new ArrayList<>( Arrays.asList(arr)); // Adding the element at position list.add(position - 1, element); // Converting the list back to array arr = list.toArray(arr); // Printing the original array System.out.println(\"Initial Array:\\n\" + Arrays.toString(arr)); // Printing the updated array System.out.println(\"\\nArray with \" + element + \" inserted at position \" + position + \":\\n\" + Arrays.toString(arr)); } // Drivers Method public static void main(String[] args) { // Sample array Integer[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Element to be inserted int element = 50; // Position to insert int position = 5; // Calling the function to insert addElement(arr, element, position); }}",
"e": 4960,
"s": 3558,
"text": null
},
{
"code": null,
"e": 5082,
"s": 4960,
"text": "Initial Array:\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nArray with 50 inserted at position 5:\n[1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]"
},
{
"code": null,
"e": 5096,
"s": 5084,
"text": "GauravWable"
},
{
"code": null,
"e": 5111,
"s": 5096,
"text": "adnanirshad158"
},
{
"code": null,
"e": 5126,
"s": 5111,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5146,
"s": 5126,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 5160,
"s": 5146,
"text": "Java Programs"
}
] |
How to convert a std::string to const char* or char* in C++?
|
In this section, we will see how to convert C++ string (std::string) to const char* or char*. These formats are C style strings. We have a function called c_str(). This will help us to do the task. It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
Following is the declaration for std::string::c_str.
const char* c_str() const;
This function returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. If an exception is thrown, there are no changes in the string.
Live Demo
#include <iostream>
#include <cstring>
#include <string>
int main () {
std::string str ("Please divide this sentence into parts");
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
char * p = std::strtok (cstr," ");
while (p!=0) {
std::cout << p << '\n';
p = std::strtok(NULL," ");
}
delete[] cstr;
return 0;
}
Please
divide
this
sentence
into
parts
|
[
{
"code": null,
"e": 1545,
"s": 1187,
"text": "In this section, we will see how to convert C++ string (std::string) to const char* or char*. These formats are C style strings. We have a function called c_str(). This will help us to do the task. It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object."
},
{
"code": null,
"e": 1598,
"s": 1545,
"text": "Following is the declaration for std::string::c_str."
},
{
"code": null,
"e": 1625,
"s": 1598,
"text": "const char* c_str() const;"
},
{
"code": null,
"e": 1859,
"s": 1625,
"text": "This function returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. If an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 1870,
"s": 1859,
"text": " Live Demo"
},
{
"code": null,
"e": 2244,
"s": 1870,
"text": "#include <iostream>\n#include <cstring>\n#include <string>\n\nint main () {\n std::string str (\"Please divide this sentence into parts\");\n\n char * cstr = new char [str.length()+1];\n std::strcpy (cstr, str.c_str());\n\n char * p = std::strtok (cstr,\" \");\n while (p!=0) {\n std::cout << p << '\\n';\n p = std::strtok(NULL,\" \");\n }\n delete[] cstr;\n return 0;\n}"
},
{
"code": null,
"e": 2283,
"s": 2244,
"text": "Please\ndivide\nthis\nsentence\ninto\nparts"
}
] |
Count occurrence of a given character in a string using Stream API in Java
|
29 May, 2019
Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using Stream API.
Examples:
Input: str = "geeksforgeeks", c = 'e'
Output: 4
'e' appears four times in str.
Input: str = "abccdefgaa", c = 'a'
Output: 3
'a' appears three times in str.
Approach:
Convert the string into character stream
Check if the character in the stream is the character to be counted using filter() function.
Count the matched characters using the count() function
Below is the implementation of the above approach:
// Java program to count occurrences// of a character using Stream import java.util.stream.*; class GFG { // Method that returns the count of the given // character in the string public static long count(String s, char ch) { return s.chars() .filter(c -> c == ch) .count(); } // Driver method public static void main(String args[]) { String str = "geeksforgeeks"; char c = 'e'; System.out.println(count(str, c)); }}
4
Related Article: Program to count occurrence of a given character in a string
Java-Stream-programs
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Write a program to reverse an array or string
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 174,
"s": 28,
"text": "Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using Stream API."
},
{
"code": null,
"e": 184,
"s": 174,
"text": "Examples:"
},
{
"code": null,
"e": 343,
"s": 184,
"text": "Input: str = \"geeksforgeeks\", c = 'e'\nOutput: 4\n'e' appears four times in str.\n\nInput: str = \"abccdefgaa\", c = 'a' \nOutput: 3\n'a' appears three times in str.\n"
},
{
"code": null,
"e": 353,
"s": 343,
"text": "Approach:"
},
{
"code": null,
"e": 394,
"s": 353,
"text": "Convert the string into character stream"
},
{
"code": null,
"e": 487,
"s": 394,
"text": "Check if the character in the stream is the character to be counted using filter() function."
},
{
"code": null,
"e": 543,
"s": 487,
"text": "Count the matched characters using the count() function"
},
{
"code": null,
"e": 594,
"s": 543,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to count occurrences// of a character using Stream import java.util.stream.*; class GFG { // Method that returns the count of the given // character in the string public static long count(String s, char ch) { return s.chars() .filter(c -> c == ch) .count(); } // Driver method public static void main(String args[]) { String str = \"geeksforgeeks\"; char c = 'e'; System.out.println(count(str, c)); }}",
"e": 1095,
"s": 594,
"text": null
},
{
"code": null,
"e": 1098,
"s": 1095,
"text": "4\n"
},
{
"code": null,
"e": 1176,
"s": 1098,
"text": "Related Article: Program to count occurrence of a given character in a string"
},
{
"code": null,
"e": 1197,
"s": 1176,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 1202,
"s": 1197,
"text": "Java"
},
{
"code": null,
"e": 1210,
"s": 1202,
"text": "Strings"
},
{
"code": null,
"e": 1218,
"s": 1210,
"text": "Strings"
},
{
"code": null,
"e": 1223,
"s": 1218,
"text": "Java"
},
{
"code": null,
"e": 1321,
"s": 1223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1336,
"s": 1321,
"text": "Stream In Java"
},
{
"code": null,
"e": 1357,
"s": 1336,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1378,
"s": 1357,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1397,
"s": 1378,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1414,
"s": 1397,
"text": "Generics in Java"
},
{
"code": null,
"e": 1460,
"s": 1414,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 1520,
"s": 1460,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 1535,
"s": 1520,
"text": "C++ Data Types"
},
{
"code": null,
"e": 1580,
"s": 1535,
"text": "Different Methods to Reverse a String in C++"
}
] |
Make Notepad using Tkinter
|
07 Sep, 2021
Let’s see how to create a simple notepad in Python using Tkinter. This notepad GUI will consist of various menu like file and edit, using which all functionalities like saving the file, opening a file, editing, cut and paste can be done.
Now for creating this notepad, Python 3 and Tkinter should already be installed in your system. You can download suitable python package as per system requirement. After you have successfully installed python you need to install Tkinter (a Python’s GUI package).
Use this command to install Tkinter :
pip install python-tk
Importing Tkinter :
Python
import tkinterimport osfrom tkinter import * # To get the space above for messagefrom tkinter.messagebox import * # To get the dialog box to open when requiredfrom tkinter.filedialog import *
Note : messagebox is used to write the message in the white box called notepad and filedialog is used for the dialog box to appear when you are opening file from anywhere in your system or saving your file in a particular position or place. Adding Menu :
Python
# Add controls(widget) self.__thisTextArea.grid(sticky = N + E + S + W) # To open new fileself.__thisFileMenu.add_command(label = "New", command = self.__newFile) # To open a already existing fileself.__thisFileMenu.add_command(label = "Open", command = self.__openFile) # To save current fileself.__thisFileMenu.add_command(label = "Save", command = self.__saveFile) # To create a line in the dialogself.__thisFileMenu.add_separator() # To terminateself.__thisFileMenu.add_command(label = "Exit", command = self.__quitApplication)self.__thisMenuBar.add_cascade(label = "File", menu = self.__thisFileMenu) # To give a feature of cutself.__thisEditMenu.add_command(label = "Cut", command = self.__cut) # To give a feature of copyself.__thisEditMenu.add_command(label = "Copy", command = self.__copy) # To give a feature of pasteself.__thisEditMenu.add_command(label = "Paste", command = self.__paste) # To give a feature of editingself.__thisMenuBar.add_cascade(label = "Edit", menu = self.__thisEditMenu) # To create a feature of description of the notepadself.__thisHelpMenu.add_command(label = "About Notepad", command = self.__showAbout)self.__thisMenuBar.add_cascade(label = "Help", menu = self.__thisHelpMenu) self.__root.config(menu = self.__thisMenuBar) self.__thisScrollBar.pack(side = RIGHT, fill = Y) # Scrollbar will adjust automatically# according to the contentself.__thisScrollBar.config(command = self.__thisTextArea.yview)self.__thisTextArea.config(yscrollcommand = self.__thisScrollBar.set)
With this code we will add the menu in the windows of our notepad and will add the things like copy, paste, save etc, to it. Adding The Functionality :
Python
def __quitApplication(self): self.__root.destroy() # exit() def __showAbout(self): showinfo("Notepad", "Mrinal Verma") def __openFile(self): self.__file = askopenfilename(defaultextension=".txt", filetypes=[("All Files","*.*"), ("Text Documents","*.txt")]) if self.__file == "": # no file to open self.__file = None else: # try to open the file # set the window title self.__root.title(os.path.basename(self.__file) + " - Notepad") self.__thisTextArea.delete(1.0,END) file = open(self.__file,"r") self.__thisTextArea.insert(1.0,file.read()) file.close() def __newFile(self): self.__root.title("Untitled - Notepad") self.__file = None self.__thisTextArea.delete(1.0,END) def __saveFile(self): if self.__file == None: #save as new file self.__file = asksaveasfilename(initialfile='Untitled.txt', defaultextension=".txt", filetypes=[("All Files","*.*"), ("Text Documents","*.txt")]) if self.__file == "": self.__file = None else: # try to save the file file = open(self.__file,"w") file.write(self.__thisTextArea.get(1.0,END)) file.close() # change the window title self.__root.title(os.path.basename(self.__file) + " - Notepad") else: file = open(self.__file,"w") file.write(self.__thisTextArea.get(1.0,END)) file.close() def __cut(self): self.__thisTextArea.event_generate("<<Cut>>") def __copy(self): self.__thisTextArea.event_generate("<<Copy>>") def __paste(self): self.__thisTextArea.event_generate("<<Paste>>")
In this we have added all the functionality that is required in the notepad, you can add other functionality too in this like the font size, font color, bold, underlined, etc.
Main Code After Merging All :
Python
import tkinterimport os from tkinter import *from tkinter.messagebox import *from tkinter.filedialog import * class Notepad: __root = Tk() # default window width and height __thisWidth = 300 __thisHeight = 300 __thisTextArea = Text(__root) __thisMenuBar = Menu(__root) __thisFileMenu = Menu(__thisMenuBar, tearoff=0) __thisEditMenu = Menu(__thisMenuBar, tearoff=0) __thisHelpMenu = Menu(__thisMenuBar, tearoff=0) # To add scrollbar __thisScrollBar = Scrollbar(__thisTextArea) __file = None def __init__(self,**kwargs): # Set icon try: self.__root.wm_iconbitmap("Notepad.ico") except: pass # Set window size (the default is 300x300) try: self.__thisWidth = kwargs['width'] except KeyError: pass try: self.__thisHeight = kwargs['height'] except KeyError: pass # Set the window text self.__root.title("Untitled - Notepad") # Center the window screenWidth = self.__root.winfo_screenwidth() screenHeight = self.__root.winfo_screenheight() # For left-align left = (screenWidth / 2) - (self.__thisWidth / 2) # For right-align top = (screenHeight / 2) - (self.__thisHeight /2) # For top and bottom self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth, self.__thisHeight, left, top)) # To make the textarea auto resizable self.__root.grid_rowconfigure(0, weight=1) self.__root.grid_columnconfigure(0, weight=1) # Add controls (widget) self.__thisTextArea.grid(sticky = N + E + S + W) # To open new file self.__thisFileMenu.add_command(label="New", command=self.__newFile) # To open a already existing file self.__thisFileMenu.add_command(label="Open", command=self.__openFile) # To save current file self.__thisFileMenu.add_command(label="Save", command=self.__saveFile) # To create a line in the dialog self.__thisFileMenu.add_separator() self.__thisFileMenu.add_command(label="Exit", command=self.__quitApplication) self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu) # To give a feature of cut self.__thisEditMenu.add_command(label="Cut", command=self.__cut) # to give a feature of copy self.__thisEditMenu.add_command(label="Copy", command=self.__copy) # To give a feature of paste self.__thisEditMenu.add_command(label="Paste", command=self.__paste) # To give a feature of editing self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu) # To create a feature of description of the notepad self.__thisHelpMenu.add_command(label="About Notepad", command=self.__showAbout) self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu) self.__root.config(menu=self.__thisMenuBar) self.__thisScrollBar.pack(side=RIGHT,fill=Y) # Scrollbar will adjust automatically according to the content self.__thisScrollBar.config(command=self.__thisTextArea.yview) self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set) def __quitApplication(self): self.__root.destroy() # exit() def __showAbout(self): showinfo("Notepad","Mrinal Verma") def __openFile(self): self.__file = askopenfilename(defaultextension=".txt", filetypes=[("All Files","*.*"), ("Text Documents","*.txt")]) if self.__file == "": # no file to open self.__file = None else: # Try to open the file # set the window title self.__root.title(os.path.basename(self.__file) + " - Notepad") self.__thisTextArea.delete(1.0,END) file = open(self.__file,"r") self.__thisTextArea.insert(1.0,file.read()) file.close() def __newFile(self): self.__root.title("Untitled - Notepad") self.__file = None self.__thisTextArea.delete(1.0,END) def __saveFile(self): if self.__file == None: # Save as new file self.__file = asksaveasfilename(initialfile='Untitled.txt', defaultextension=".txt", filetypes=[("All Files","*.*"), ("Text Documents","*.txt")]) if self.__file == "": self.__file = None else: # Try to save the file file = open(self.__file,"w") file.write(self.__thisTextArea.get(1.0,END)) file.close() # Change the window title self.__root.title(os.path.basename(self.__file) + " - Notepad") else: file = open(self.__file,"w") file.write(self.__thisTextArea.get(1.0,END)) file.close() def __cut(self): self.__thisTextArea.event_generate("<<Cut>>") def __copy(self): self.__thisTextArea.event_generate("<<Copy>>") def __paste(self): self.__thisTextArea.event_generate("<<Paste>>") def run(self): # Run main application self.__root.mainloop() # Run main applicationnotepad = Notepad(width=600,height=400)notepad.run()
To run this code, save it by the extension .py and then open cmd(command prompt) and move to the location of the file saved and then write the following
python "filename".py
and press enter and it will run. Or can be run directly by simply double clicking your .py extension file.
How to Create Notepad using Python? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to Create Notepad using Python? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 35:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=iyJ1_ODzNUk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
surinderdawra388
Python-projects
python-utility
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Implementing Web Scraping in Python with BeautifulSoup
10 Best Web Development Projects For Your Resume
OpenCV C++ Program for Face Detection
Simple Chat Room using Python
Twitter Sentiment Analysis using Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 290,
"s": 52,
"text": "Let’s see how to create a simple notepad in Python using Tkinter. This notepad GUI will consist of various menu like file and edit, using which all functionalities like saving the file, opening a file, editing, cut and paste can be done."
},
{
"code": null,
"e": 553,
"s": 290,
"text": "Now for creating this notepad, Python 3 and Tkinter should already be installed in your system. You can download suitable python package as per system requirement. After you have successfully installed python you need to install Tkinter (a Python’s GUI package)."
},
{
"code": null,
"e": 592,
"s": 553,
"text": "Use this command to install Tkinter : "
},
{
"code": null,
"e": 614,
"s": 592,
"text": "pip install python-tk"
},
{
"code": null,
"e": 634,
"s": 614,
"text": "Importing Tkinter :"
},
{
"code": null,
"e": 641,
"s": 634,
"text": "Python"
},
{
"code": "import tkinterimport osfrom tkinter import * # To get the space above for messagefrom tkinter.messagebox import * # To get the dialog box to open when requiredfrom tkinter.filedialog import *",
"e": 833,
"s": 641,
"text": null
},
{
"code": null,
"e": 1090,
"s": 833,
"text": "Note : messagebox is used to write the message in the white box called notepad and filedialog is used for the dialog box to appear when you are opening file from anywhere in your system or saving your file in a particular position or place. Adding Menu :"
},
{
"code": null,
"e": 1097,
"s": 1090,
"text": "Python"
},
{
"code": "# Add controls(widget) self.__thisTextArea.grid(sticky = N + E + S + W) # To open new fileself.__thisFileMenu.add_command(label = \"New\", command = self.__newFile) # To open a already existing fileself.__thisFileMenu.add_command(label = \"Open\", command = self.__openFile) # To save current fileself.__thisFileMenu.add_command(label = \"Save\", command = self.__saveFile) # To create a line in the dialogself.__thisFileMenu.add_separator() # To terminateself.__thisFileMenu.add_command(label = \"Exit\", command = self.__quitApplication)self.__thisMenuBar.add_cascade(label = \"File\", menu = self.__thisFileMenu) # To give a feature of cutself.__thisEditMenu.add_command(label = \"Cut\", command = self.__cut) # To give a feature of copyself.__thisEditMenu.add_command(label = \"Copy\", command = self.__copy) # To give a feature of pasteself.__thisEditMenu.add_command(label = \"Paste\", command = self.__paste) # To give a feature of editingself.__thisMenuBar.add_cascade(label = \"Edit\", menu = self.__thisEditMenu) # To create a feature of description of the notepadself.__thisHelpMenu.add_command(label = \"About Notepad\", command = self.__showAbout)self.__thisMenuBar.add_cascade(label = \"Help\", menu = self.__thisHelpMenu) self.__root.config(menu = self.__thisMenuBar) self.__thisScrollBar.pack(side = RIGHT, fill = Y) # Scrollbar will adjust automatically# according to the contentself.__thisScrollBar.config(command = self.__thisTextArea.yview)self.__thisTextArea.config(yscrollcommand = self.__thisScrollBar.set)",
"e": 2943,
"s": 1097,
"text": null
},
{
"code": null,
"e": 3097,
"s": 2943,
"text": "With this code we will add the menu in the windows of our notepad and will add the things like copy, paste, save etc, to it. Adding The Functionality :"
},
{
"code": null,
"e": 3104,
"s": 3097,
"text": "Python"
},
{
"code": "def __quitApplication(self): self.__root.destroy() # exit() def __showAbout(self): showinfo(\"Notepad\", \"Mrinal Verma\") def __openFile(self): self.__file = askopenfilename(defaultextension=\".txt\", filetypes=[(\"All Files\",\"*.*\"), (\"Text Documents\",\"*.txt\")]) if self.__file == \"\": # no file to open self.__file = None else: # try to open the file # set the window title self.__root.title(os.path.basename(self.__file) + \" - Notepad\") self.__thisTextArea.delete(1.0,END) file = open(self.__file,\"r\") self.__thisTextArea.insert(1.0,file.read()) file.close() def __newFile(self): self.__root.title(\"Untitled - Notepad\") self.__file = None self.__thisTextArea.delete(1.0,END) def __saveFile(self): if self.__file == None: #save as new file self.__file = asksaveasfilename(initialfile='Untitled.txt', defaultextension=\".txt\", filetypes=[(\"All Files\",\"*.*\"), (\"Text Documents\",\"*.txt\")]) if self.__file == \"\": self.__file = None else: # try to save the file file = open(self.__file,\"w\") file.write(self.__thisTextArea.get(1.0,END)) file.close() # change the window title self.__root.title(os.path.basename(self.__file) + \" - Notepad\") else: file = open(self.__file,\"w\") file.write(self.__thisTextArea.get(1.0,END)) file.close() def __cut(self): self.__thisTextArea.event_generate(\"<<Cut>>\") def __copy(self): self.__thisTextArea.event_generate(\"<<Copy>>\") def __paste(self): self.__thisTextArea.event_generate(\"<<Paste>>\")",
"e": 5009,
"s": 3104,
"text": null
},
{
"code": null,
"e": 5186,
"s": 5009,
"text": "In this we have added all the functionality that is required in the notepad, you can add other functionality too in this like the font size, font color, bold, underlined, etc. "
},
{
"code": null,
"e": 5216,
"s": 5186,
"text": "Main Code After Merging All :"
},
{
"code": null,
"e": 5223,
"s": 5216,
"text": "Python"
},
{
"code": "import tkinterimport os from tkinter import *from tkinter.messagebox import *from tkinter.filedialog import * class Notepad: __root = Tk() # default window width and height __thisWidth = 300 __thisHeight = 300 __thisTextArea = Text(__root) __thisMenuBar = Menu(__root) __thisFileMenu = Menu(__thisMenuBar, tearoff=0) __thisEditMenu = Menu(__thisMenuBar, tearoff=0) __thisHelpMenu = Menu(__thisMenuBar, tearoff=0) # To add scrollbar __thisScrollBar = Scrollbar(__thisTextArea) __file = None def __init__(self,**kwargs): # Set icon try: self.__root.wm_iconbitmap(\"Notepad.ico\") except: pass # Set window size (the default is 300x300) try: self.__thisWidth = kwargs['width'] except KeyError: pass try: self.__thisHeight = kwargs['height'] except KeyError: pass # Set the window text self.__root.title(\"Untitled - Notepad\") # Center the window screenWidth = self.__root.winfo_screenwidth() screenHeight = self.__root.winfo_screenheight() # For left-align left = (screenWidth / 2) - (self.__thisWidth / 2) # For right-align top = (screenHeight / 2) - (self.__thisHeight /2) # For top and bottom self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth, self.__thisHeight, left, top)) # To make the textarea auto resizable self.__root.grid_rowconfigure(0, weight=1) self.__root.grid_columnconfigure(0, weight=1) # Add controls (widget) self.__thisTextArea.grid(sticky = N + E + S + W) # To open new file self.__thisFileMenu.add_command(label=\"New\", command=self.__newFile) # To open a already existing file self.__thisFileMenu.add_command(label=\"Open\", command=self.__openFile) # To save current file self.__thisFileMenu.add_command(label=\"Save\", command=self.__saveFile) # To create a line in the dialog self.__thisFileMenu.add_separator() self.__thisFileMenu.add_command(label=\"Exit\", command=self.__quitApplication) self.__thisMenuBar.add_cascade(label=\"File\", menu=self.__thisFileMenu) # To give a feature of cut self.__thisEditMenu.add_command(label=\"Cut\", command=self.__cut) # to give a feature of copy self.__thisEditMenu.add_command(label=\"Copy\", command=self.__copy) # To give a feature of paste self.__thisEditMenu.add_command(label=\"Paste\", command=self.__paste) # To give a feature of editing self.__thisMenuBar.add_cascade(label=\"Edit\", menu=self.__thisEditMenu) # To create a feature of description of the notepad self.__thisHelpMenu.add_command(label=\"About Notepad\", command=self.__showAbout) self.__thisMenuBar.add_cascade(label=\"Help\", menu=self.__thisHelpMenu) self.__root.config(menu=self.__thisMenuBar) self.__thisScrollBar.pack(side=RIGHT,fill=Y) # Scrollbar will adjust automatically according to the content self.__thisScrollBar.config(command=self.__thisTextArea.yview) self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set) def __quitApplication(self): self.__root.destroy() # exit() def __showAbout(self): showinfo(\"Notepad\",\"Mrinal Verma\") def __openFile(self): self.__file = askopenfilename(defaultextension=\".txt\", filetypes=[(\"All Files\",\"*.*\"), (\"Text Documents\",\"*.txt\")]) if self.__file == \"\": # no file to open self.__file = None else: # Try to open the file # set the window title self.__root.title(os.path.basename(self.__file) + \" - Notepad\") self.__thisTextArea.delete(1.0,END) file = open(self.__file,\"r\") self.__thisTextArea.insert(1.0,file.read()) file.close() def __newFile(self): self.__root.title(\"Untitled - Notepad\") self.__file = None self.__thisTextArea.delete(1.0,END) def __saveFile(self): if self.__file == None: # Save as new file self.__file = asksaveasfilename(initialfile='Untitled.txt', defaultextension=\".txt\", filetypes=[(\"All Files\",\"*.*\"), (\"Text Documents\",\"*.txt\")]) if self.__file == \"\": self.__file = None else: # Try to save the file file = open(self.__file,\"w\") file.write(self.__thisTextArea.get(1.0,END)) file.close() # Change the window title self.__root.title(os.path.basename(self.__file) + \" - Notepad\") else: file = open(self.__file,\"w\") file.write(self.__thisTextArea.get(1.0,END)) file.close() def __cut(self): self.__thisTextArea.event_generate(\"<<Cut>>\") def __copy(self): self.__thisTextArea.event_generate(\"<<Copy>>\") def __paste(self): self.__thisTextArea.event_generate(\"<<Paste>>\") def run(self): # Run main application self.__root.mainloop() # Run main applicationnotepad = Notepad(width=600,height=400)notepad.run()",
"e": 11525,
"s": 5223,
"text": null
},
{
"code": null,
"e": 11679,
"s": 11525,
"text": "To run this code, save it by the extension .py and then open cmd(command prompt) and move to the location of the file saved and then write the following "
},
{
"code": null,
"e": 11701,
"s": 11679,
"text": "python \"filename\".py "
},
{
"code": null,
"e": 11809,
"s": 11701,
"text": "and press enter and it will run. Or can be run directly by simply double clicking your .py extension file. "
},
{
"code": null,
"e": 12698,
"s": 11809,
"text": "How to Create Notepad using Python? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to Create Notepad using Python? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 35:24•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=iyJ1_ODzNUk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 12717,
"s": 12700,
"text": "surinderdawra388"
},
{
"code": null,
"e": 12733,
"s": 12717,
"text": "Python-projects"
},
{
"code": null,
"e": 12748,
"s": 12733,
"text": "python-utility"
},
{
"code": null,
"e": 12756,
"s": 12748,
"text": "Project"
},
{
"code": null,
"e": 12763,
"s": 12756,
"text": "Python"
},
{
"code": null,
"e": 12861,
"s": 12763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12916,
"s": 12861,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 12965,
"s": 12916,
"text": "10 Best Web Development Projects For Your Resume"
},
{
"code": null,
"e": 13003,
"s": 12965,
"text": "OpenCV C++ Program for Face Detection"
},
{
"code": null,
"e": 13033,
"s": 13003,
"text": "Simple Chat Room using Python"
},
{
"code": null,
"e": 13073,
"s": 13033,
"text": "Twitter Sentiment Analysis using Python"
},
{
"code": null,
"e": 13101,
"s": 13073,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 13151,
"s": 13101,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 13173,
"s": 13151,
"text": "Python map() function"
},
{
"code": null,
"e": 13191,
"s": 13173,
"text": "Python Dictionary"
}
] |
Simplex Algorithm – Tabular Method
|
16 May, 2020
Simplex Algorithm is a well-known optimization technique in Linear Programming.The general form of an LPP (Linear Programming Problem) is
Example: Let’s consider the following maximization problem.Initial construction steps :
Build your matrix A. A will contain the coefficients of the constraints.
Matrix b will contain the amount of resources.
And matrix c will contain the coefficients of objective function or cost.
For the above problem –Matrix A – At Iteration 0
At Iteration 0
Simplex Algorithm
1. Start with the initial basis associated with identity matrix.
2. Calculate the relative profits.
For MAX problem-
If all the relative profits are less than or equal to 0, then the current basis is the optimal one. STOP.
Else continue to 3.
For MIN problem
If all the relative profits are greater than or equal to 0, then the current basis is the optimal one. STOP.
Else continue to 3.
3. Find the column corresponding to max relative profit. Say column k has the max
Rel. profit. So xk will enter the basis.
4. Perform a min ratio test to determine which variable will leave the basis.
Index of the min element i.e 'r' will determine the leaving variable.
The basic variable at index r, will leave the basis.
NOTE: Min ratio test is always performed on positive elements.
5. It's evident that the entered variable will not form an identity matrix, so
we will have to perform row operations to make it identity again.
Find the pivot element. The element at index (r, k) will be the pivot element and
row r will be the pivot row.
6. Divide the rth row by pivot to make it 1. And subtract c*(rth row) from other
rows to make them 0, where c is the coefficient required to make that row 0.
Table at Iteration 1
Table at iteration 1
Calculation of relative profits – (Cj – Zj), where Cj is the coefficient in Z and Zj is yi*CBC1 – Z1 = 1 – (1*0 + 2*0)C2 – Z2 = 1 – (1*0 + 1*0)C3 – Z3 = 0 – (0*0 + 1*0)C4 – Z4 = 0 – (1*0 + 0*0)
So Relative profits are- 1, 1, 0, 0 (As shown in the table)Clearly not all the relative profits are less or equal to 0. So will perform the next iteration.Determination of entering variable and leaving variable.Max relative profit 1 at index 1. So x1 will enter the basis.Min of (8, 5) is 5 which is at index 2. So x3 will leave the basis.
Since x1 entered perform required row operations to make an identity matrix.
Pivot index = [2, 4]Pivot element = 2
Divide the 2nd row by pivot element i.e 2 to make it 1.And subtract 1*R2 from R1 to make it 0See the next table.
Table At Iteration 2
Table at iteration 2
Relative profits = 0, 1/2, -1/2, 0Pivot index = [1, 5]Pivot element = 1/2Perform necessary row operations.See next table
Table At iteration 3
Following cases can occur while performing this algorithm.
Case 1 – Unbounded SolutionIf the column corresponding to the max relative profit contains only non-positive real numbers then we won’t be able to perform the min ratio test. Therefore it is reported as unbounded solution.
Case 2 – Alternate SolutionIf at any iteration any one of the non-basic variable’s relative profit comes out to be 0, then it contains alternate solutions. Many optimal solutions will exist.
Example 2The above example was an equality case where we were able to find the initial basis. Now we will perform simplex on an example where there is no identity forming.Convert the above problem into standard form i.ewhere x3, x4 and x5 are slack variables. These will form identity and hence the initial basis.Table at Iteration 0
Table at iteration 0
Now continuing as the previous example.Table at iteration 1
Table at iteration 1
Table at Iteration 2
Table at iteration 2
Table at iteration 3
Table at iteration 3
Code Implementation of Simplex Algorithm
import numpy as np from fractions import Fraction # so that numbers are not displayed in decimal. print("\n ****SiMplex Algorithm ****\n\n") # inputs # A will contain the coefficients of the constraintsA = np.array([[1, 1, 0, 1], [2, 1, 1, 0]])# b will contain the amount of resources b = np.array([8, 10]) # c will contain coefficients of objective function Z c = np.array([1, 1, 0, 0]) # B will contain the basic variables that make identity matrixcb = np.array(c[3])B = np.array([[3], [2]]) # cb contains their corresponding coefficients in Z cb = np.vstack((cb, c[2])) xb = np.transpose([b]) # combine matrices B and cbtable = np.hstack((B, cb)) table = np.hstack((table, xb)) # combine matrices B, cb and xb# finally combine matrix A to form the complete simplex tabletable = np.hstack((table, A)) # change the type of table to floattable = np.array(table, dtype ='float') # inputs end # if min problem, make this var 1MIN = 0 print("Table at itr = 0")print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4")for row in table: for el in row: # limit the denominator under 100 print(Fraction(str(el)).limit_denominator(100), end ='\t') print()print()print("Simplex Working....") # when optimality reached it will be made 1reached = 0 itr = 1unbounded = 0alternate = 0 while reached == 0: print("Iteration: ", end =' ') print(itr) print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4") for row in table: for el in row: print(Fraction(str(el)).limit_denominator(100), end ='\t') print() # calculate Relative profits-> cj - zj for non-basics i = 0 rel_prof = [] while i<len(A[0]): rel_prof.append(c[i] - np.sum(table[:, 1]*table[:, 3 + i])) i = i + 1 print("rel profit: ", end =" ") for profit in rel_prof: print(Fraction(str(profit)).limit_denominator(100), end =", ") print() i = 0 b_var = table[:, 0] # checking for alternate solution while i<len(A[0]): j = 0 present = 0 while j<len(b_var): if int(b_var[j]) == i: present = 1 break; j+= 1 if present == 0: if rel_prof[i] == 0: alternate = 1 print("Case of Alternate found") # print(i, end =" ") i+= 1 print() flag = 0 for profit in rel_prof: if profit>0: flag = 1 break # if all relative profits <= 0 if flag == 0: print("All profits are <= 0, optimality reached") reached = 1 break # kth var will enter the basis k = rel_prof.index(max(rel_prof)) min = 99999 i = 0; r = -1 # min ratio test (only positive values) while i<len(table): if (table[:, 2][i]>0 and table[:, 3 + k][i]>0): val = table[:, 2][i]/table[:, 3 + k][i] if val<min: min = val r = i # leaving variable i+= 1 # if no min ratio test was performed if r ==-1: unbounded = 1 print("Case of Unbounded") break print("pivot element index:", end =' ') print(np.array([r, 3 + k])) pivot = table[r][3 + k] print("pivot element: ", end =" ") print(Fraction(pivot).limit_denominator(100)) # perform row operations # divide the pivot row with the pivot element table[r, 2:len(table[0])] = table[ r, 2:len(table[0])] / pivot # do row operation on other rows i = 0 while i<len(table): if i != r: table[i, 2:len(table[0])] = table[i, 2:len(table[0])] - table[i][3 + k] * table[r, 2:len(table[0])] i += 1 # assign the new basic variable table[r][0] = k table[r][1] = c[k] print() print() itr+= 1 print() print("***************************************************************")if unbounded == 1: print("UNBOUNDED LPP") exit()if alternate == 1: print("ALTERNATE Solution") print("optimal table:")print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4")for row in table: for el in row: print(Fraction(str(el)).limit_denominator(100), end ='\t') print()print()print("value of Z at optimality: ", end =" ") basis = []i = 0sum = 0while i<len(table): sum += c[int(table[i][0])]*table[i][2] temp = "x"+str(int(table[i][0])+1) basis.append(temp) i+= 1# if MIN problem make z negativeif MIN == 1: print(-Fraction(str(sum)).limit_denominator(100))else: print(Fraction(str(sum)).limit_denominator(100))print("Final Basis: ", end =" ")print(basis) print("Simplex Finished...")print()
For the above just plug in the required values and you will get a detailed step by step solution of your LPP by the simplex algorithm.
choudharyshreyansh27
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 May, 2020"
},
{
"code": null,
"e": 192,
"s": 54,
"text": "Simplex Algorithm is a well-known optimization technique in Linear Programming.The general form of an LPP (Linear Programming Problem) is"
},
{
"code": null,
"e": 280,
"s": 192,
"text": "Example: Let’s consider the following maximization problem.Initial construction steps :"
},
{
"code": null,
"e": 353,
"s": 280,
"text": "Build your matrix A. A will contain the coefficients of the constraints."
},
{
"code": null,
"e": 400,
"s": 353,
"text": "Matrix b will contain the amount of resources."
},
{
"code": null,
"e": 474,
"s": 400,
"text": "And matrix c will contain the coefficients of objective function or cost."
},
{
"code": null,
"e": 523,
"s": 474,
"text": "For the above problem –Matrix A – At Iteration 0"
},
{
"code": null,
"e": 538,
"s": 523,
"text": "At Iteration 0"
},
{
"code": null,
"e": 1762,
"s": 538,
"text": "Simplex Algorithm\n1. Start with the initial basis associated with identity matrix.\n2. Calculate the relative profits. \n\nFor MAX problem-\nIf all the relative profits are less than or equal to 0, then the current basis is the optimal one. STOP.\nElse continue to 3.\n\nFor MIN problem \nIf all the relative profits are greater than or equal to 0, then the current basis is the optimal one. STOP.\nElse continue to 3.\n\n3. Find the column corresponding to max relative profit. Say column k has the max \nRel. profit. So xk will enter the basis.\n\n4. Perform a min ratio test to determine which variable will leave the basis.\n \nIndex of the min element i.e 'r' will determine the leaving variable.\nThe basic variable at index r, will leave the basis. \nNOTE: Min ratio test is always performed on positive elements.\n\n5. It's evident that the entered variable will not form an identity matrix, so \nwe will have to perform row operations to make it identity again.\nFind the pivot element. The element at index (r, k) will be the pivot element and \nrow r will be the pivot row. \n\n6. Divide the rth row by pivot to make it 1. And subtract c*(rth row) from other \nrows to make them 0, where c is the coefficient required to make that row 0.\n"
},
{
"code": null,
"e": 1783,
"s": 1762,
"text": "Table at Iteration 1"
},
{
"code": null,
"e": 1804,
"s": 1783,
"text": "Table at iteration 1"
},
{
"code": null,
"e": 1998,
"s": 1804,
"text": "Calculation of relative profits – (Cj – Zj), where Cj is the coefficient in Z and Zj is yi*CBC1 – Z1 = 1 – (1*0 + 2*0)C2 – Z2 = 1 – (1*0 + 1*0)C3 – Z3 = 0 – (0*0 + 1*0)C4 – Z4 = 0 – (1*0 + 0*0)"
},
{
"code": null,
"e": 2338,
"s": 1998,
"text": "So Relative profits are- 1, 1, 0, 0 (As shown in the table)Clearly not all the relative profits are less or equal to 0. So will perform the next iteration.Determination of entering variable and leaving variable.Max relative profit 1 at index 1. So x1 will enter the basis.Min of (8, 5) is 5 which is at index 2. So x3 will leave the basis."
},
{
"code": null,
"e": 2415,
"s": 2338,
"text": "Since x1 entered perform required row operations to make an identity matrix."
},
{
"code": null,
"e": 2453,
"s": 2415,
"text": "Pivot index = [2, 4]Pivot element = 2"
},
{
"code": null,
"e": 2566,
"s": 2453,
"text": "Divide the 2nd row by pivot element i.e 2 to make it 1.And subtract 1*R2 from R1 to make it 0See the next table."
},
{
"code": null,
"e": 2587,
"s": 2566,
"text": "Table At Iteration 2"
},
{
"code": null,
"e": 2608,
"s": 2587,
"text": "Table at iteration 2"
},
{
"code": null,
"e": 2729,
"s": 2608,
"text": "Relative profits = 0, 1/2, -1/2, 0Pivot index = [1, 5]Pivot element = 1/2Perform necessary row operations.See next table"
},
{
"code": null,
"e": 2750,
"s": 2729,
"text": "Table At iteration 3"
},
{
"code": null,
"e": 2809,
"s": 2750,
"text": "Following cases can occur while performing this algorithm."
},
{
"code": null,
"e": 3032,
"s": 2809,
"text": "Case 1 – Unbounded SolutionIf the column corresponding to the max relative profit contains only non-positive real numbers then we won’t be able to perform the min ratio test. Therefore it is reported as unbounded solution."
},
{
"code": null,
"e": 3223,
"s": 3032,
"text": "Case 2 – Alternate SolutionIf at any iteration any one of the non-basic variable’s relative profit comes out to be 0, then it contains alternate solutions. Many optimal solutions will exist."
},
{
"code": null,
"e": 3557,
"s": 3223,
"text": "Example 2The above example was an equality case where we were able to find the initial basis. Now we will perform simplex on an example where there is no identity forming.Convert the above problem into standard form i.ewhere x3, x4 and x5 are slack variables. These will form identity and hence the initial basis.Table at Iteration 0"
},
{
"code": null,
"e": 3578,
"s": 3557,
"text": "Table at iteration 0"
},
{
"code": null,
"e": 3638,
"s": 3578,
"text": "Now continuing as the previous example.Table at iteration 1"
},
{
"code": null,
"e": 3659,
"s": 3638,
"text": "Table at iteration 1"
},
{
"code": null,
"e": 3680,
"s": 3659,
"text": "Table at Iteration 2"
},
{
"code": null,
"e": 3701,
"s": 3680,
"text": "Table at iteration 2"
},
{
"code": null,
"e": 3722,
"s": 3701,
"text": "Table at iteration 3"
},
{
"code": null,
"e": 3743,
"s": 3722,
"text": "Table at iteration 3"
},
{
"code": null,
"e": 3784,
"s": 3743,
"text": "Code Implementation of Simplex Algorithm"
},
{
"code": "import numpy as np from fractions import Fraction # so that numbers are not displayed in decimal. print(\"\\n ****SiMplex Algorithm ****\\n\\n\") # inputs # A will contain the coefficients of the constraintsA = np.array([[1, 1, 0, 1], [2, 1, 1, 0]])# b will contain the amount of resources b = np.array([8, 10]) # c will contain coefficients of objective function Z c = np.array([1, 1, 0, 0]) # B will contain the basic variables that make identity matrixcb = np.array(c[3])B = np.array([[3], [2]]) # cb contains their corresponding coefficients in Z cb = np.vstack((cb, c[2])) xb = np.transpose([b]) # combine matrices B and cbtable = np.hstack((B, cb)) table = np.hstack((table, xb)) # combine matrices B, cb and xb# finally combine matrix A to form the complete simplex tabletable = np.hstack((table, A)) # change the type of table to floattable = np.array(table, dtype ='float') # inputs end # if min problem, make this var 1MIN = 0 print(\"Table at itr = 0\")print(\"B \\tCB \\tXB \\ty1 \\ty2 \\ty3 \\ty4\")for row in table: for el in row: # limit the denominator under 100 print(Fraction(str(el)).limit_denominator(100), end ='\\t') print()print()print(\"Simplex Working....\") # when optimality reached it will be made 1reached = 0 itr = 1unbounded = 0alternate = 0 while reached == 0: print(\"Iteration: \", end =' ') print(itr) print(\"B \\tCB \\tXB \\ty1 \\ty2 \\ty3 \\ty4\") for row in table: for el in row: print(Fraction(str(el)).limit_denominator(100), end ='\\t') print() # calculate Relative profits-> cj - zj for non-basics i = 0 rel_prof = [] while i<len(A[0]): rel_prof.append(c[i] - np.sum(table[:, 1]*table[:, 3 + i])) i = i + 1 print(\"rel profit: \", end =\" \") for profit in rel_prof: print(Fraction(str(profit)).limit_denominator(100), end =\", \") print() i = 0 b_var = table[:, 0] # checking for alternate solution while i<len(A[0]): j = 0 present = 0 while j<len(b_var): if int(b_var[j]) == i: present = 1 break; j+= 1 if present == 0: if rel_prof[i] == 0: alternate = 1 print(\"Case of Alternate found\") # print(i, end =\" \") i+= 1 print() flag = 0 for profit in rel_prof: if profit>0: flag = 1 break # if all relative profits <= 0 if flag == 0: print(\"All profits are <= 0, optimality reached\") reached = 1 break # kth var will enter the basis k = rel_prof.index(max(rel_prof)) min = 99999 i = 0; r = -1 # min ratio test (only positive values) while i<len(table): if (table[:, 2][i]>0 and table[:, 3 + k][i]>0): val = table[:, 2][i]/table[:, 3 + k][i] if val<min: min = val r = i # leaving variable i+= 1 # if no min ratio test was performed if r ==-1: unbounded = 1 print(\"Case of Unbounded\") break print(\"pivot element index:\", end =' ') print(np.array([r, 3 + k])) pivot = table[r][3 + k] print(\"pivot element: \", end =\" \") print(Fraction(pivot).limit_denominator(100)) # perform row operations # divide the pivot row with the pivot element table[r, 2:len(table[0])] = table[ r, 2:len(table[0])] / pivot # do row operation on other rows i = 0 while i<len(table): if i != r: table[i, 2:len(table[0])] = table[i, 2:len(table[0])] - table[i][3 + k] * table[r, 2:len(table[0])] i += 1 # assign the new basic variable table[r][0] = k table[r][1] = c[k] print() print() itr+= 1 print() print(\"***************************************************************\")if unbounded == 1: print(\"UNBOUNDED LPP\") exit()if alternate == 1: print(\"ALTERNATE Solution\") print(\"optimal table:\")print(\"B \\tCB \\tXB \\ty1 \\ty2 \\ty3 \\ty4\")for row in table: for el in row: print(Fraction(str(el)).limit_denominator(100), end ='\\t') print()print()print(\"value of Z at optimality: \", end =\" \") basis = []i = 0sum = 0while i<len(table): sum += c[int(table[i][0])]*table[i][2] temp = \"x\"+str(int(table[i][0])+1) basis.append(temp) i+= 1# if MIN problem make z negativeif MIN == 1: print(-Fraction(str(sum)).limit_denominator(100))else: print(Fraction(str(sum)).limit_denominator(100))print(\"Final Basis: \", end =\" \")print(basis) print(\"Simplex Finished...\")print()",
"e": 8520,
"s": 3784,
"text": null
},
{
"code": null,
"e": 8655,
"s": 8520,
"text": "For the above just plug in the required values and you will get a detailed step by step solution of your LPP by the simplex algorithm."
},
{
"code": null,
"e": 8676,
"s": 8655,
"text": "choudharyshreyansh27"
},
{
"code": null,
"e": 8683,
"s": 8676,
"text": "Python"
},
{
"code": null,
"e": 8781,
"s": 8683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8813,
"s": 8781,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8840,
"s": 8813,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8871,
"s": 8840,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8892,
"s": 8871,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8948,
"s": 8892,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 8971,
"s": 8948,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 9013,
"s": 8971,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 9055,
"s": 9013,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 9094,
"s": 9055,
"text": "Python | datetime.timedelta() function"
}
] |
Command-Line Option and Argument Parsing using argparse in Python
|
19 Feb, 2020
Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module.
The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)Parameters:prog– name of the program (default=sys.argv[0])usage– string describes the program usage(default: generated from arguments added to the parser)description– text to display before the argument help(default: none)epilog– text to display after the argument help (default: none)parents– list of ArgumentParser objects whose arguments should also be includedformatter_class– class for customizing the help outputprefix_chars– set of characters that prefix optional arguments (default: ‘-‘)fromfile_prefix_chars– set of characters that prefix files from which additional arguments should be read (default: None)argument_default– global default value for arguments (default: None)conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)add_help– Add a -h/–help option to the parser (default: True)allow_abbrev– Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)Adding Arguments: Next step is to fill the ArgumentParser with the information about the arguments of the program. This implies a call to the add_argument() method. These information tell ArgumentParser how to take arguments from the command-line and turn them into objects.Syntax: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])Parameters:name or flags– either a name or list of option stringaction– basic type of action to be taken when this argument is encountered at the command linenargs– number of command-line arguments that should be consumedconst– constant value required by some action and nargs selectionsdefault– value produced if the arguments are absent from the command linetype– type to which the command line arguments should be converted.choices – A container of the allowable values for the argumentrequired – Whether or not the command-line option may be omitted (optionals only)help– brief description of what the argument doesmetavar – A name for the argument in usage messagesdest – The name of the attribute to be added to the object returned by parse_args()Parsing Arguments: The information gathered in the step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result.Syntax: ArgumentParser.parse_args(args=None, namespace=None)Parameter:args – List of strings to parse. The default is taken from sys.argv.namespace – An object to take the attributes. The default is a new empty Namespace objectIn most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:Namespace(accumulate=, integers=[ 2, 8, -7, 41 ])
Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)Parameters:prog– name of the program (default=sys.argv[0])usage– string describes the program usage(default: generated from arguments added to the parser)description– text to display before the argument help(default: none)epilog– text to display after the argument help (default: none)parents– list of ArgumentParser objects whose arguments should also be includedformatter_class– class for customizing the help outputprefix_chars– set of characters that prefix optional arguments (default: ‘-‘)fromfile_prefix_chars– set of characters that prefix files from which additional arguments should be read (default: None)argument_default– global default value for arguments (default: None)conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)add_help– Add a -h/–help option to the parser (default: True)allow_abbrev– Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)
Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)
Parameters:
prog– name of the program (default=sys.argv[0])
usage– string describes the program usage(default: generated from arguments added to the parser)
description– text to display before the argument help(default: none)
epilog– text to display after the argument help (default: none)
parents– list of ArgumentParser objects whose arguments should also be included
formatter_class– class for customizing the help output
prefix_chars– set of characters that prefix optional arguments (default: ‘-‘)
fromfile_prefix_chars– set of characters that prefix files from which additional arguments should be read (default: None)
argument_default– global default value for arguments (default: None)
conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)
add_help– Add a -h/–help option to the parser (default: True)
allow_abbrev– Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)
Adding Arguments: Next step is to fill the ArgumentParser with the information about the arguments of the program. This implies a call to the add_argument() method. These information tell ArgumentParser how to take arguments from the command-line and turn them into objects.Syntax: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])Parameters:name or flags– either a name or list of option stringaction– basic type of action to be taken when this argument is encountered at the command linenargs– number of command-line arguments that should be consumedconst– constant value required by some action and nargs selectionsdefault– value produced if the arguments are absent from the command linetype– type to which the command line arguments should be converted.choices – A container of the allowable values for the argumentrequired – Whether or not the command-line option may be omitted (optionals only)help– brief description of what the argument doesmetavar – A name for the argument in usage messagesdest – The name of the attribute to be added to the object returned by parse_args()
Syntax: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
Parameters:
name or flags– either a name or list of option string
action– basic type of action to be taken when this argument is encountered at the command line
nargs– number of command-line arguments that should be consumed
const– constant value required by some action and nargs selections
default– value produced if the arguments are absent from the command line
type– type to which the command line arguments should be converted.
choices – A container of the allowable values for the argument
required – Whether or not the command-line option may be omitted (optionals only)
help– brief description of what the argument does
metavar – A name for the argument in usage messages
dest – The name of the attribute to be added to the object returned by parse_args()
Parsing Arguments: The information gathered in the step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result.Syntax: ArgumentParser.parse_args(args=None, namespace=None)Parameter:args – List of strings to parse. The default is taken from sys.argv.namespace – An object to take the attributes. The default is a new empty Namespace objectIn most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:Namespace(accumulate=, integers=[ 2, 8, -7, 41 ])
Syntax: ArgumentParser.parse_args(args=None, namespace=None)
Parameter:
args – List of strings to parse. The default is taken from sys.argv.
namespace – An object to take the attributes. The default is a new empty Namespace object
In most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:
Namespace(accumulate=, integers=[ 2, 8, -7, 41 ])
These were the root concepts you need to be familiar with to deal with argparse. The following are some examples to support this application.
Example 1: To find the sum of command-line arguments using argparse
import argparse # Initialize the Parserparser = argparse.ArgumentParser(description ='Process some integers.') # Adding Argumentsparser.add_argument('integers', metavar ='N', type = int, nargs ='+', help ='an integer for the accumulator') parser.add_argument(dest ='accumulate', action ='store_const', const = sum, help ='sum the integers') args = parser.parse_args()print(args.accumulate(args.integers))
Output:
Example 2: Program to arrange the integer inputs in ascending order
import argparse # Initializing Parserparser = argparse.ArgumentParser(description ='sort some integers.') # Adding Argumentparser.add_argument('integers', metavar ='N', type = int, nargs ='+', help ='an integer for the accumulator') parser.add_argument(dest ='accumulate', action ='store_const', const = sorted, help ='arranges the integers in ascending order') args = parser.parse_args()print(args.accumulate(args.integers))
Output:
Example 3: To find the average of the entered command line numerical arguments
import argparse # Initializing Parserparser = argparse.ArgumentParser(description ='sort some integers.') # Adding Argumentparser.add_argument('integers', metavar ='N', type = float, nargs ='+', help ='an integer for the accumulator') parser.add_argument('sum', action ='store_const', const = sum) parser.add_argument('len', action ='store_const', const = len) args = parser.parse_args()add = args.sum(args.integers)length = args.len(args.integers)average = add / lengthprint(average)
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 347,
"s": 54,
"text": "Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module."
},
{
"code": null,
"e": 643,
"s": 347,
"text": "The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments."
},
{
"code": null,
"e": 4034,
"s": 643,
"text": "Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)Parameters:prog– name of the program (default=sys.argv[0])usage– string describes the program usage(default: generated from arguments added to the parser)description– text to display before the argument help(default: none)epilog– text to display after the argument help (default: none)parents– list of ArgumentParser objects whose arguments should also be includedformatter_class– class for customizing the help outputprefix_chars– set of characters that prefix optional arguments (default: ‘-‘)fromfile_prefix_chars– set of characters that prefix files from which additional arguments should be read (default: None)argument_default– global default value for arguments (default: None)conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)add_help– Add a -h/–help option to the parser (default: True)allow_abbrev– Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)Adding Arguments: Next step is to fill the ArgumentParser with the information about the arguments of the program. This implies a call to the add_argument() method. These information tell ArgumentParser how to take arguments from the command-line and turn them into objects.Syntax: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])Parameters:name or flags– either a name or list of option stringaction– basic type of action to be taken when this argument is encountered at the command linenargs– number of command-line arguments that should be consumedconst– constant value required by some action and nargs selectionsdefault– value produced if the arguments are absent from the command linetype– type to which the command line arguments should be converted.choices – A container of the allowable values for the argumentrequired – Whether or not the command-line option may be omitted (optionals only)help– brief description of what the argument doesmetavar – A name for the argument in usage messagesdest – The name of the attribute to be added to the object returned by parse_args()Parsing Arguments: The information gathered in the step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result.Syntax: ArgumentParser.parse_args(args=None, namespace=None)Parameter:args – List of strings to parse. The default is taken from sys.argv.namespace – An object to take the attributes. The default is a new empty Namespace objectIn most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:Namespace(accumulate=, integers=[ 2, 8, -7, 41 ])"
},
{
"code": null,
"e": 5508,
"s": 4034,
"text": "Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)Parameters:prog– name of the program (default=sys.argv[0])usage– string describes the program usage(default: generated from arguments added to the parser)description– text to display before the argument help(default: none)epilog– text to display after the argument help (default: none)parents– list of ArgumentParser objects whose arguments should also be includedformatter_class– class for customizing the help outputprefix_chars– set of characters that prefix optional arguments (default: ‘-‘)fromfile_prefix_chars– set of characters that prefix files from which additional arguments should be read (default: None)argument_default– global default value for arguments (default: None)conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)add_help– Add a -h/–help option to the parser (default: True)allow_abbrev– Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)"
},
{
"code": null,
"e": 5781,
"s": 5508,
"text": "Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)"
},
{
"code": null,
"e": 5793,
"s": 5781,
"text": "Parameters:"
},
{
"code": null,
"e": 5841,
"s": 5793,
"text": "prog– name of the program (default=sys.argv[0])"
},
{
"code": null,
"e": 5938,
"s": 5841,
"text": "usage– string describes the program usage(default: generated from arguments added to the parser)"
},
{
"code": null,
"e": 6007,
"s": 5938,
"text": "description– text to display before the argument help(default: none)"
},
{
"code": null,
"e": 6071,
"s": 6007,
"text": "epilog– text to display after the argument help (default: none)"
},
{
"code": null,
"e": 6151,
"s": 6071,
"text": "parents– list of ArgumentParser objects whose arguments should also be included"
},
{
"code": null,
"e": 6206,
"s": 6151,
"text": "formatter_class– class for customizing the help output"
},
{
"code": null,
"e": 6284,
"s": 6206,
"text": "prefix_chars– set of characters that prefix optional arguments (default: ‘-‘)"
},
{
"code": null,
"e": 6406,
"s": 6284,
"text": "fromfile_prefix_chars– set of characters that prefix files from which additional arguments should be read (default: None)"
},
{
"code": null,
"e": 6475,
"s": 6406,
"text": "argument_default– global default value for arguments (default: None)"
},
{
"code": null,
"e": 6560,
"s": 6475,
"text": "conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)"
},
{
"code": null,
"e": 6622,
"s": 6560,
"text": "add_help– Add a -h/–help option to the parser (default: True)"
},
{
"code": null,
"e": 6726,
"s": 6622,
"text": "allow_abbrev– Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)"
},
{
"code": null,
"e": 7904,
"s": 6726,
"text": "Adding Arguments: Next step is to fill the ArgumentParser with the information about the arguments of the program. This implies a call to the add_argument() method. These information tell ArgumentParser how to take arguments from the command-line and turn them into objects.Syntax: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])Parameters:name or flags– either a name or list of option stringaction– basic type of action to be taken when this argument is encountered at the command linenargs– number of command-line arguments that should be consumedconst– constant value required by some action and nargs selectionsdefault– value produced if the arguments are absent from the command linetype– type to which the command line arguments should be converted.choices – A container of the allowable values for the argumentrequired – Whether or not the command-line option may be omitted (optionals only)help– brief description of what the argument doesmetavar – A name for the argument in usage messagesdest – The name of the attribute to be added to the object returned by parse_args()"
},
{
"code": null,
"e": 8055,
"s": 7904,
"text": "Syntax: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])"
},
{
"code": null,
"e": 8067,
"s": 8055,
"text": "Parameters:"
},
{
"code": null,
"e": 8121,
"s": 8067,
"text": "name or flags– either a name or list of option string"
},
{
"code": null,
"e": 8216,
"s": 8121,
"text": "action– basic type of action to be taken when this argument is encountered at the command line"
},
{
"code": null,
"e": 8280,
"s": 8216,
"text": "nargs– number of command-line arguments that should be consumed"
},
{
"code": null,
"e": 8347,
"s": 8280,
"text": "const– constant value required by some action and nargs selections"
},
{
"code": null,
"e": 8421,
"s": 8347,
"text": "default– value produced if the arguments are absent from the command line"
},
{
"code": null,
"e": 8489,
"s": 8421,
"text": "type– type to which the command line arguments should be converted."
},
{
"code": null,
"e": 8552,
"s": 8489,
"text": "choices – A container of the allowable values for the argument"
},
{
"code": null,
"e": 8634,
"s": 8552,
"text": "required – Whether or not the command-line option may be omitted (optionals only)"
},
{
"code": null,
"e": 8684,
"s": 8634,
"text": "help– brief description of what the argument does"
},
{
"code": null,
"e": 8736,
"s": 8684,
"text": "metavar – A name for the argument in usage messages"
},
{
"code": null,
"e": 8820,
"s": 8736,
"text": "dest – The name of the attribute to be added to the object returned by parse_args()"
},
{
"code": null,
"e": 9561,
"s": 8820,
"text": "Parsing Arguments: The information gathered in the step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result.Syntax: ArgumentParser.parse_args(args=None, namespace=None)Parameter:args – List of strings to parse. The default is taken from sys.argv.namespace – An object to take the attributes. The default is a new empty Namespace objectIn most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:Namespace(accumulate=, integers=[ 2, 8, -7, 41 ])"
},
{
"code": null,
"e": 9622,
"s": 9561,
"text": "Syntax: ArgumentParser.parse_args(args=None, namespace=None)"
},
{
"code": null,
"e": 9633,
"s": 9622,
"text": "Parameter:"
},
{
"code": null,
"e": 9702,
"s": 9633,
"text": "args – List of strings to parse. The default is taken from sys.argv."
},
{
"code": null,
"e": 9792,
"s": 9702,
"text": "namespace – An object to take the attributes. The default is a new empty Namespace object"
},
{
"code": null,
"e": 9909,
"s": 9792,
"text": "In most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:"
},
{
"code": null,
"e": 9959,
"s": 9909,
"text": "Namespace(accumulate=, integers=[ 2, 8, -7, 41 ])"
},
{
"code": null,
"e": 10101,
"s": 9959,
"text": "These were the root concepts you need to be familiar with to deal with argparse. The following are some examples to support this application."
},
{
"code": null,
"e": 10169,
"s": 10101,
"text": "Example 1: To find the sum of command-line arguments using argparse"
},
{
"code": "import argparse # Initialize the Parserparser = argparse.ArgumentParser(description ='Process some integers.') # Adding Argumentsparser.add_argument('integers', metavar ='N', type = int, nargs ='+', help ='an integer for the accumulator') parser.add_argument(dest ='accumulate', action ='store_const', const = sum, help ='sum the integers') args = parser.parse_args()print(args.accumulate(args.integers))",
"e": 10678,
"s": 10169,
"text": null
},
{
"code": null,
"e": 10686,
"s": 10678,
"text": "Output:"
},
{
"code": null,
"e": 10754,
"s": 10686,
"text": "Example 2: Program to arrange the integer inputs in ascending order"
},
{
"code": "import argparse # Initializing Parserparser = argparse.ArgumentParser(description ='sort some integers.') # Adding Argumentparser.add_argument('integers', metavar ='N', type = int, nargs ='+', help ='an integer for the accumulator') parser.add_argument(dest ='accumulate', action ='store_const', const = sorted, help ='arranges the integers in ascending order') args = parser.parse_args()print(args.accumulate(args.integers))",
"e": 11319,
"s": 10754,
"text": null
},
{
"code": null,
"e": 11327,
"s": 11319,
"text": "Output:"
},
{
"code": null,
"e": 11406,
"s": 11327,
"text": "Example 3: To find the average of the entered command line numerical arguments"
},
{
"code": "import argparse # Initializing Parserparser = argparse.ArgumentParser(description ='sort some integers.') # Adding Argumentparser.add_argument('integers', metavar ='N', type = float, nargs ='+', help ='an integer for the accumulator') parser.add_argument('sum', action ='store_const', const = sum) parser.add_argument('len', action ='store_const', const = len) args = parser.parse_args()add = args.sum(args.integers)length = args.len(args.integers)average = add / lengthprint(average)",
"e": 12050,
"s": 11406,
"text": null
},
{
"code": null,
"e": 12058,
"s": 12050,
"text": "Output:"
},
{
"code": null,
"e": 12073,
"s": 12058,
"text": "python-modules"
},
{
"code": null,
"e": 12080,
"s": 12073,
"text": "Python"
}
] |
Why would you use flexbox instead of floats?
|
24 May, 2021
Before we dive into flexbox vs float, we will understand about flexbox and float.
Flexbox is a css3 layout model that provides an easy and clean way to arrange items with a container.
These are the following reasons to use flexbox over floats.
Positioning child elements becomes easier with flexbox.Flexbox is responsive and mobile-friendly.Flex container’s margins do not collapse with the margins of its content.We can easily change the order of elements on our webpage without even making changes in HTML.
Positioning child elements becomes easier with flexbox.
Flexbox is responsive and mobile-friendly.
Flex container’s margins do not collapse with the margins of its content.
We can easily change the order of elements on our webpage without even making changes in HTML.
These are the important concept of the flexbox model.
Flexbox is a direction-agnostic layout model.Flexbox has the ability to alter an item’s width and height to best fit in its container’s available free space.Flex value applies for the display property of a container which is called flex container as well as the container’s contents or flex child.Flexbox has a list of important properties that are used to make a flexible container. They are flex-direction, flex-wrap, flex-flow, justify-content, align-items, align-content.
Flexbox is a direction-agnostic layout model.
Flexbox has the ability to alter an item’s width and height to best fit in its container’s available free space.
Flex value applies for the display property of a container which is called flex container as well as the container’s contents or flex child.
Flexbox has a list of important properties that are used to make a flexible container. They are flex-direction, flex-wrap, flex-flow, justify-content, align-items, align-content.
Example: In this example, we will explain the advantages of flex over the float. by explaining flex properties.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="main.css" /> <style> .flex-container { height: 350px; width: 600px; border: 3px solid black; } .flex-items{ margin: 5px; } #one { height: 100px; width: 100px; border: 5px solid green; } #two{ height: 100px; width: 100px; border: 5px solid green; } #three{ height: 100px; width: 100px; border: 5px solid green; } </style></head><body> <div class="flex-container"> <div id="one" class="flex-items"> </div> <div id="two" class="flex-items"> </div> <div id="three" class="flex-items"> </div> </div></body></html>
Output: In this example, we applied display: flex property to the larger container to make it flexible.
In the above code, we can change the CSS code for the class .flex-container as given below.
Code snippet:
CSS
.flex-container { display: flex; height: 350px; width: 600px; border: 3px solid black; }
Output: So we can see that after applying to flex property, it automatically arranges the child container in the horizontal direction which is its default value. We can change it as per the application’s need to arrange the child items.
CSS flex-direction Property: The flex-direction property is a sub-property of the flexible box layout module. It established the main axis of the flexible item.
Flex-direction has some values.
flex-direction:column
flex-direction:row
flex-direction:column-reverse
flex-direction:row-reverse
Code snippet: Just change the class properties of the class flex-container in the CSS part of the above HTML code. Similar changes are made in other snippets as well.
CSS
.flex-container { display: flex; flex-direction:column; height: 400px; width: 600px; border: 3px solid black; }
Output:
Code snippet:
CSS
.flex-container { display: flex; flex-direction:row; height: 400px; width: 600px; border: 3px solid black; }
Output:
Code snippet:
CSS
.flex-container { display: flex; flex-direction:column-reverse; height: 400px; width: 600px; border: 3px solid black; }
Output:
Code snippet:
CSS
.flex-container { display: flex; flex-direction:row-reverse; height: 400px; width: 600px; border: 3px solid black; }
Output:
CSS Flex-wrap property: Flex-wrap property is used for wrapping all the elements according to their parent container, from the above example if we reduce the width of the parent container without applying the wrap property, then it will squeeze the size of the child elements in order to maintain the flexibility of the container.
CSS Flex-flow property: Flex-flow property is not a single property. In this flex-direction and flex-wrap are combined, or we can say that it is a shorthand property for flex-direction and flex-wrap property.
CSS Justify-content property: Justify-content property is used for positioning alignment of the child elements.
Justify-content: start: Arrange all the child element from the start of the container
Code snippet: Only change the flex-container class of the CSS part in the first HTML code.
CSS
.flex-container { display: flex; justify-content:start; height: 400px; width: 600px; border: 3px solid black; }
Output:
Justify-content: center: Place all the child element around the center of the container
Code snippet:
CSS
.flex-container { display: flex; justify-content:center; height: 400px; width: 600px; border: 3px solid black; }
Output:
Justify-content: space-around: Put spaces between the child elements and spread them throughout the container.
Code snippet:
CSS
.flex-container { display: flex; justify-content:space-around; height: 400px; width: 600px; border: 3px solid black; }
Output:
Justify-content: space-evenly: Arrange all the child elements with equally distributed spaces between them and keep them in the center of the parent container.
Code snippet:
CSS
.flex-container { display: flex; justify-content:space-evenly; height: 400px; width: 600px; border: 3px solid black; }
Output:
Justify-content: space-between: Put spaces only between the child containers.
Code-snippet:
CSS
.flex-container { display: flex; justify-content:space-between; height: 400px; width: 600px; border: 3px solid black; }
Output:
These are the important concepts of floats.
Float is a positioning layout model.Float only focus on how an element or item can float inside a container.Float can only place items on the right side or on the left side of the corresponding container.Float has no effect if the display is absolute.Float is best for small layout positioning.There are some properties of floats such as float:right, float:left, float:none, float:inherit, float:inline-start, float:inline-end, float:initial, float:unset
Float is a positioning layout model.
Float only focus on how an element or item can float inside a container.
Float can only place items on the right side or on the left side of the corresponding container.
Float has no effect if the display is absolute.
Float is best for small layout positioning.
There are some properties of floats such as float:right, float:left, float:none, float:inherit, float:inline-start, float:inline-end, float:initial, float:unset
In conclusion, we can say that flexbox and floats are quite different features to achieve a good layout model. Using floats we are limited to place items left or right but using flexbox we can modify our models in all four directions. Flexbox is a new concept in CSS to achieve a responsive webpage with some important properties of flexbox. We should use flexbox over floats.
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 134,
"s": 52,
"text": "Before we dive into flexbox vs float, we will understand about flexbox and float."
},
{
"code": null,
"e": 237,
"s": 134,
"text": "Flexbox is a css3 layout model that provides an easy and clean way to arrange items with a container. "
},
{
"code": null,
"e": 298,
"s": 237,
"text": "These are the following reasons to use flexbox over floats. "
},
{
"code": null,
"e": 563,
"s": 298,
"text": "Positioning child elements becomes easier with flexbox.Flexbox is responsive and mobile-friendly.Flex container’s margins do not collapse with the margins of its content.We can easily change the order of elements on our webpage without even making changes in HTML."
},
{
"code": null,
"e": 619,
"s": 563,
"text": "Positioning child elements becomes easier with flexbox."
},
{
"code": null,
"e": 662,
"s": 619,
"text": "Flexbox is responsive and mobile-friendly."
},
{
"code": null,
"e": 736,
"s": 662,
"text": "Flex container’s margins do not collapse with the margins of its content."
},
{
"code": null,
"e": 831,
"s": 736,
"text": "We can easily change the order of elements on our webpage without even making changes in HTML."
},
{
"code": null,
"e": 886,
"s": 831,
"text": "These are the important concept of the flexbox model. "
},
{
"code": null,
"e": 1362,
"s": 886,
"text": "Flexbox is a direction-agnostic layout model.Flexbox has the ability to alter an item’s width and height to best fit in its container’s available free space.Flex value applies for the display property of a container which is called flex container as well as the container’s contents or flex child.Flexbox has a list of important properties that are used to make a flexible container. They are flex-direction, flex-wrap, flex-flow, justify-content, align-items, align-content."
},
{
"code": null,
"e": 1408,
"s": 1362,
"text": "Flexbox is a direction-agnostic layout model."
},
{
"code": null,
"e": 1521,
"s": 1408,
"text": "Flexbox has the ability to alter an item’s width and height to best fit in its container’s available free space."
},
{
"code": null,
"e": 1662,
"s": 1521,
"text": "Flex value applies for the display property of a container which is called flex container as well as the container’s contents or flex child."
},
{
"code": null,
"e": 1841,
"s": 1662,
"text": "Flexbox has a list of important properties that are used to make a flexible container. They are flex-direction, flex-wrap, flex-flow, justify-content, align-items, align-content."
},
{
"code": null,
"e": 1954,
"s": 1841,
"text": "Example: In this example, we will explain the advantages of flex over the float. by explaining flex properties."
},
{
"code": null,
"e": 1959,
"s": 1954,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <link rel=\"stylesheet\" href=\"main.css\" /> <style> .flex-container { height: 350px; width: 600px; border: 3px solid black; } .flex-items{ margin: 5px; } #one { height: 100px; width: 100px; border: 5px solid green; } #two{ height: 100px; width: 100px; border: 5px solid green; } #three{ height: 100px; width: 100px; border: 5px solid green; } </style></head><body> <div class=\"flex-container\"> <div id=\"one\" class=\"flex-items\"> </div> <div id=\"two\" class=\"flex-items\"> </div> <div id=\"three\" class=\"flex-items\"> </div> </div></body></html>",
"e": 2937,
"s": 1959,
"text": null
},
{
"code": null,
"e": 3041,
"s": 2937,
"text": "Output: In this example, we applied display: flex property to the larger container to make it flexible."
},
{
"code": null,
"e": 3133,
"s": 3041,
"text": "In the above code, we can change the CSS code for the class .flex-container as given below."
},
{
"code": null,
"e": 3147,
"s": 3133,
"text": "Code snippet:"
},
{
"code": null,
"e": 3151,
"s": 3147,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; height: 350px; width: 600px; border: 3px solid black; }",
"e": 3280,
"s": 3151,
"text": null
},
{
"code": null,
"e": 3517,
"s": 3280,
"text": "Output: So we can see that after applying to flex property, it automatically arranges the child container in the horizontal direction which is its default value. We can change it as per the application’s need to arrange the child items."
},
{
"code": null,
"e": 3679,
"s": 3517,
"text": "CSS flex-direction Property: The flex-direction property is a sub-property of the flexible box layout module. It established the main axis of the flexible item. "
},
{
"code": null,
"e": 3711,
"s": 3679,
"text": "Flex-direction has some values."
},
{
"code": null,
"e": 3733,
"s": 3711,
"text": "flex-direction:column"
},
{
"code": null,
"e": 3752,
"s": 3733,
"text": "flex-direction:row"
},
{
"code": null,
"e": 3782,
"s": 3752,
"text": "flex-direction:column-reverse"
},
{
"code": null,
"e": 3809,
"s": 3782,
"text": "flex-direction:row-reverse"
},
{
"code": null,
"e": 3976,
"s": 3809,
"text": "Code snippet: Just change the class properties of the class flex-container in the CSS part of the above HTML code. Similar changes are made in other snippets as well."
},
{
"code": null,
"e": 3980,
"s": 3976,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; flex-direction:column; height: 400px; width: 600px; border: 3px solid black; }",
"e": 4139,
"s": 3980,
"text": null
},
{
"code": null,
"e": 4147,
"s": 4139,
"text": "Output:"
},
{
"code": null,
"e": 4161,
"s": 4147,
"text": "Code snippet:"
},
{
"code": null,
"e": 4165,
"s": 4161,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; flex-direction:row; height: 400px; width: 600px; border: 3px solid black; }",
"e": 4321,
"s": 4165,
"text": null
},
{
"code": null,
"e": 4329,
"s": 4321,
"text": "Output:"
},
{
"code": null,
"e": 4343,
"s": 4329,
"text": "Code snippet:"
},
{
"code": null,
"e": 4347,
"s": 4343,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; flex-direction:column-reverse; height: 400px; width: 600px; border: 3px solid black; }",
"e": 4514,
"s": 4347,
"text": null
},
{
"code": null,
"e": 4522,
"s": 4514,
"text": "Output:"
},
{
"code": null,
"e": 4536,
"s": 4522,
"text": "Code snippet:"
},
{
"code": null,
"e": 4540,
"s": 4536,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; flex-direction:row-reverse; height: 400px; width: 600px; border: 3px solid black; }",
"e": 4704,
"s": 4540,
"text": null
},
{
"code": null,
"e": 4712,
"s": 4704,
"text": "Output:"
},
{
"code": null,
"e": 5044,
"s": 4712,
"text": "CSS Flex-wrap property: Flex-wrap property is used for wrapping all the elements according to their parent container, from the above example if we reduce the width of the parent container without applying the wrap property, then it will squeeze the size of the child elements in order to maintain the flexibility of the container. "
},
{
"code": null,
"e": 5253,
"s": 5044,
"text": "CSS Flex-flow property: Flex-flow property is not a single property. In this flex-direction and flex-wrap are combined, or we can say that it is a shorthand property for flex-direction and flex-wrap property."
},
{
"code": null,
"e": 5365,
"s": 5253,
"text": "CSS Justify-content property: Justify-content property is used for positioning alignment of the child elements."
},
{
"code": null,
"e": 5451,
"s": 5365,
"text": "Justify-content: start: Arrange all the child element from the start of the container"
},
{
"code": null,
"e": 5542,
"s": 5451,
"text": "Code snippet: Only change the flex-container class of the CSS part in the first HTML code."
},
{
"code": null,
"e": 5546,
"s": 5542,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; justify-content:start; height: 400px; width: 600px; border: 3px solid black; }",
"e": 5699,
"s": 5546,
"text": null
},
{
"code": null,
"e": 5707,
"s": 5699,
"text": "Output:"
},
{
"code": null,
"e": 5795,
"s": 5707,
"text": "Justify-content: center: Place all the child element around the center of the container"
},
{
"code": null,
"e": 5809,
"s": 5795,
"text": "Code snippet:"
},
{
"code": null,
"e": 5813,
"s": 5809,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; justify-content:center; height: 400px; width: 600px; border: 3px solid black; }",
"e": 5967,
"s": 5813,
"text": null
},
{
"code": null,
"e": 5975,
"s": 5967,
"text": "Output:"
},
{
"code": null,
"e": 6086,
"s": 5975,
"text": "Justify-content: space-around: Put spaces between the child elements and spread them throughout the container."
},
{
"code": null,
"e": 6100,
"s": 6086,
"text": "Code snippet:"
},
{
"code": null,
"e": 6104,
"s": 6100,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; justify-content:space-around; height: 400px; width: 600px; border: 3px solid black; }",
"e": 6264,
"s": 6104,
"text": null
},
{
"code": null,
"e": 6272,
"s": 6264,
"text": "Output:"
},
{
"code": null,
"e": 6432,
"s": 6272,
"text": "Justify-content: space-evenly: Arrange all the child elements with equally distributed spaces between them and keep them in the center of the parent container."
},
{
"code": null,
"e": 6446,
"s": 6432,
"text": "Code snippet:"
},
{
"code": null,
"e": 6450,
"s": 6446,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; justify-content:space-evenly; height: 400px; width: 600px; border: 3px solid black; }",
"e": 6610,
"s": 6450,
"text": null
},
{
"code": null,
"e": 6619,
"s": 6610,
"text": "Output: "
},
{
"code": null,
"e": 6697,
"s": 6619,
"text": "Justify-content: space-between: Put spaces only between the child containers."
},
{
"code": null,
"e": 6711,
"s": 6697,
"text": "Code-snippet:"
},
{
"code": null,
"e": 6715,
"s": 6711,
"text": "CSS"
},
{
"code": ".flex-container { display: flex; justify-content:space-between; height: 400px; width: 600px; border: 3px solid black; }",
"e": 6876,
"s": 6715,
"text": null
},
{
"code": null,
"e": 6884,
"s": 6876,
"text": "Output:"
},
{
"code": null,
"e": 6928,
"s": 6884,
"text": "These are the important concepts of floats."
},
{
"code": null,
"e": 7383,
"s": 6928,
"text": "Float is a positioning layout model.Float only focus on how an element or item can float inside a container.Float can only place items on the right side or on the left side of the corresponding container.Float has no effect if the display is absolute.Float is best for small layout positioning.There are some properties of floats such as float:right, float:left, float:none, float:inherit, float:inline-start, float:inline-end, float:initial, float:unset"
},
{
"code": null,
"e": 7420,
"s": 7383,
"text": "Float is a positioning layout model."
},
{
"code": null,
"e": 7493,
"s": 7420,
"text": "Float only focus on how an element or item can float inside a container."
},
{
"code": null,
"e": 7590,
"s": 7493,
"text": "Float can only place items on the right side or on the left side of the corresponding container."
},
{
"code": null,
"e": 7638,
"s": 7590,
"text": "Float has no effect if the display is absolute."
},
{
"code": null,
"e": 7682,
"s": 7638,
"text": "Float is best for small layout positioning."
},
{
"code": null,
"e": 7843,
"s": 7682,
"text": "There are some properties of floats such as float:right, float:left, float:none, float:inherit, float:inline-start, float:inline-end, float:initial, float:unset"
},
{
"code": null,
"e": 8220,
"s": 7843,
"text": "In conclusion, we can say that flexbox and floats are quite different features to achieve a good layout model. Using floats we are limited to place items left or right but using flexbox we can modify our models in all four directions. Flexbox is a new concept in CSS to achieve a responsive webpage with some important properties of flexbox. We should use flexbox over floats."
},
{
"code": null,
"e": 8235,
"s": 8220,
"text": "CSS-Properties"
},
{
"code": null,
"e": 8242,
"s": 8235,
"text": "Picked"
},
{
"code": null,
"e": 8246,
"s": 8242,
"text": "CSS"
},
{
"code": null,
"e": 8263,
"s": 8246,
"text": "Web Technologies"
},
{
"code": null,
"e": 8361,
"s": 8263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8400,
"s": 8361,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 8439,
"s": 8400,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 8478,
"s": 8439,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 8515,
"s": 8478,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 8544,
"s": 8515,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 8577,
"s": 8544,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 8638,
"s": 8577,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 8681,
"s": 8638,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 8753,
"s": 8681,
"text": "Differences between Functional Components and Class Components in React"
}
] |
GATE | GATE CS 2020 | Question 16
|
11 Aug, 2021
What is the worst case time complexity of inserting n2 elements into an AVL-tree with n elements initially ?(A) Θ(n4)(B) Θ(n2)(C) Θ(n2 log n)(D) Θ(n3)Answer: (C)Explanation: Since AVL tree is balanced tree, the height is O(log n). So, time complexity to insert an element in an AVL tree is O(log n) in worst case.
Note:
Every insertion of element:
Finding place to insert = O(log n)
If property not satisfied (after insertion) do rotation = O(log n)
So, an AVL insertion take = O(log n) + O(log n) = O(log n) in worst case.
Now, given n2 element need to insert into given AVL tree, therefore, total time complexity will be O(n2 log n).
Alternative method: Time complexity in worst case,
1st insertion time complexity = O(log n)
2nd insertion time complexity = O(log(n+1))
.
.
.
n2th insertion time complexity = O(log(n + n2))
So, total time complexity will be,
= O(log n) + O(log n+1)) + .... + O(log(n + n2))
= O(log n*(n+1)*(n+2)*...(n+n2))
= O(log nn2)
= O(n2 log n)
Option (C) is correct.
GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0045:08 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2001 | Question 50
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "What is the worst case time complexity of inserting n2 elements into an AVL-tree with n elements initially ?(A) Θ(n4)(B) Θ(n2)(C) Θ(n2 log n)(D) Θ(n3)Answer: (C)Explanation: Since AVL tree is balanced tree, the height is O(log n). So, time complexity to insert an element in an AVL tree is O(log n) in worst case."
},
{
"code": null,
"e": 348,
"s": 342,
"text": "Note:"
},
{
"code": null,
"e": 554,
"s": 348,
"text": "Every insertion of element:\nFinding place to insert = O(log n)\nIf property not satisfied (after insertion) do rotation = O(log n)\n\nSo, an AVL insertion take = O(log n) + O(log n) = O(log n) in worst case. "
},
{
"code": null,
"e": 666,
"s": 554,
"text": "Now, given n2 element need to insert into given AVL tree, therefore, total time complexity will be O(n2 log n)."
},
{
"code": null,
"e": 717,
"s": 666,
"text": "Alternative method: Time complexity in worst case,"
},
{
"code": null,
"e": 857,
"s": 717,
"text": "1st insertion time complexity = O(log n)\n2nd insertion time complexity = O(log(n+1))\n.\n.\n.\nn2th insertion time complexity = O(log(n + n2)) "
},
{
"code": null,
"e": 892,
"s": 857,
"text": "So, total time complexity will be,"
},
{
"code": null,
"e": 1004,
"s": 892,
"text": "= O(log n) + O(log n+1)) + .... + O(log(n + n2))\n= O(log n*(n+1)*(n+2)*...(n+n2))\n= O(log nn2)\n= O(n2 log n) "
},
{
"code": null,
"e": 1027,
"s": 1004,
"text": "Option (C) is correct."
},
{
"code": null,
"e": 2061,
"s": 1027,
"text": "GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0045:08 / 1:16:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fP8QED8d6ws\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 2066,
"s": 2061,
"text": "GATE"
},
{
"code": null,
"e": 2164,
"s": 2066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2206,
"s": 2164,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 2268,
"s": 2206,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 2302,
"s": 2268,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 2344,
"s": 2302,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 2386,
"s": 2344,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 2428,
"s": 2386,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 2462,
"s": 2428,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 2504,
"s": 2462,
"text": "GATE | GATE-CS-2015 (Set 2) | Question 55"
},
{
"code": null,
"e": 2538,
"s": 2504,
"text": "GATE | GATE CS 2008 | Question 40"
}
] |
C++ | Static Keyword | Question 1
|
28 Jun, 2021
Predict the output of following C++ program.
#include <iostream>using namespace std; class Test{ static int x;public: Test() { x++; } static int getX() {return x;}}; int Test::x = 0; int main(){ cout << Test::getX() << " "; Test t[5]; cout << Test::getX();}
(A) 0 0(B) 5 5(C) 0 5(D) Compiler ErrorAnswer: (C)Explanation: Static functions can be called without any object. So the call “Test::getX()” is fine.
Since x is initialized as 0, the first call to getX() returns 0. Note the statement x++ in constructor. When an array of 5 objects is created, the constructor is called 5 times. So x is incremented to 5 before the next call to getX().Quiz of this Question
C++-Static Keyword
Static Keyword
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
Smart Pointers in C++ and How to Use Them
C++ | Function Overloading and Default Arguments | Question 2
C++ | References | Question 4
C++ | new and delete | Question 4
C++ | const keyword | Question 1
C++ | Static Keyword | Question 3
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 97,
"s": 52,
"text": "Predict the output of following C++ program."
},
{
"code": "#include <iostream>using namespace std; class Test{ static int x;public: Test() { x++; } static int getX() {return x;}}; int Test::x = 0; int main(){ cout << Test::getX() << \" \"; Test t[5]; cout << Test::getX();}",
"e": 331,
"s": 97,
"text": null
},
{
"code": null,
"e": 481,
"s": 331,
"text": "(A) 0 0(B) 5 5(C) 0 5(D) Compiler ErrorAnswer: (C)Explanation: Static functions can be called without any object. So the call “Test::getX()” is fine."
},
{
"code": null,
"e": 737,
"s": 481,
"text": "Since x is initialized as 0, the first call to getX() returns 0. Note the statement x++ in constructor. When an array of 5 objects is created, the constructor is called 5 times. So x is incremented to 5 before the next call to getX().Quiz of this Question"
},
{
"code": null,
"e": 756,
"s": 737,
"text": "C++-Static Keyword"
},
{
"code": null,
"e": 771,
"s": 756,
"text": "Static Keyword"
},
{
"code": null,
"e": 782,
"s": 771,
"text": "C Language"
},
{
"code": null,
"e": 791,
"s": 782,
"text": "C++ Quiz"
},
{
"code": null,
"e": 889,
"s": 791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 937,
"s": 889,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 982,
"s": 937,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 1003,
"s": 982,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 1029,
"s": 1003,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 1071,
"s": 1029,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 1133,
"s": 1071,
"text": "C++ | Function Overloading and Default Arguments | Question 2"
},
{
"code": null,
"e": 1163,
"s": 1133,
"text": "C++ | References | Question 4"
},
{
"code": null,
"e": 1197,
"s": 1163,
"text": "C++ | new and delete | Question 4"
},
{
"code": null,
"e": 1230,
"s": 1197,
"text": "C++ | const keyword | Question 1"
}
] |
Maximum and minimum isolated vertices in a graph
|
18 Jun, 2021
Given ‘n’ vertices and ‘m’ edges of a graph. Find the minimum number and maximum number of isolated vertices that are possible in the graph. Examples:
Input : 4 2
Output : Minimum 0
Maximum 1
1--2 3--4 <---Minimum - No isolated vertex
1--2 <--- Maximum - 1 Isolated vertex i.e. 4
|
3
Input : 5 2
Output : Minimum 1
Maximum 2
1--2 3--4 5 <-- Minimum - 1 isolated vertex i.e. 5
1--2 4 5 <-- Maximum - 2 isolated vertex i.e. 4 and 5
|
3
For minimum number of isolated vertices, we connect two vertices by only one edge. Each vertex should be only connected to one other vertex and each vertex should have degree one Thus if the number of edges is ‘m’, and if ‘n’ vertices <=2 * ‘m’ edges, there is no isolated vertex and if this condition is false, there are n-2*m isolated vertices.For maximum number of isolated vertices, we create a polygon such that each vertex is connected to other vertex and each vertex has a diagonal with every other vertex. Thus, number of diagonals from one vertex to other vertex of n sided polygon is n*(n-3)/2 and number of edges connecting adjacent vertices is n. Thus, total number of edges is n*(n-1)/2.
For minimum number of isolated vertices, we connect two vertices by only one edge. Each vertex should be only connected to one other vertex and each vertex should have degree one Thus if the number of edges is ‘m’, and if ‘n’ vertices <=2 * ‘m’ edges, there is no isolated vertex and if this condition is false, there are n-2*m isolated vertices.
For maximum number of isolated vertices, we create a polygon such that each vertex is connected to other vertex and each vertex has a diagonal with every other vertex. Thus, number of diagonals from one vertex to other vertex of n sided polygon is n*(n-3)/2 and number of edges connecting adjacent vertices is n. Thus, total number of edges is n*(n-1)/2.
Below is the implementation of above approach.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find maximum/minimum number// of isolated vertices.#include <bits/stdc++.h>using namespace std; // Function to find out the minimum and// maximum number of isolated verticesvoid find(int n, int m){ // Condition to find out minimum number // of isolated vertices if (n <= 2 * m) cout << "Minimum " << 0 << endl; else cout << "Minimum " << n - 2 * m << endl; // To find out maximum number of isolated // vertices // Loop to find out value of number of // vertices that are connected int i; for (i = 1; i <= n; i++) { if (i * (i - 1) / 2 >= m) break; } cout << "Maximum " << n - i;} // Driver Functionint main(){ // Number of vertices int n = 4; // Number of edges int m = 2; // Calling the function to maximum and // minimum number of isolated vertices find(n, m); return 0;}
// Java program to find maximum/minimum number// of isolated vertices. import java.io.*; class GFG { // Function to find out the minimum and// maximum number of isolated vertices static void find(int n, int m){ // Condition to find out minimum number // of isolated vertices if (n <= 2 * m) System.out.println( "Minimum " + 0); else System.out.println( "Minimum " + (n - 2 * m)); // To find out maximum number of isolated // vertices // Loop to find out value of number of // vertices that are connected int i; for (i = 1; i <= n; i++) { if (i * (i - 1) / 2 >= m) break; } System.out.println( "Maximum " + (n - i));} // Driver Function public static void main (String[] args) { // Number of vertices int n = 4; // Number of edges int m = 2; // Calling the function to maximum and // minimum number of isolated vertices find(n, m); }}//This code is contributed by inder_verma.
# Python3 program to find maximum/minimum# number of isolated vertices. # Function to find out the minimum and# maximum number of isolated verticesdef find(n, m) : # Condition to find out minimum # number of isolated vertices if (n <= 2 * m): print("Minimum ", 0) else: print("Minimum ", n - 2 * m ) # To find out maximum number of # isolated vertices # Loop to find out value of number # of vertices that are connected for i in range(1, n + 1): if (i * (i - 1) // 2 >= m): break print("Maximum ", n - i) # Driver Codeif __name__ == '__main__': # Number of vertices n = 4 # Number of edges m = 2 # Calling the function to maximum and # minimum number of isolated vertices find(n, m) # This code is contributed by# SHUBHAMSINGH10
// C# program to find maximum/// minimum number of isolated vertices.using System; class GFG{ // Function to find out the// minimum and maximum number// of isolated verticesstatic void find(int n, int m){ // Condition to find out minimum // number of isolated vertices if (n <= 2 * m) Console.WriteLine("Minimum " + 0); else Console.WriteLine("Minimum " + (n - 2 * m)); // To find out maximum number // of isolated vertices // Loop to find out value of // number of vertices that // are connected int i; for (i = 1; i <= n; i++) { if (i * (i - 1) / 2 >= m) break; } Console.WriteLine("Maximum " + (n - i));} // Driver Codepublic static void Main (){ // Number of vertices int n = 4; // Number of edges int m = 2; // Calling the function to // maximum and minimum number // of isolated vertices find(n, m);}} // This code is contributed// by inder_verma.
<?php// PHP program to find maximum/minimum// number of isolated vertices. // Function to find out the// minimum and maximum number// of isolated verticesfunction find($n, $m){ // Condition to find out minimum // number of isolated vertices if ($n <= 2 * $m) echo "Minimum 0\n"; else echo "Minimum " , ($n - 2 * $m); // To find out maximum number // of isolated vertices // Loop to find out value of number // of vertices that are connected for ($i = 1; $i <= $n; $i++) { if ($i * ($i - 1) / 2 >= $m) break; } echo "Maximum " , ($n - $i);} // Driver Code // Number of vertices$n = 4; // Number of edges$m = 2; // Calling the function to// maximum and minimum number// of isolated verticesfind($n, $m); // This code is contributed// by inder_verma?>
<script> // Javascript program to find maximum/ // minimum number of isolated vertices. // Function to find out the // minimum and maximum number // of isolated vertices function find(n, m) { // Condition to find out minimum // number of isolated vertices if (n <= 2 * m) document.write("Minimum " + 0 + "</br>"); else document.write("Minimum " + (n - 2 * m) + "</br>"); // To find out maximum number // of isolated vertices // Loop to find out value of // number of vertices that // are connected let i; for (i = 1; i <= n; i++) { if (i * parseInt((i - 1) / 2, 10) >= m) break; } document.write("Maximum " + (n - i)); } // Number of vertices let n = 4; // Number of edges let m = 2; // Calling the function to // maximum and minimum number // of isolated vertices find(n, m); // This code is contributed by divyeshrabadiya07.</script>
Minimum 0
Maximum 1
Time Complexity – O(n)
inderDuMCA
SHUBHAMSINGH10
divyeshrabadiya07
Game Theory
Graph
Game Theory
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the player who will win by choosing a number in range [1, K] with sum total N
Classification of Algorithms with Examples
Zero-Sum Game
Maximum cells attacked by Rook or Bishop in given Chessboard
Game Development with Unity | Introduction
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2021"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "Given ‘n’ vertices and ‘m’ edges of a graph. Find the minimum number and maximum number of isolated vertices that are possible in the graph. Examples: "
},
{
"code": null,
"e": 506,
"s": 181,
"text": "Input : 4 2\nOutput : Minimum 0\n Maximum 1\n\n1--2 3--4 <---Minimum - No isolated vertex\n1--2 <--- Maximum - 1 Isolated vertex i.e. 4\n |\n 3\n\n\nInput : 5 2\nOutput : Minimum 1\n Maximum 2\n\n1--2 3--4 5 <-- Minimum - 1 isolated vertex i.e. 5\n1--2 4 5 <-- Maximum - 2 isolated vertex i.e. 4 and 5\n |\n 3"
},
{
"code": null,
"e": 1211,
"s": 510,
"text": "For minimum number of isolated vertices, we connect two vertices by only one edge. Each vertex should be only connected to one other vertex and each vertex should have degree one Thus if the number of edges is ‘m’, and if ‘n’ vertices <=2 * ‘m’ edges, there is no isolated vertex and if this condition is false, there are n-2*m isolated vertices.For maximum number of isolated vertices, we create a polygon such that each vertex is connected to other vertex and each vertex has a diagonal with every other vertex. Thus, number of diagonals from one vertex to other vertex of n sided polygon is n*(n-3)/2 and number of edges connecting adjacent vertices is n. Thus, total number of edges is n*(n-1)/2."
},
{
"code": null,
"e": 1558,
"s": 1211,
"text": "For minimum number of isolated vertices, we connect two vertices by only one edge. Each vertex should be only connected to one other vertex and each vertex should have degree one Thus if the number of edges is ‘m’, and if ‘n’ vertices <=2 * ‘m’ edges, there is no isolated vertex and if this condition is false, there are n-2*m isolated vertices."
},
{
"code": null,
"e": 1913,
"s": 1558,
"text": "For maximum number of isolated vertices, we create a polygon such that each vertex is connected to other vertex and each vertex has a diagonal with every other vertex. Thus, number of diagonals from one vertex to other vertex of n sided polygon is n*(n-3)/2 and number of edges connecting adjacent vertices is n. Thus, total number of edges is n*(n-1)/2."
},
{
"code": null,
"e": 1962,
"s": 1913,
"text": "Below is the implementation of above approach. "
},
{
"code": null,
"e": 1966,
"s": 1962,
"text": "C++"
},
{
"code": null,
"e": 1971,
"s": 1966,
"text": "Java"
},
{
"code": null,
"e": 1979,
"s": 1971,
"text": "Python3"
},
{
"code": null,
"e": 1982,
"s": 1979,
"text": "C#"
},
{
"code": null,
"e": 1986,
"s": 1982,
"text": "PHP"
},
{
"code": null,
"e": 1997,
"s": 1986,
"text": "Javascript"
},
{
"code": "// CPP program to find maximum/minimum number// of isolated vertices.#include <bits/stdc++.h>using namespace std; // Function to find out the minimum and// maximum number of isolated verticesvoid find(int n, int m){ // Condition to find out minimum number // of isolated vertices if (n <= 2 * m) cout << \"Minimum \" << 0 << endl; else cout << \"Minimum \" << n - 2 * m << endl; // To find out maximum number of isolated // vertices // Loop to find out value of number of // vertices that are connected int i; for (i = 1; i <= n; i++) { if (i * (i - 1) / 2 >= m) break; } cout << \"Maximum \" << n - i;} // Driver Functionint main(){ // Number of vertices int n = 4; // Number of edges int m = 2; // Calling the function to maximum and // minimum number of isolated vertices find(n, m); return 0;}",
"e": 2884,
"s": 1997,
"text": null
},
{
"code": "// Java program to find maximum/minimum number// of isolated vertices. import java.io.*; class GFG { // Function to find out the minimum and// maximum number of isolated vertices static void find(int n, int m){ // Condition to find out minimum number // of isolated vertices if (n <= 2 * m) System.out.println( \"Minimum \" + 0); else System.out.println( \"Minimum \" + (n - 2 * m)); // To find out maximum number of isolated // vertices // Loop to find out value of number of // vertices that are connected int i; for (i = 1; i <= n; i++) { if (i * (i - 1) / 2 >= m) break; } System.out.println( \"Maximum \" + (n - i));} // Driver Function public static void main (String[] args) { // Number of vertices int n = 4; // Number of edges int m = 2; // Calling the function to maximum and // minimum number of isolated vertices find(n, m); }}//This code is contributed by inder_verma.",
"e": 3866,
"s": 2884,
"text": null
},
{
"code": "# Python3 program to find maximum/minimum# number of isolated vertices. # Function to find out the minimum and# maximum number of isolated verticesdef find(n, m) : # Condition to find out minimum # number of isolated vertices if (n <= 2 * m): print(\"Minimum \", 0) else: print(\"Minimum \", n - 2 * m ) # To find out maximum number of # isolated vertices # Loop to find out value of number # of vertices that are connected for i in range(1, n + 1): if (i * (i - 1) // 2 >= m): break print(\"Maximum \", n - i) # Driver Codeif __name__ == '__main__': # Number of vertices n = 4 # Number of edges m = 2 # Calling the function to maximum and # minimum number of isolated vertices find(n, m) # This code is contributed by# SHUBHAMSINGH10",
"e": 4696,
"s": 3866,
"text": null
},
{
"code": "// C# program to find maximum/// minimum number of isolated vertices.using System; class GFG{ // Function to find out the// minimum and maximum number// of isolated verticesstatic void find(int n, int m){ // Condition to find out minimum // number of isolated vertices if (n <= 2 * m) Console.WriteLine(\"Minimum \" + 0); else Console.WriteLine(\"Minimum \" + (n - 2 * m)); // To find out maximum number // of isolated vertices // Loop to find out value of // number of vertices that // are connected int i; for (i = 1; i <= n; i++) { if (i * (i - 1) / 2 >= m) break; } Console.WriteLine(\"Maximum \" + (n - i));} // Driver Codepublic static void Main (){ // Number of vertices int n = 4; // Number of edges int m = 2; // Calling the function to // maximum and minimum number // of isolated vertices find(n, m);}} // This code is contributed// by inder_verma.",
"e": 5685,
"s": 4696,
"text": null
},
{
"code": "<?php// PHP program to find maximum/minimum// number of isolated vertices. // Function to find out the// minimum and maximum number// of isolated verticesfunction find($n, $m){ // Condition to find out minimum // number of isolated vertices if ($n <= 2 * $m) echo \"Minimum 0\\n\"; else echo \"Minimum \" , ($n - 2 * $m); // To find out maximum number // of isolated vertices // Loop to find out value of number // of vertices that are connected for ($i = 1; $i <= $n; $i++) { if ($i * ($i - 1) / 2 >= $m) break; } echo \"Maximum \" , ($n - $i);} // Driver Code // Number of vertices$n = 4; // Number of edges$m = 2; // Calling the function to// maximum and minimum number// of isolated verticesfind($n, $m); // This code is contributed// by inder_verma?>",
"e": 6503,
"s": 5685,
"text": null
},
{
"code": "<script> // Javascript program to find maximum/ // minimum number of isolated vertices. // Function to find out the // minimum and maximum number // of isolated vertices function find(n, m) { // Condition to find out minimum // number of isolated vertices if (n <= 2 * m) document.write(\"Minimum \" + 0 + \"</br>\"); else document.write(\"Minimum \" + (n - 2 * m) + \"</br>\"); // To find out maximum number // of isolated vertices // Loop to find out value of // number of vertices that // are connected let i; for (i = 1; i <= n; i++) { if (i * parseInt((i - 1) / 2, 10) >= m) break; } document.write(\"Maximum \" + (n - i)); } // Number of vertices let n = 4; // Number of edges let m = 2; // Calling the function to // maximum and minimum number // of isolated vertices find(n, m); // This code is contributed by divyeshrabadiya07.</script>",
"e": 7564,
"s": 6503,
"text": null
},
{
"code": null,
"e": 7584,
"s": 7564,
"text": "Minimum 0\nMaximum 1"
},
{
"code": null,
"e": 7610,
"s": 7586,
"text": "Time Complexity – O(n) "
},
{
"code": null,
"e": 7621,
"s": 7610,
"text": "inderDuMCA"
},
{
"code": null,
"e": 7636,
"s": 7621,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 7654,
"s": 7636,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 7666,
"s": 7654,
"text": "Game Theory"
},
{
"code": null,
"e": 7672,
"s": 7666,
"text": "Graph"
},
{
"code": null,
"e": 7684,
"s": 7672,
"text": "Game Theory"
},
{
"code": null,
"e": 7690,
"s": 7684,
"text": "Graph"
},
{
"code": null,
"e": 7788,
"s": 7690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7871,
"s": 7788,
"text": "Find the player who will win by choosing a number in range [1, K] with sum total N"
},
{
"code": null,
"e": 7914,
"s": 7871,
"text": "Classification of Algorithms with Examples"
},
{
"code": null,
"e": 7928,
"s": 7914,
"text": "Zero-Sum Game"
},
{
"code": null,
"e": 7989,
"s": 7928,
"text": "Maximum cells attacked by Rook or Bishop in given Chessboard"
},
{
"code": null,
"e": 8032,
"s": 7989,
"text": "Game Development with Unity | Introduction"
},
{
"code": null,
"e": 8072,
"s": 8032,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 8110,
"s": 8072,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 8161,
"s": 8110,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 8212,
"s": 8161,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
] |
Floor square root without using sqrt() function : Recursive
|
28 Dec, 2021
Given a number N, the task is to find the floor square root of the number N without using the built-in square root function. Floor square root of a number is the greatest whole number which is less than or equal to its square root.
Examples:
Input: N = 25 Output: 5 Explanation: Square root of 25 = 5. Therefore 5 is the greatest whole number less than equal to Square root of 25.
Input: N = 30 Output: 5 Explanation: Square root of 30 = 5.47 Therefore 5 is the greatest whole number less than equal to Square root of 30(5.47)
Naive Approach: In the basic approach to find the floor square root of a number, find the square of numbers from 1 to N, till the square of some number K becomes greater than N. Hence the value of (K – 1) will be the floor square root of N.
Below is the algorithm to solve this problem using Naive approach:
Iterate a loop from numbers 1 to N in K.
For any K, if its square becomes greater than N, then K-1 is the floor square root of N.
Time Complexity: O(√N)
Efficient Approach: From the Naive approach, it is clear that the floor square root of N will lie in the range [1, N]. Hence instead of checking each number in this range, we can efficiently search the required number in this range. Therefore, the idea is to use the binary search in order to efficiently find the floor square root of the number N in log N.
Below is the recursive algorithm to solve the above problem using Binary Search:
Implement the Binary Search in the range 0 to N.
Find the mid value of the range using formula:
mid = (start + end) / 2
Base Case: The recursive call will get executed till square of mid is less than or equal to N and the square of (mid+1) is greater than equal to N.
(mid2 ≤ N) and ((mid + 1)2 > N)
If the base case is not satisfied, then the range will get changed accordingly. If the square of mid is less than equal to N, then the range gets updated to [mid + 1, end]
If the square of mid is less than equal to N, then the range gets updated to [mid + 1, end]
if(mid2 ≤ N)
updated range = [mid + 1, end]
If the square of mid is greater than N, then the range gets updated to [low, mid + 1]
if(mid2 > N)
updated range = [low, mid - 1]
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// square root of the number N// without using sqrt() function #include <bits/stdc++.h>using namespace std; // Function to find the square// root of the number N using BSint sqrtSearch(int low, int high, int N){ // If the range is still valid if (low <= high) { // Find the mid-value of the range int mid = (low + high) / 2; // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low;} // Driver Codeint main(){ int N = 25; cout << sqrtSearch(0, N, N) << endl; return 0;}
// Java implementation to find the// square root of the number N// without using sqrt() functionclass GFG { // Function to find the square // root of the number N using BS static int sqrtSearch(int low, int high, int N) { // If the range is still valid if (low <= high) { // Find the mid-value of the range int mid = (int)(low + high) / 2; // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low; } // Driver Code public static void main (String[] args) { int N = 25; System.out.println(sqrtSearch(0, N, N)); }} // This code is contributed by Yash_R
# Python3 implementation to find the# square root of the number N# without using sqrt() function # Function to find the square# root of the number N using BSdef sqrtSearch(low, high, N) : # If the range is still valid if (low <= high) : # Find the mid-value of the range mid = (low + high) // 2; # Base Case if ((mid * mid <= N) and ((mid + 1) * (mid + 1) > N)) : return mid; # Condition to check if the # left search space is useless elif (mid * mid < N) : return sqrtSearch(mid + 1, high, N); else : return sqrtSearch(low, mid - 1, N); return low; # Driver Codeif __name__ == "__main__" : N = 25; print(sqrtSearch(0, N, N)) # This code is contributed by Yash_R
// C# implementation to find the// square root of the number N// without using sqrt() functionusing System; class GFG { // Function to find the square // root of the number N using BS static int sqrtSearch(int low, int high, int N) { // If the range is still valid if (low <= high) { // Find the mid-value of the range int mid = (int)(low + high) / 2; // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low; } // Driver Code public static void Main(String[] args) { int N = 25; Console.WriteLine(sqrtSearch(0, N, N)); }} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation to find the// square root of the number N// without using sqrt() function // Function to find the square// root of the number N using BSfunction sqrtSearch(low, high, N){ // If the range is still valid if (low <= high) { // Find the mid-value of the range var mid = parseInt( (low + high) / 2); // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low;} // Driver Codevar N = 25; document.write(sqrtSearch(0, N, N)); // This code is contributed by todaysgaurav </script>
5
Performance Analysis:
Time Complexity: As in the above approach, there is Binary Search used over the search space of 0 to N which takes O(log N) time in worst case, Hence the Time Complexity will be O(log N).
Space Complexity: As in the above approach, taking consideration of the stack space used in the recursive calls which can take O(logN) space in worst case, Hence the space complexity will be O(log N)
Yash_R
princiraj1992
nidhi_biet
todaysgaurav
shashankskb18700
Binary Search
maths-perfect-square
root
Algorithms
Mathematical
Mathematical
Binary Search
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
Find if there is a path between two vertices in an undirected graph
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 285,
"s": 53,
"text": "Given a number N, the task is to find the floor square root of the number N without using the built-in square root function. Floor square root of a number is the greatest whole number which is less than or equal to its square root."
},
{
"code": null,
"e": 297,
"s": 285,
"text": "Examples: "
},
{
"code": null,
"e": 437,
"s": 297,
"text": "Input: N = 25 Output: 5 Explanation: Square root of 25 = 5. Therefore 5 is the greatest whole number less than equal to Square root of 25. "
},
{
"code": null,
"e": 585,
"s": 437,
"text": "Input: N = 30 Output: 5 Explanation: Square root of 30 = 5.47 Therefore 5 is the greatest whole number less than equal to Square root of 30(5.47) "
},
{
"code": null,
"e": 826,
"s": 585,
"text": "Naive Approach: In the basic approach to find the floor square root of a number, find the square of numbers from 1 to N, till the square of some number K becomes greater than N. Hence the value of (K – 1) will be the floor square root of N."
},
{
"code": null,
"e": 894,
"s": 826,
"text": "Below is the algorithm to solve this problem using Naive approach: "
},
{
"code": null,
"e": 935,
"s": 894,
"text": "Iterate a loop from numbers 1 to N in K."
},
{
"code": null,
"e": 1024,
"s": 935,
"text": "For any K, if its square becomes greater than N, then K-1 is the floor square root of N."
},
{
"code": null,
"e": 1047,
"s": 1024,
"text": "Time Complexity: O(√N)"
},
{
"code": null,
"e": 1405,
"s": 1047,
"text": "Efficient Approach: From the Naive approach, it is clear that the floor square root of N will lie in the range [1, N]. Hence instead of checking each number in this range, we can efficiently search the required number in this range. Therefore, the idea is to use the binary search in order to efficiently find the floor square root of the number N in log N."
},
{
"code": null,
"e": 1487,
"s": 1405,
"text": "Below is the recursive algorithm to solve the above problem using Binary Search: "
},
{
"code": null,
"e": 1536,
"s": 1487,
"text": "Implement the Binary Search in the range 0 to N."
},
{
"code": null,
"e": 1583,
"s": 1536,
"text": "Find the mid value of the range using formula:"
},
{
"code": null,
"e": 1607,
"s": 1583,
"text": "mid = (start + end) / 2"
},
{
"code": null,
"e": 1755,
"s": 1607,
"text": "Base Case: The recursive call will get executed till square of mid is less than or equal to N and the square of (mid+1) is greater than equal to N."
},
{
"code": null,
"e": 1787,
"s": 1755,
"text": "(mid2 ≤ N) and ((mid + 1)2 > N)"
},
{
"code": null,
"e": 1959,
"s": 1787,
"text": "If the base case is not satisfied, then the range will get changed accordingly. If the square of mid is less than equal to N, then the range gets updated to [mid + 1, end]"
},
{
"code": null,
"e": 2051,
"s": 1959,
"text": "If the square of mid is less than equal to N, then the range gets updated to [mid + 1, end]"
},
{
"code": null,
"e": 2099,
"s": 2051,
"text": "if(mid2 ≤ N)\n updated range = [mid + 1, end]"
},
{
"code": null,
"e": 2185,
"s": 2099,
"text": "If the square of mid is greater than N, then the range gets updated to [low, mid + 1]"
},
{
"code": null,
"e": 2233,
"s": 2185,
"text": "if(mid2 > N)\n updated range = [low, mid - 1]"
},
{
"code": null,
"e": 2285,
"s": 2233,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2289,
"s": 2285,
"text": "C++"
},
{
"code": null,
"e": 2294,
"s": 2289,
"text": "Java"
},
{
"code": null,
"e": 2302,
"s": 2294,
"text": "Python3"
},
{
"code": null,
"e": 2305,
"s": 2302,
"text": "C#"
},
{
"code": null,
"e": 2316,
"s": 2305,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// square root of the number N// without using sqrt() function #include <bits/stdc++.h>using namespace std; // Function to find the square// root of the number N using BSint sqrtSearch(int low, int high, int N){ // If the range is still valid if (low <= high) { // Find the mid-value of the range int mid = (low + high) / 2; // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low;} // Driver Codeint main(){ int N = 25; cout << sqrtSearch(0, N, N) << endl; return 0;}",
"e": 3182,
"s": 2316,
"text": null
},
{
"code": "// Java implementation to find the// square root of the number N// without using sqrt() functionclass GFG { // Function to find the square // root of the number N using BS static int sqrtSearch(int low, int high, int N) { // If the range is still valid if (low <= high) { // Find the mid-value of the range int mid = (int)(low + high) / 2; // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low; } // Driver Code public static void main (String[] args) { int N = 25; System.out.println(sqrtSearch(0, N, N)); }} // This code is contributed by Yash_R",
"e": 4222,
"s": 3182,
"text": null
},
{
"code": "# Python3 implementation to find the# square root of the number N# without using sqrt() function # Function to find the square# root of the number N using BSdef sqrtSearch(low, high, N) : # If the range is still valid if (low <= high) : # Find the mid-value of the range mid = (low + high) // 2; # Base Case if ((mid * mid <= N) and ((mid + 1) * (mid + 1) > N)) : return mid; # Condition to check if the # left search space is useless elif (mid * mid < N) : return sqrtSearch(mid + 1, high, N); else : return sqrtSearch(low, mid - 1, N); return low; # Driver Codeif __name__ == \"__main__\" : N = 25; print(sqrtSearch(0, N, N)) # This code is contributed by Yash_R",
"e": 5000,
"s": 4222,
"text": null
},
{
"code": "// C# implementation to find the// square root of the number N// without using sqrt() functionusing System; class GFG { // Function to find the square // root of the number N using BS static int sqrtSearch(int low, int high, int N) { // If the range is still valid if (low <= high) { // Find the mid-value of the range int mid = (int)(low + high) / 2; // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low; } // Driver Code public static void Main(String[] args) { int N = 25; Console.WriteLine(sqrtSearch(0, N, N)); }} // This code is contributed by PrinciRaj1992",
"e": 6063,
"s": 5000,
"text": null
},
{
"code": "<script> // Javascript implementation to find the// square root of the number N// without using sqrt() function // Function to find the square// root of the number N using BSfunction sqrtSearch(low, high, N){ // If the range is still valid if (low <= high) { // Find the mid-value of the range var mid = parseInt( (low + high) / 2); // Base Case if ((mid * mid <= N) && ((mid + 1) * (mid + 1) > N)) { return mid; } // Condition to check if the // left search space is useless else if (mid * mid < N) { return sqrtSearch(mid + 1, high, N); } else { return sqrtSearch(low, mid - 1, N); } } return low;} // Driver Codevar N = 25; document.write(sqrtSearch(0, N, N)); // This code is contributed by todaysgaurav </script>",
"e": 6953,
"s": 6063,
"text": null
},
{
"code": null,
"e": 6955,
"s": 6953,
"text": "5"
},
{
"code": null,
"e": 6980,
"s": 6957,
"text": "Performance Analysis: "
},
{
"code": null,
"e": 7168,
"s": 6980,
"text": "Time Complexity: As in the above approach, there is Binary Search used over the search space of 0 to N which takes O(log N) time in worst case, Hence the Time Complexity will be O(log N)."
},
{
"code": null,
"e": 7368,
"s": 7168,
"text": "Space Complexity: As in the above approach, taking consideration of the stack space used in the recursive calls which can take O(logN) space in worst case, Hence the space complexity will be O(log N)"
},
{
"code": null,
"e": 7377,
"s": 7370,
"text": "Yash_R"
},
{
"code": null,
"e": 7391,
"s": 7377,
"text": "princiraj1992"
},
{
"code": null,
"e": 7402,
"s": 7391,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7415,
"s": 7402,
"text": "todaysgaurav"
},
{
"code": null,
"e": 7432,
"s": 7415,
"text": "shashankskb18700"
},
{
"code": null,
"e": 7446,
"s": 7432,
"text": "Binary Search"
},
{
"code": null,
"e": 7467,
"s": 7446,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 7472,
"s": 7467,
"text": "root"
},
{
"code": null,
"e": 7483,
"s": 7472,
"text": "Algorithms"
},
{
"code": null,
"e": 7496,
"s": 7483,
"text": "Mathematical"
},
{
"code": null,
"e": 7509,
"s": 7496,
"text": "Mathematical"
},
{
"code": null,
"e": 7523,
"s": 7509,
"text": "Binary Search"
},
{
"code": null,
"e": 7534,
"s": 7523,
"text": "Algorithms"
},
{
"code": null,
"e": 7632,
"s": 7534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7657,
"s": 7632,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 7706,
"s": 7657,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 7744,
"s": 7706,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 7795,
"s": 7744,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 7863,
"s": 7795,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 7893,
"s": 7863,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 7936,
"s": 7893,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7996,
"s": 7936,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8011,
"s": 7996,
"text": "C++ Data Types"
}
] |
Program to cyclically rotate an array by one in Python | List Slicing
|
21 Nov, 2018
Given an array, cyclically rotate the array clockwise by one.
Examples:
Input: arr = [1, 2, 3, 4, 5]
Output: arr = [5, 1, 2, 3, 4]
We have existing solution for this problem please refer Program to cyclically rotate an array by one link. We will solve this problem in python quickly using List Comprehension. Approach is very simple, just remove last element in list and append it in front of remaining list.
# Program to cyclically rotate an array by one def cyclicRotate(input): # slice list in two parts and append # last element in front of the sliced list # [input[-1]] --> converts last element pf array into list # to append in front of sliced list # input[0:-1] --> list of elements except last element print ([input[-1]] + input[0:-1]) # Driver programif __name__ == "__main__": input = [1, 2, 3, 4, 5] cyclicRotate(input)
Output:
[5, 1, 2, 3, 4]
KarlKwon
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 90,
"s": 28,
"text": "Given an array, cyclically rotate the array clockwise by one."
},
{
"code": null,
"e": 100,
"s": 90,
"text": "Examples:"
},
{
"code": null,
"e": 161,
"s": 100,
"text": "Input: arr = [1, 2, 3, 4, 5]\nOutput: arr = [5, 1, 2, 3, 4]\n"
},
{
"code": null,
"e": 439,
"s": 161,
"text": "We have existing solution for this problem please refer Program to cyclically rotate an array by one link. We will solve this problem in python quickly using List Comprehension. Approach is very simple, just remove last element in list and append it in front of remaining list."
},
{
"code": "# Program to cyclically rotate an array by one def cyclicRotate(input): # slice list in two parts and append # last element in front of the sliced list # [input[-1]] --> converts last element pf array into list # to append in front of sliced list # input[0:-1] --> list of elements except last element print ([input[-1]] + input[0:-1]) # Driver programif __name__ == \"__main__\": input = [1, 2, 3, 4, 5] cyclicRotate(input)",
"e": 910,
"s": 439,
"text": null
},
{
"code": null,
"e": 918,
"s": 910,
"text": "Output:"
},
{
"code": null,
"e": 935,
"s": 918,
"text": "[5, 1, 2, 3, 4]\n"
},
{
"code": null,
"e": 944,
"s": 935,
"text": "KarlKwon"
},
{
"code": null,
"e": 965,
"s": 944,
"text": "Python list-programs"
},
{
"code": null,
"e": 977,
"s": 965,
"text": "python-list"
},
{
"code": null,
"e": 984,
"s": 977,
"text": "Python"
},
{
"code": null,
"e": 996,
"s": 984,
"text": "python-list"
}
] |
Descriptive Analysis in R Programming
|
16 Dec, 2021
In Descriptive analysis, we are describing our data with the help of various representative methods like using charts, graphs, tables, excel files, etc. In the descriptive analysis, we describe our data in some manner and present it in a meaningful way so that it can be easily understood. Most of the time it is performed on small data sets and this analysis helps us a lot to predict some future trends based on the current findings. Some measures that are used to describe a data set are measures of central tendency and measures of variability or dispersion.
The measure of central tendency
Measure of variability
It represents the whole set of data by a single value. It gives us the location of central points. There are three main measures of central tendency:
Mean
Mode
Median
Measure of variability is known as the spread of data or how well is our data is distributed. The most common variability measures are:
Range
Variance
Standard deviation
Descriptive Analysis helps us to understand our data and is a very important part of Machine Learning. This is due to Machine Learning being all about making predictions. On the other hand, statistics is all about drawing conclusions from data, which is a necessary initial step for Machine Learning. Let’s do this descriptive analysis in R.
Descriptive analyses consist of describing simply the data using some summary statistics and graphics. Here, we’ll describe how to compute summary statistics using R software.
Before doing any computation, first of all, we need to prepare our data, save our data in external .txt or .csv files and it’s a best practice to save the file in the current directory. After that import, your data into R as follow:
Get the csv file here.
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F)# Print the first 6 rowsprint(head(myData))
Output:
Product Age Gender Education MaritalStatus Usage Fitness Income Miles
1 TM195 18 Male 14 Single 3 4 29562 112
2 TM195 19 Male 15 Single 2 3 31836 75
3 TM195 19 Female 14 Partnered 4 3 30699 66
4 TM195 19 Male 12 Single 3 3 32973 85
5 TM195 20 Male 13 Partnered 4 2 35247 47
6 TM195 20 Female 14 Partnered 3 3 32973 66
It is the sum of observations divided by the total number of observations. It is also defined as average which is the sum divided by count.
where n = number of terms
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Compute the mean valuemean = mean(myData$Age)print(mean)
Output:
[1] 28.78889
It is the middle value of the data set. It splits the data into two halves. If the number of elements in the data set is odd then the center element is median and if it is even then the median would be the average of two central elements.
where n = number of terms
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Compute the median valuemedian = median(myData$Age)print(median)
Output:
[1] 26
It is the value that has the highest frequency in the given data set. The data set may have no mode if the frequency of all data points is the same. Also, we can have more than one mode if we encounter two or more data points having the same frequency.
Example:
R
# R program to illustrate# Descriptive Analysis # Import the librarylibrary(modeest) # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Compute the mode valuemode = mfv(myData$Age)print(mode)
Output:
[1] 25
The range describes the difference between the largest and smallest data point in our data set. The bigger the range, the more is the spread of data and vice versa.
Range = Largest data value – smallest data value
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Calculate the maximummax = max(myData$Age)# Calculate the minimummin = min(myData$Age)# Calculate the rangerange = max - min cat("Range is:\n")print(range) # Alternate method to get min and maxr = range(myData$Age)print(r)
Output:
Range is:
[1] 32
[1] 18 50
It is defined as an average squared deviation from the mean. It is being calculated by finding the difference between every data point and the average which is also known as the mean, squaring them, adding all of them, and then dividing by the number of data points present in our data set.
where, N = number of terms u = Mean
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Calculating variancevariance = var(myData$Age)print(variance)
Output:
[1] 48.21217
It is defined as the square root of the variance. It is being calculated by finding the Mean, then subtract each number from the Mean which is also known as average and square the result. Adding all the values and then divide by the no of terms followed the square root.
where, N = number of terms u = Mean
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Calculating Standard deviationstd = sd(myData$Age)print(std)
Output:
[1] 6.943498
A quartile is a type of quantile. The first quartile (Q1), is defined as the middle number between the smallest number and the median of the data set, the second quartile (Q2) – the median of the given data set while the third quartile (Q3), is the middle number between the median and the largest value of the data set.
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Calculating Quartilesquartiles = quantile(myData$Age)print(quartiles)
Output:
0% 25% 50% 75% 100%
18 24 26 33 50
The interquartile range (IQR), also called as midspread or middle 50%, or technically H-spread is the difference between the third quartile (Q3) and the first quartile (Q1). It covers the center of the distribution and contains 50% of the observations.
IQR = Q3 – Q1
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Calculating IQRIQR = IQR(myData$Age)print(IQR)
Output:
[1] 9
The function summary() can be used to display several statistic summaries of either one variable or an entire data frame.
Summary of a single variable:
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Calculating summarysummary = summary(myData$Age)print(summary)
Output:
Min. 1st Qu. Median Mean 3rd Qu. Max.
18.00 24.00 26.00 28.79 33.00 50.00
Summary of the data frame
Example:
R
# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv("CardioGoodFitness.csv", stringsAsFactors = F) # Calculating summarysummary = summary(myData)print(summary)
Output:
Product Age Gender Education
Length:180 Min. :18.00 Length:180 Min. :12.00
Class :character 1st Qu.:24.00 Class :character 1st Qu.:14.00
Mode :character Median :26.00 Mode :character Median :16.00
Mean :28.79 Mean :15.57
3rd Qu.:33.00 3rd Qu.:16.00
Max. :50.00 Max. :21.00
MaritalStatus Usage Fitness Income Miles
Length:180 Min. :2.000 Min. :1.000 Min. : 29562 Min. : 21.0
Class :character 1st Qu.:3.000 1st Qu.:3.000 1st Qu.: 44059 1st Qu.: 66.0
Mode :character Median :3.000 Median :3.000 Median : 50597 Median : 94.0
Mean :3.456 Mean :3.311 Mean : 53720 Mean :103.2
3rd Qu.:4.000 3rd Qu.:4.000 3rd Qu.: 58668 3rd Qu.:114.8
Max. :7.000 Max. :5.000 Max. :104581 Max. :360.0
nidhi_biet
kumar_satyam
Picked
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
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
Similarities and Difference between Java and C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 592,
"s": 28,
"text": "In Descriptive analysis, we are describing our data with the help of various representative methods like using charts, graphs, tables, excel files, etc. In the descriptive analysis, we describe our data in some manner and present it in a meaningful way so that it can be easily understood. Most of the time it is performed on small data sets and this analysis helps us a lot to predict some future trends based on the current findings. Some measures that are used to describe a data set are measures of central tendency and measures of variability or dispersion. "
},
{
"code": null,
"e": 624,
"s": 592,
"text": "The measure of central tendency"
},
{
"code": null,
"e": 647,
"s": 624,
"text": "Measure of variability"
},
{
"code": null,
"e": 798,
"s": 647,
"text": "It represents the whole set of data by a single value. It gives us the location of central points. There are three main measures of central tendency: "
},
{
"code": null,
"e": 803,
"s": 798,
"text": "Mean"
},
{
"code": null,
"e": 808,
"s": 803,
"text": "Mode"
},
{
"code": null,
"e": 815,
"s": 808,
"text": "Median"
},
{
"code": null,
"e": 952,
"s": 815,
"text": "Measure of variability is known as the spread of data or how well is our data is distributed. The most common variability measures are: "
},
{
"code": null,
"e": 958,
"s": 952,
"text": "Range"
},
{
"code": null,
"e": 967,
"s": 958,
"text": "Variance"
},
{
"code": null,
"e": 986,
"s": 967,
"text": "Standard deviation"
},
{
"code": null,
"e": 1328,
"s": 986,
"text": "Descriptive Analysis helps us to understand our data and is a very important part of Machine Learning. This is due to Machine Learning being all about making predictions. On the other hand, statistics is all about drawing conclusions from data, which is a necessary initial step for Machine Learning. Let’s do this descriptive analysis in R."
},
{
"code": null,
"e": 1504,
"s": 1328,
"text": "Descriptive analyses consist of describing simply the data using some summary statistics and graphics. Here, we’ll describe how to compute summary statistics using R software."
},
{
"code": null,
"e": 1737,
"s": 1504,
"text": "Before doing any computation, first of all, we need to prepare our data, save our data in external .txt or .csv files and it’s a best practice to save the file in the current directory. After that import, your data into R as follow:"
},
{
"code": null,
"e": 1760,
"s": 1737,
"text": "Get the csv file here."
},
{
"code": null,
"e": 1762,
"s": 1760,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F)# Print the first 6 rowsprint(head(myData))",
"e": 1967,
"s": 1762,
"text": null
},
{
"code": null,
"e": 1975,
"s": 1967,
"text": "Output:"
},
{
"code": null,
"e": 2480,
"s": 1975,
"text": " Product Age Gender Education MaritalStatus Usage Fitness Income Miles\n1 TM195 18 Male 14 Single 3 4 29562 112\n2 TM195 19 Male 15 Single 2 3 31836 75\n3 TM195 19 Female 14 Partnered 4 3 30699 66\n4 TM195 19 Male 12 Single 3 3 32973 85\n5 TM195 20 Male 13 Partnered 4 2 35247 47\n6 TM195 20 Female 14 Partnered 3 3 32973 66"
},
{
"code": null,
"e": 2620,
"s": 2480,
"text": "It is the sum of observations divided by the total number of observations. It is also defined as average which is the sum divided by count."
},
{
"code": null,
"e": 2646,
"s": 2620,
"text": "where n = number of terms"
},
{
"code": null,
"e": 2656,
"s": 2646,
"text": "Example: "
},
{
"code": null,
"e": 2658,
"s": 2656,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Compute the mean valuemean = mean(myData$Age)print(mean)",
"e": 2879,
"s": 2658,
"text": null
},
{
"code": null,
"e": 2888,
"s": 2879,
"text": "Output: "
},
{
"code": null,
"e": 2901,
"s": 2888,
"text": "[1] 28.78889"
},
{
"code": null,
"e": 3141,
"s": 2901,
"text": "It is the middle value of the data set. It splits the data into two halves. If the number of elements in the data set is odd then the center element is median and if it is even then the median would be the average of two central elements. "
},
{
"code": null,
"e": 3167,
"s": 3141,
"text": "where n = number of terms"
},
{
"code": null,
"e": 3177,
"s": 3167,
"text": "Example: "
},
{
"code": null,
"e": 3179,
"s": 3177,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Compute the median valuemedian = median(myData$Age)print(median)",
"e": 3408,
"s": 3179,
"text": null
},
{
"code": null,
"e": 3417,
"s": 3408,
"text": "Output: "
},
{
"code": null,
"e": 3424,
"s": 3417,
"text": "[1] 26"
},
{
"code": null,
"e": 3677,
"s": 3424,
"text": "It is the value that has the highest frequency in the given data set. The data set may have no mode if the frequency of all data points is the same. Also, we can have more than one mode if we encounter two or more data points having the same frequency."
},
{
"code": null,
"e": 3687,
"s": 3677,
"text": "Example: "
},
{
"code": null,
"e": 3689,
"s": 3687,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the librarylibrary(modeest) # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Compute the mode valuemode = mfv(myData$Age)print(mode)",
"e": 3946,
"s": 3689,
"text": null
},
{
"code": null,
"e": 3955,
"s": 3946,
"text": "Output: "
},
{
"code": null,
"e": 3962,
"s": 3955,
"text": "[1] 25"
},
{
"code": null,
"e": 4127,
"s": 3962,
"text": "The range describes the difference between the largest and smallest data point in our data set. The bigger the range, the more is the spread of data and vice versa."
},
{
"code": null,
"e": 4177,
"s": 4127,
"text": "Range = Largest data value – smallest data value "
},
{
"code": null,
"e": 4187,
"s": 4177,
"text": "Example: "
},
{
"code": null,
"e": 4189,
"s": 4187,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Calculate the maximummax = max(myData$Age)# Calculate the minimummin = min(myData$Age)# Calculate the rangerange = max - min cat(\"Range is:\\n\")print(range) # Alternate method to get min and maxr = range(myData$Age)print(r)",
"e": 4576,
"s": 4189,
"text": null
},
{
"code": null,
"e": 4585,
"s": 4576,
"text": "Output: "
},
{
"code": null,
"e": 4613,
"s": 4585,
"text": "Range is:\n[1] 32\n\n[1] 18 50"
},
{
"code": null,
"e": 4904,
"s": 4613,
"text": "It is defined as an average squared deviation from the mean. It is being calculated by finding the difference between every data point and the average which is also known as the mean, squaring them, adding all of them, and then dividing by the number of data points present in our data set."
},
{
"code": null,
"e": 4940,
"s": 4904,
"text": "where, N = number of terms u = Mean"
},
{
"code": null,
"e": 4950,
"s": 4940,
"text": "Example: "
},
{
"code": null,
"e": 4952,
"s": 4950,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Calculating variancevariance = var(myData$Age)print(variance)",
"e": 5178,
"s": 4952,
"text": null
},
{
"code": null,
"e": 5187,
"s": 5178,
"text": "Output: "
},
{
"code": null,
"e": 5200,
"s": 5187,
"text": "[1] 48.21217"
},
{
"code": null,
"e": 5471,
"s": 5200,
"text": "It is defined as the square root of the variance. It is being calculated by finding the Mean, then subtract each number from the Mean which is also known as average and square the result. Adding all the values and then divide by the no of terms followed the square root."
},
{
"code": null,
"e": 5507,
"s": 5471,
"text": "where, N = number of terms u = Mean"
},
{
"code": null,
"e": 5517,
"s": 5507,
"text": "Example: "
},
{
"code": null,
"e": 5519,
"s": 5517,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Calculating Standard deviationstd = sd(myData$Age)print(std)",
"e": 5729,
"s": 5519,
"text": null
},
{
"code": null,
"e": 5738,
"s": 5729,
"text": "Output: "
},
{
"code": null,
"e": 5751,
"s": 5738,
"text": "[1] 6.943498"
},
{
"code": null,
"e": 6072,
"s": 5751,
"text": "A quartile is a type of quantile. The first quartile (Q1), is defined as the middle number between the smallest number and the median of the data set, the second quartile (Q2) – the median of the given data set while the third quartile (Q3), is the middle number between the median and the largest value of the data set."
},
{
"code": null,
"e": 6082,
"s": 6072,
"text": "Example: "
},
{
"code": null,
"e": 6084,
"s": 6082,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Calculating Quartilesquartiles = quantile(myData$Age)print(quartiles)",
"e": 6303,
"s": 6084,
"text": null
},
{
"code": null,
"e": 6312,
"s": 6303,
"text": "Output: "
},
{
"code": null,
"e": 6360,
"s": 6312,
"text": "0% 25% 50% 75% 100% \n18 24 26 33 50 "
},
{
"code": null,
"e": 6614,
"s": 6360,
"text": "The interquartile range (IQR), also called as midspread or middle 50%, or technically H-spread is the difference between the third quartile (Q3) and the first quartile (Q1). It covers the center of the distribution and contains 50% of the observations. "
},
{
"code": null,
"e": 6628,
"s": 6614,
"text": "IQR = Q3 – Q1"
},
{
"code": null,
"e": 6638,
"s": 6628,
"text": "Example: "
},
{
"code": null,
"e": 6640,
"s": 6638,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Calculating IQRIQR = IQR(myData$Age)print(IQR)",
"e": 6836,
"s": 6640,
"text": null
},
{
"code": null,
"e": 6845,
"s": 6836,
"text": "Output: "
},
{
"code": null,
"e": 6851,
"s": 6845,
"text": "[1] 9"
},
{
"code": null,
"e": 6973,
"s": 6851,
"text": "The function summary() can be used to display several statistic summaries of either one variable or an entire data frame."
},
{
"code": null,
"e": 7004,
"s": 6973,
"text": "Summary of a single variable: "
},
{
"code": null,
"e": 7014,
"s": 7004,
"text": "Example: "
},
{
"code": null,
"e": 7016,
"s": 7014,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Calculating summarysummary = summary(myData$Age)print(summary)",
"e": 7243,
"s": 7016,
"text": null
},
{
"code": null,
"e": 7252,
"s": 7243,
"text": "Output: "
},
{
"code": null,
"e": 7346,
"s": 7252,
"text": " Min. 1st Qu. Median Mean 3rd Qu. Max. \n18.00 24.00 26.00 28.79 33.00 50.00 "
},
{
"code": null,
"e": 7373,
"s": 7346,
"text": "Summary of the data frame "
},
{
"code": null,
"e": 7383,
"s": 7373,
"text": "Example: "
},
{
"code": null,
"e": 7385,
"s": 7383,
"text": "R"
},
{
"code": "# R program to illustrate# Descriptive Analysis # Import the data using read.csv()myData = read.csv(\"CardioGoodFitness.csv\", stringsAsFactors = F) # Calculating summarysummary = summary(myData)print(summary)",
"e": 7608,
"s": 7385,
"text": null
},
{
"code": null,
"e": 7617,
"s": 7608,
"text": "Output: "
},
{
"code": null,
"e": 8708,
"s": 7617,
"text": "Product Age Gender Education \n Length:180 Min. :18.00 Length:180 Min. :12.00 \n Class :character 1st Qu.:24.00 Class :character 1st Qu.:14.00 \n Mode :character Median :26.00 Mode :character Median :16.00 \n Mean :28.79 Mean :15.57 \n 3rd Qu.:33.00 3rd Qu.:16.00 \n Max. :50.00 Max. :21.00 \n\n\n MaritalStatus Usage Fitness Income Miles \n Length:180 Min. :2.000 Min. :1.000 Min. : 29562 Min. : 21.0 \n Class :character 1st Qu.:3.000 1st Qu.:3.000 1st Qu.: 44059 1st Qu.: 66.0 \n Mode :character Median :3.000 Median :3.000 Median : 50597 Median : 94.0 \n Mean :3.456 Mean :3.311 Mean : 53720 Mean :103.2 \n 3rd Qu.:4.000 3rd Qu.:4.000 3rd Qu.: 58668 3rd Qu.:114.8 \n Max. :7.000 Max. :5.000 Max. :104581 Max. :360.0 "
},
{
"code": null,
"e": 8719,
"s": 8708,
"text": "nidhi_biet"
},
{
"code": null,
"e": 8732,
"s": 8719,
"text": "kumar_satyam"
},
{
"code": null,
"e": 8739,
"s": 8732,
"text": "Picked"
},
{
"code": null,
"e": 8750,
"s": 8739,
"text": "R Language"
},
{
"code": null,
"e": 8766,
"s": 8750,
"text": "Write From Home"
},
{
"code": null,
"e": 8864,
"s": 8766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8909,
"s": 8864,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 8961,
"s": 8909,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 9019,
"s": 8961,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 9071,
"s": 9019,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 9129,
"s": 9071,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 9165,
"s": 9129,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 9201,
"s": 9165,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 9262,
"s": 9201,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 9278,
"s": 9262,
"text": "Python infinity"
}
] |
Make a violin plot in Python using Matplotlib
|
21 Apr, 2020
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
Note: For more information, refer to Python Matplotlib – An Overview
Violin plots are a combination of box plot and histograms. It portrays the distribution, median, interquartile range of data. So we see that iqr and median are the statistical information provided by box plot whereas distribution is being provided by the histogram.
Violin Plot
The white dot refers to the median.
The end points of the bold line represent the iqr1 and iqr3.
The end points of the thin line represent the min and max similar to the box plot.
The distribution above 1.5x interquartile(min, max end points of the thin line) denotes the presence of outliers.
Syntax: violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, quantiles=None, points=100,bw_method=None, *, data=None)
Parameters:dataset: Array or a sequence of vectors.The input data.
positions: array-like, default = [1, 2, ..., n].Sets the positions of the violins. The ticks and limits are automatically set to match the positions.
vert: bool, default = True.If true, creates a vertical violin plot. Otherwise, creates a horizontal violin plot.
widths: array-like, default = 0.5Either a scalar or a vector that sets the maximal width of each violin. The default is 0.5, which uses about half of the available horizontal space.
showmeans: bool, default = FalseIf True, will toggle rendering of the means.
showextrema: bool, default = TrueIf True, will toggle rendering of the extrema.
showmedians: bool, default = FalseIf True, will toggle rendering of the medians.
quantiles: array-like, default = NoneIf not None, set a list of floats in interval [0, 1] for each violin, which stands for the quantiles that will be rendered for that violin.
points: scalar, default = 100Defines the number of points to evaluate each of the gaussian kernel density estimations at.
bw_method: str, scalar or callable, optionalThe method used to calculate the estimator bandwidth. This can be ‘scott’, ‘silverman’, a scalar constant or a callable. If a scalar, this will be used directly as kde.factor. If a callable, it should take a GaussianKDE instance as its only parameter and return a scalar. If None (default), ‘scott’ is used.
Example 1:
import numpy as npimport matplotlib.pyplot as plt # creating a list of # uniformly distributed valuesuniform = np.arange(-100, 100) # creating a list of normally# distributed valuesnormal = np.random.normal(size = 100)*30 # creating figure and axes to# plot the imagefig, (ax1, ax2) = plt.subplots(nrows = 1, ncols = 2, figsize =(9, 4), sharey = True) # plotting violin plot for# uniform distributionax1.set_title('Uniform Distribution')ax1.set_ylabel('Observed values')ax1.violinplot(uniform) # plotting violin plot for # normal distributionax2.set_title('Normal Distribution')ax2.violinplot(normal) # Function to show the plotplt.show()
Output:
Example 2: Multiple Violin plots
import numpy as npimport matplotlib.pyplot as pltfrom random import randint # Creating 3 empty listsl1 = []l2 =[]l3 =[] # Filling the lists with random valuefor i in range(100): n = randint(1, 100) l1.append(n) for i in range(100): n = randint(1, 100) l2.append(n) for i in range(100): n = randint(1, 100) l3.append(n) random_collection = [l1, l2, l3] # Create a figure instancefig = plt.figure() # Create an axes instanceax = fig.gca() # Create the violinplotviolinplot = ax.violinplot(random_collection)plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 331,
"s": 52,
"text": "Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc."
},
{
"code": null,
"e": 400,
"s": 331,
"text": "Note: For more information, refer to Python Matplotlib – An Overview"
},
{
"code": null,
"e": 666,
"s": 400,
"text": "Violin plots are a combination of box plot and histograms. It portrays the distribution, median, interquartile range of data. So we see that iqr and median are the statistical information provided by box plot whereas distribution is being provided by the histogram."
},
{
"code": null,
"e": 678,
"s": 666,
"text": "Violin Plot"
},
{
"code": null,
"e": 714,
"s": 678,
"text": "The white dot refers to the median."
},
{
"code": null,
"e": 775,
"s": 714,
"text": "The end points of the bold line represent the iqr1 and iqr3."
},
{
"code": null,
"e": 858,
"s": 775,
"text": "The end points of the thin line represent the min and max similar to the box plot."
},
{
"code": null,
"e": 972,
"s": 858,
"text": "The distribution above 1.5x interquartile(min, max end points of the thin line) denotes the presence of outliers."
},
{
"code": null,
"e": 1150,
"s": 972,
"text": "Syntax: violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, quantiles=None, points=100,bw_method=None, *, data=None)"
},
{
"code": null,
"e": 1217,
"s": 1150,
"text": "Parameters:dataset: Array or a sequence of vectors.The input data."
},
{
"code": null,
"e": 1367,
"s": 1217,
"text": "positions: array-like, default = [1, 2, ..., n].Sets the positions of the violins. The ticks and limits are automatically set to match the positions."
},
{
"code": null,
"e": 1480,
"s": 1367,
"text": "vert: bool, default = True.If true, creates a vertical violin plot. Otherwise, creates a horizontal violin plot."
},
{
"code": null,
"e": 1662,
"s": 1480,
"text": "widths: array-like, default = 0.5Either a scalar or a vector that sets the maximal width of each violin. The default is 0.5, which uses about half of the available horizontal space."
},
{
"code": null,
"e": 1739,
"s": 1662,
"text": "showmeans: bool, default = FalseIf True, will toggle rendering of the means."
},
{
"code": null,
"e": 1819,
"s": 1739,
"text": "showextrema: bool, default = TrueIf True, will toggle rendering of the extrema."
},
{
"code": null,
"e": 1900,
"s": 1819,
"text": "showmedians: bool, default = FalseIf True, will toggle rendering of the medians."
},
{
"code": null,
"e": 2077,
"s": 1900,
"text": "quantiles: array-like, default = NoneIf not None, set a list of floats in interval [0, 1] for each violin, which stands for the quantiles that will be rendered for that violin."
},
{
"code": null,
"e": 2199,
"s": 2077,
"text": "points: scalar, default = 100Defines the number of points to evaluate each of the gaussian kernel density estimations at."
},
{
"code": null,
"e": 2551,
"s": 2199,
"text": "bw_method: str, scalar or callable, optionalThe method used to calculate the estimator bandwidth. This can be ‘scott’, ‘silverman’, a scalar constant or a callable. If a scalar, this will be used directly as kde.factor. If a callable, it should take a GaussianKDE instance as its only parameter and return a scalar. If None (default), ‘scott’ is used."
},
{
"code": null,
"e": 2562,
"s": 2551,
"text": "Example 1:"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt # creating a list of # uniformly distributed valuesuniform = np.arange(-100, 100) # creating a list of normally# distributed valuesnormal = np.random.normal(size = 100)*30 # creating figure and axes to# plot the imagefig, (ax1, ax2) = plt.subplots(nrows = 1, ncols = 2, figsize =(9, 4), sharey = True) # plotting violin plot for# uniform distributionax1.set_title('Uniform Distribution')ax1.set_ylabel('Observed values')ax1.violinplot(uniform) # plotting violin plot for # normal distributionax2.set_title('Normal Distribution')ax2.violinplot(normal) # Function to show the plotplt.show()",
"e": 3300,
"s": 2562,
"text": null
},
{
"code": null,
"e": 3308,
"s": 3300,
"text": "Output:"
},
{
"code": null,
"e": 3341,
"s": 3308,
"text": "Example 2: Multiple Violin plots"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom random import randint # Creating 3 empty listsl1 = []l2 =[]l3 =[] # Filling the lists with random valuefor i in range(100): n = randint(1, 100) l1.append(n) for i in range(100): n = randint(1, 100) l2.append(n) for i in range(100): n = randint(1, 100) l3.append(n) random_collection = [l1, l2, l3] # Create a figure instancefig = plt.figure() # Create an axes instanceax = fig.gca() # Create the violinplotviolinplot = ax.violinplot(random_collection)plt.show()",
"e": 3891,
"s": 3341,
"text": null
},
{
"code": null,
"e": 3899,
"s": 3891,
"text": "Output:"
},
{
"code": null,
"e": 3917,
"s": 3899,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3924,
"s": 3917,
"text": "Python"
}
] |
C++ iostream Library - cout Object
|
The object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog).
Object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write.
Following is the declaration for std::cout.
extern ostream cout;
cout is not tied to any other output stream.
A program should not mix output operations on cout with output operations on wcout (or with other wide-oriented output operations on stdout): Once an output operation has been performed on either, the standard output stream acquires an orientation (either narrow or wide) that can only be safely changed by calling freopen on stdout.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2940,
"s": 2603,
"text": "The object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog)."
},
{
"code": null,
"e": 3126,
"s": 2940,
"text": "Object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write."
},
{
"code": null,
"e": 3170,
"s": 3126,
"text": "Following is the declaration for std::cout."
},
{
"code": null,
"e": 3191,
"s": 3170,
"text": "extern ostream cout;"
},
{
"code": null,
"e": 3236,
"s": 3191,
"text": "cout is not tied to any other output stream."
},
{
"code": null,
"e": 3570,
"s": 3236,
"text": "A program should not mix output operations on cout with output operations on wcout (or with other wide-oriented output operations on stdout): Once an output operation has been performed on either, the standard output stream acquires an orientation (either narrow or wide) that can only be safely changed by calling freopen on stdout."
},
{
"code": null,
"e": 3577,
"s": 3570,
"text": " Print"
},
{
"code": null,
"e": 3588,
"s": 3577,
"text": " Add Notes"
}
] |
Survival Analysis To Understand Customer Retention | by Rashid Kazmi, Ph.D. | Towards Data Science
|
Customer retention is an increasingly pressing issue in today’s ever-competitive commercial arena. Companies are eager to develop a customer retention focus and initiatives to maximise long-term customer value. Specifically, the importance of customer retention; conceptualises an integrated customer value/retention model; and explains how usage segmentation can assist in relationship-building, retention strategy and profit planning. I am proposing a solution that integrates various techniques of customer data analysis, modelling and mining multiple concept-level associations to form an intuitive and novel approach to gauging customer loyalty and predicting their likelihood of defection. Immediate action triggered by these “early-warnings’’ resulting this could be the key to eventual customer retention
At the heart of any contractual or subscription‐oriented business model is the notion of the retention rate. An important managerial task is to take a series of past retention numbers for a given group of customers and project them into the future to make more accurate predictions about customer tenure, lifetime value, and so on. Thus, Customer lifetime value (LTV) is one of the cornerstones of database marketing. Customer Lifetime Value is usually defined as the total net income a company can expect from a customer (Novo 2001). The exact mathematical definition and its calculation method depend on many factors, such as whether customers are “subscribers” (as in most online subscription products) or “visitors” (as indirect marketing or e-business).
In this article, I will discuss the calculation and business uses of Customer Lifetime Value (LTV). The Business Intelligence Unit of the CRM any company which tailors analytical solutions to business problems, which are a high priority in the industry: chum and retention analysis, fraud analysis, campaign management, credit and collection, risk management and more. LTV plays a major role in several of these applications, in particular, Churn analysis and retention campaign management. In the context of churn analysis, the LTV of a customer or a segment is important complementary information to their churn probability, as it gives a sense of how much is really being lost due to churn and how much effort should be concentrated on this segment. In the context of retention campaigns, the main business issue is the relation between the resources invested in retention and the corresponding change in LTV of the target segments.
In general, an LTV model has three components: customer’s value over time, the customer’s length of service and a discounting factor. Each component can be calculated or estimated separately or their modelling can be combined. When modelling LTV in the context of a retention campaign, there is an additional issue, which is the need to calculate a customer’s LTV before and after the retention effort. In other words, we would need to calculate several LTV’s for each customer or segment, corresponding to each possible retention campaign we may want to run (i.e. the different incentives we may want to suggest). Being able to estimate these different LTV’s is the key to a successful and useful LTV application.
Let’s get with a quick motivation and the question that sometimes I do get asked what is the average subscription length and how long customers are at the company. For example, we have nine customers and the bars are tracking their average subscription lengths. The green bars are the customer that is still active and the red bars are the customer that are no longer active customers.
So say what’s the average subscription length? One question that needs to be asked, however, is whether just take the average of all of these customers in the CRM database or customer that are still active?
What if one takes average subscription length next month, probably going to to get totally different. Essentially, its s a moving target we are trying to look at. The second scenario can be one just ignore the active people and just take the inactive people and look at the average of that. This also does not resolve the problem as well because again some customer will become inactive. Thus, we are massively biasing our dataset so the customer who’ve already cancelled so neither way of taking the straightforward out which really gives us what we want. Taken together, these discussions suggest that, we’ve got a sense of data where we haven’t actually observed the endpoint that we’re trying to measure yet so essentially taking an average like this is never really going to be a sensible thing to do so.
To measure the problem mentioned above we need survival analysis for estimating the time to an event for a particular population when you may not have all you know see all the events happen it’s all your data points. Survival analysis is really quite an old idea in statistics and it’s used quite a lot so, for example, in medical statistics, not a very cheery example to start with. Where survival rates after cancer and the probability that people are surviving five-ten years are all survival analysis. Going back to what we care about is our customers and what we’re looking at is from when customers have signed up and started and moved off their free trial on to pay for subscription and how long do we think they’re going to be open to using the service which obviously then goes into the lifetime value side of it.
To begin with, its good idea to walk through some of the definition to understand survival analysis conceptually. We’ll take care of capital T which is the time to a subscription end for a customer. This is obviously greater than zero. However, it could be infinite if the customer never churns. This is quantity we care about and this will help us to understand lifetime value which is basically the probability that the customer hasn’t churned at any day T into the future. This is non increasing function. The overall probability is also important which is what would happen on each infinitesimal day. We define this by the hazard function which is the probability that on any given day T i.e. the exact day the customer churn not one day before not one day afterwards. These two things as you expect are related but it was just like a little bit of elementary probability you can show that essentially the survival function is expressed in terms of the hazard function in a relatively simple way.
In Python, we’ve got two main package lifelines and scikit-survival package. Lifelines are longer standing package and are very lightweight. Nonetheless, it also offers really nice visualisations. Both of these are based on their scikit-learn. One can use them how you’d use any scikit-learn package and put it in pipelines.
The dataset — here we used customer churn. The idea is to use data to walk the reader through the full cycle of customer retention with a data science perspective. We have started with understanding the business perspective of the problem. Then, we will use the available data set to gain insights and build a predictive model for use with future data.
We’ve got a lot of categorical data so particularly stuff like a partner, dependent, contract etc. There is standard one hot entertaining approach where you just turn it into like n or n minus one binary feature based on category. This would be great for X if you remember how cox model looks: it means we’d have a coefficient attached to every single categorical variable. So we will get really good clarity on the impact of each individual category. This would result in a massive data set as we have got the curse of dimensionality.
HTML
CSS
Result
Skip Results Iframe
<script src="https://gist.github.com/rhkaz/f6afe75ab2151a4a3a91f98b396ab030.js"></script>
/* https://github.com/lonekorean/gist-syntax-themes */
@import url('https://cdn.rawgit.com/lonekorean/gist-syntax-themes/848d6580/stylesheets/monokai.css');
@import url('https://fonts.googleapis.com/css?family=Open+Sans');
body {
margin: 20px;
font: 16px 'Open Sans', sans-serif;
}
This Pen is owned by Rashid Kazmi on CodePen.
See more by @rhkaz on CodePen
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.
|
[
{
"code": null,
"e": 985,
"s": 172,
"text": "Customer retention is an increasingly pressing issue in today’s ever-competitive commercial arena. Companies are eager to develop a customer retention focus and initiatives to maximise long-term customer value. Specifically, the importance of customer retention; conceptualises an integrated customer value/retention model; and explains how usage segmentation can assist in relationship-building, retention strategy and profit planning. I am proposing a solution that integrates various techniques of customer data analysis, modelling and mining multiple concept-level associations to form an intuitive and novel approach to gauging customer loyalty and predicting their likelihood of defection. Immediate action triggered by these “early-warnings’’ resulting this could be the key to eventual customer retention"
},
{
"code": null,
"e": 1744,
"s": 985,
"text": "At the heart of any contractual or subscription‐oriented business model is the notion of the retention rate. An important managerial task is to take a series of past retention numbers for a given group of customers and project them into the future to make more accurate predictions about customer tenure, lifetime value, and so on. Thus, Customer lifetime value (LTV) is one of the cornerstones of database marketing. Customer Lifetime Value is usually defined as the total net income a company can expect from a customer (Novo 2001). The exact mathematical definition and its calculation method depend on many factors, such as whether customers are “subscribers” (as in most online subscription products) or “visitors” (as indirect marketing or e-business)."
},
{
"code": null,
"e": 2680,
"s": 1744,
"text": "In this article, I will discuss the calculation and business uses of Customer Lifetime Value (LTV). The Business Intelligence Unit of the CRM any company which tailors analytical solutions to business problems, which are a high priority in the industry: chum and retention analysis, fraud analysis, campaign management, credit and collection, risk management and more. LTV plays a major role in several of these applications, in particular, Churn analysis and retention campaign management. In the context of churn analysis, the LTV of a customer or a segment is important complementary information to their churn probability, as it gives a sense of how much is really being lost due to churn and how much effort should be concentrated on this segment. In the context of retention campaigns, the main business issue is the relation between the resources invested in retention and the corresponding change in LTV of the target segments."
},
{
"code": null,
"e": 3395,
"s": 2680,
"text": "In general, an LTV model has three components: customer’s value over time, the customer’s length of service and a discounting factor. Each component can be calculated or estimated separately or their modelling can be combined. When modelling LTV in the context of a retention campaign, there is an additional issue, which is the need to calculate a customer’s LTV before and after the retention effort. In other words, we would need to calculate several LTV’s for each customer or segment, corresponding to each possible retention campaign we may want to run (i.e. the different incentives we may want to suggest). Being able to estimate these different LTV’s is the key to a successful and useful LTV application."
},
{
"code": null,
"e": 3781,
"s": 3395,
"text": "Let’s get with a quick motivation and the question that sometimes I do get asked what is the average subscription length and how long customers are at the company. For example, we have nine customers and the bars are tracking their average subscription lengths. The green bars are the customer that is still active and the red bars are the customer that are no longer active customers."
},
{
"code": null,
"e": 3988,
"s": 3781,
"text": "So say what’s the average subscription length? One question that needs to be asked, however, is whether just take the average of all of these customers in the CRM database or customer that are still active?"
},
{
"code": null,
"e": 4798,
"s": 3988,
"text": "What if one takes average subscription length next month, probably going to to get totally different. Essentially, its s a moving target we are trying to look at. The second scenario can be one just ignore the active people and just take the inactive people and look at the average of that. This also does not resolve the problem as well because again some customer will become inactive. Thus, we are massively biasing our dataset so the customer who’ve already cancelled so neither way of taking the straightforward out which really gives us what we want. Taken together, these discussions suggest that, we’ve got a sense of data where we haven’t actually observed the endpoint that we’re trying to measure yet so essentially taking an average like this is never really going to be a sensible thing to do so."
},
{
"code": null,
"e": 5621,
"s": 4798,
"text": "To measure the problem mentioned above we need survival analysis for estimating the time to an event for a particular population when you may not have all you know see all the events happen it’s all your data points. Survival analysis is really quite an old idea in statistics and it’s used quite a lot so, for example, in medical statistics, not a very cheery example to start with. Where survival rates after cancer and the probability that people are surviving five-ten years are all survival analysis. Going back to what we care about is our customers and what we’re looking at is from when customers have signed up and started and moved off their free trial on to pay for subscription and how long do we think they’re going to be open to using the service which obviously then goes into the lifetime value side of it."
},
{
"code": null,
"e": 6622,
"s": 5621,
"text": "To begin with, its good idea to walk through some of the definition to understand survival analysis conceptually. We’ll take care of capital T which is the time to a subscription end for a customer. This is obviously greater than zero. However, it could be infinite if the customer never churns. This is quantity we care about and this will help us to understand lifetime value which is basically the probability that the customer hasn’t churned at any day T into the future. This is non increasing function. The overall probability is also important which is what would happen on each infinitesimal day. We define this by the hazard function which is the probability that on any given day T i.e. the exact day the customer churn not one day before not one day afterwards. These two things as you expect are related but it was just like a little bit of elementary probability you can show that essentially the survival function is expressed in terms of the hazard function in a relatively simple way."
},
{
"code": null,
"e": 6947,
"s": 6622,
"text": "In Python, we’ve got two main package lifelines and scikit-survival package. Lifelines are longer standing package and are very lightweight. Nonetheless, it also offers really nice visualisations. Both of these are based on their scikit-learn. One can use them how you’d use any scikit-learn package and put it in pipelines."
},
{
"code": null,
"e": 7300,
"s": 6947,
"text": "The dataset — here we used customer churn. The idea is to use data to walk the reader through the full cycle of customer retention with a data science perspective. We have started with understanding the business perspective of the problem. Then, we will use the available data set to gain insights and build a predictive model for use with future data."
},
{
"code": null,
"e": 7836,
"s": 7300,
"text": "We’ve got a lot of categorical data so particularly stuff like a partner, dependent, contract etc. There is standard one hot entertaining approach where you just turn it into like n or n minus one binary feature based on category. This would be great for X if you remember how cox model looks: it means we’d have a coefficient attached to every single categorical variable. So we will get really good clarity on the impact of each individual category. This would result in a massive data set as we have got the curse of dimensionality."
},
{
"code": null,
"e": 7845,
"s": 7836,
"text": "\n\nHTML\n\n"
},
{
"code": null,
"e": 7853,
"s": 7845,
"text": "\n\nCSS\n\n"
},
{
"code": null,
"e": 7864,
"s": 7853,
"text": "\n\nResult\n\n"
},
{
"code": null,
"e": 7886,
"s": 7864,
"text": "\nSkip Results Iframe\n"
},
{
"code": null,
"e": 7976,
"s": 7886,
"text": "<script src=\"https://gist.github.com/rhkaz/f6afe75ab2151a4a3a91f98b396ab030.js\"></script>"
},
{
"code": null,
"e": 8265,
"s": 7976,
"text": "/* https://github.com/lonekorean/gist-syntax-themes */\n@import url('https://cdn.rawgit.com/lonekorean/gist-syntax-themes/848d6580/stylesheets/monokai.css');\n\n@import url('https://fonts.googleapis.com/css?family=Open+Sans');\nbody {\n margin: 20px;\n font: 16px 'Open Sans', sans-serif;\n}\n\n"
},
{
"code": null,
"e": 8313,
"s": 8265,
"text": "\nThis Pen is owned by Rashid Kazmi on CodePen.\n"
},
{
"code": null,
"e": 8347,
"s": 8313,
"text": "\n\nSee more by @rhkaz on CodePen\n\n"
},
{
"code": null,
"e": 8398,
"s": 8347,
"text": "\nThis Pen doesn't use any external CSS resources.\n"
}
] |
Data Structures and Algorithms | Set 3 - GeeksforGeeks
|
05 Jul, 2018
Following questions have asked in GATE CS exam.
1. Suppose you are given an array s[1...n] and a procedure reverse (s,i,j) which reverses the order of elements in a between positions i and j (both inclusive). What does the following sequence
do, where 1 < k <= n:
reverse (s, 1, k);
reverse (s, k + 1, n);
reverse (s, 1, n);
(GATE CS 2000)(a) Rotates s left by k positions(b) Leaves s unchanged(c) Reverses all elements of s(d) None of the above
Answer: (a)Effect of the above 3 reversals for any k is equivalent to left rotation of the array of size n by k. Please see this post for details.If we rotate an array n times for k = 1 to n, we get the same array back.
2. The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE CS 2004)a) queueb) stackc) treed) list
Answer(b)There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of all three types.
void func(int c, int a[]){ return ((c +2) + arr[(c-2)]) ; }
Stack is a straightforward choice for checking if left and right parentheses are balanced. Here is a algorithm to do the same.
/*Return 1 if expression has balanced parentheses */bool areParenthesesBalanced(expression ){ for each character in expression { if(character == ’(’ || character == ’{’ || character == ’[’) push(stack, character); if(character == ’)’ || character == ’}’ || character == ’]’) { if(isEmpty(stack)) return 0; /*We are seeing a right parenthesis without a left pair*/ /* Pop the top element from stack, if it is not a pair bracket of character then there is a mismatch. This will happen for expressions like {(}) */ else if (! isMatchingPair(pop(stack), character) ) return 0; } } if(isEmpty(stack)) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* End of function to check parentheses */ /* Returns 1 if character1 and character2 are matching left and right parentheses */bool isMatchingPair(character1, character2){ if(character1 == ‘(‘ && character2 == ‘)’) return 1; else If(character1 == ‘{‘ && character2 == ‘}’) return 1; else If(character1 == ‘[‘ && character2 == ‘]’) return 1; else return 0;}
3. Level order traversal of a rooted tree can be done by starting from the root and performing (GATE CS 2004)a) preorder traversalb) in-order traversalc) depth first searchd) breadth first search
Answer(d)See this post for details
4. Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?i. 9679, 1989, 4199 hash to the same valueii. 1471, 6171 has to the same valueiii. All elements hash to the same valueiv. Each element hashes to a different value(GATE CS 2004)
a) i onlyb) ii onlyc) i and ii onlyd) iii or iv
Answer (c)
5. Postorder traversal of a given binary search tree, T produces the following sequence of keys10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29Which one of the following sequences of keys can be the result of an in-order traversal of the tree T? (GATE CS 2005)a) 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95b) 9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29c) 29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95d) 95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29
Answer (a)Inorder traversal of a BST always gives elements in increasing order. Among all four options, a) is the only increasing order sequence.
GATE-CS-2004
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Introduction of Operating System - Set 1
Types of Network Topology
Data Structures and Algorithms | Set 21
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2
|
[
{
"code": null,
"e": 23885,
"s": 23857,
"text": "\n05 Jul, 2018"
},
{
"code": null,
"e": 23933,
"s": 23885,
"text": "Following questions have asked in GATE CS exam."
},
{
"code": null,
"e": 24127,
"s": 23933,
"text": "1. Suppose you are given an array s[1...n] and a procedure reverse (s,i,j) which reverses the order of elements in a between positions i and j (both inclusive). What does the following sequence"
},
{
"code": null,
"e": 24217,
"s": 24127,
"text": "do, where 1 < k <= n:\n reverse (s, 1, k);\n reverse (s, k + 1, n);\n reverse (s, 1, n);\n"
},
{
"code": null,
"e": 24338,
"s": 24217,
"text": "(GATE CS 2000)(a) Rotates s left by k positions(b) Leaves s unchanged(c) Reverses all elements of s(d) None of the above"
},
{
"code": null,
"e": 24558,
"s": 24338,
"text": "Answer: (a)Effect of the above 3 reversals for any k is equivalent to left rotation of the array of size n by k. Please see this post for details.If we rotate an array n times for k = 1 to n, we get the same array back."
},
{
"code": null,
"e": 24702,
"s": 24558,
"text": "2. The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE CS 2004)a) queueb) stackc) treed) list"
},
{
"code": null,
"e": 24835,
"s": 24702,
"text": "Answer(b)There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of all three types."
},
{
"code": "void func(int c, int a[]){ return ((c +2) + arr[(c-2)]) ; }",
"e": 24899,
"s": 24835,
"text": null
},
{
"code": null,
"e": 25026,
"s": 24899,
"text": "Stack is a straightforward choice for checking if left and right parentheses are balanced. Here is a algorithm to do the same."
},
{
"code": "/*Return 1 if expression has balanced parentheses */bool areParenthesesBalanced(expression ){ for each character in expression { if(character == ’(’ || character == ’{’ || character == ’[’) push(stack, character); if(character == ’)’ || character == ’}’ || character == ’]’) { if(isEmpty(stack)) return 0; /*We are seeing a right parenthesis without a left pair*/ /* Pop the top element from stack, if it is not a pair bracket of character then there is a mismatch. This will happen for expressions like {(}) */ else if (! isMatchingPair(pop(stack), character) ) return 0; } } if(isEmpty(stack)) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* End of function to check parentheses */ /* Returns 1 if character1 and character2 are matching left and right parentheses */bool isMatchingPair(character1, character2){ if(character1 == ‘(‘ && character2 == ‘)’) return 1; else If(character1 == ‘{‘ && character2 == ‘}’) return 1; else If(character1 == ‘[‘ && character2 == ‘]’) return 1; else return 0;}",
"e": 26222,
"s": 25026,
"text": null
},
{
"code": null,
"e": 26418,
"s": 26222,
"text": "3. Level order traversal of a rooted tree can be done by starting from the root and performing (GATE CS 2004)a) preorder traversalb) in-order traversalc) depth first searchd) breadth first search"
},
{
"code": null,
"e": 26453,
"s": 26418,
"text": "Answer(d)See this post for details"
},
{
"code": null,
"e": 26783,
"s": 26453,
"text": "4. Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?i. 9679, 1989, 4199 hash to the same valueii. 1471, 6171 has to the same valueiii. All elements hash to the same valueiv. Each element hashes to a different value(GATE CS 2004)"
},
{
"code": null,
"e": 26831,
"s": 26783,
"text": "a) i onlyb) ii onlyc) i and ii onlyd) iii or iv"
},
{
"code": null,
"e": 26842,
"s": 26831,
"text": "Answer (c)"
},
{
"code": null,
"e": 27292,
"s": 26842,
"text": "5. Postorder traversal of a given binary search tree, T produces the following sequence of keys10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29Which one of the following sequences of keys can be the result of an in-order traversal of the tree T? (GATE CS 2005)a) 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95b) 9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29c) 29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95d) 95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29"
},
{
"code": null,
"e": 27438,
"s": 27292,
"text": "Answer (a)Inorder traversal of a BST always gives elements in increasing order. Among all four options, a) is the only increasing order sequence."
},
{
"code": null,
"e": 27451,
"s": 27438,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 27469,
"s": 27451,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 27477,
"s": 27469,
"text": "GATE CS"
},
{
"code": null,
"e": 27481,
"s": 27477,
"text": "MCQ"
},
{
"code": null,
"e": 27579,
"s": 27481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27588,
"s": 27579,
"text": "Comments"
},
{
"code": null,
"e": 27601,
"s": 27588,
"text": "Old Comments"
},
{
"code": null,
"e": 27650,
"s": 27601,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 27682,
"s": 27650,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27721,
"s": 27682,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 27762,
"s": 27721,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 27788,
"s": 27762,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 27828,
"s": 27788,
"text": "Data Structures and Algorithms | Set 21"
},
{
"code": null,
"e": 27875,
"s": 27828,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 27901,
"s": 27875,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 27927,
"s": 27901,
"text": "Computer Networks | Set 1"
}
] |
How to set location and location.href using JavaScript ? - GeeksforGeeks
|
03 Dec, 2020
Both location and location.href are used to set or return the complete URL of your current page. They return a string which contains the entire URL with the protocol.
Syntax:
location = "https://www.geeksforgeeks.org";
or
location.href = "https://www.geeksforgeeks.org";
Both are used to set the URL. Both are described as running JavaScript 1.0 in the backend in Netscape 2.0 and have been running in all browsers ever since. However, you have the liberty to prefer any one of the two according to your convenience but it is preferred to use location.href because location might not support older versions of Internet Explorer.
Commands like location.split(“#); cannot be used as location is an object but location.href can be used as it is a string.
Example: The following code demonstrates the DOM Location href property.
HTML
<!DOCTYPE html> <html> <head> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>Setting location and location.href</h2> <p> Click on the button to go to designated URL </p> <button ondblclick="myhref()"> Destination URL </button> <p id="href"></p> <script> function myhref() { location.href = "https://www.geeksforgeeks.org"; } </script> </body> </html>
Output:
Before Clicking the Button:
After Double Click on Button:
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 24789,
"s": 24761,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 24956,
"s": 24789,
"text": "Both location and location.href are used to set or return the complete URL of your current page. They return a string which contains the entire URL with the protocol."
},
{
"code": null,
"e": 24964,
"s": 24956,
"text": "Syntax:"
},
{
"code": null,
"e": 25008,
"s": 24964,
"text": "location = \"https://www.geeksforgeeks.org\";"
},
{
"code": null,
"e": 25011,
"s": 25008,
"text": "or"
},
{
"code": null,
"e": 25060,
"s": 25011,
"text": "location.href = \"https://www.geeksforgeeks.org\";"
},
{
"code": null,
"e": 25419,
"s": 25060,
"text": "Both are used to set the URL. Both are described as running JavaScript 1.0 in the backend in Netscape 2.0 and have been running in all browsers ever since. However, you have the liberty to prefer any one of the two according to your convenience but it is preferred to use location.href because location might not support older versions of Internet Explorer. "
},
{
"code": null,
"e": 25543,
"s": 25419,
"text": "Commands like location.split(“#); cannot be used as location is an object but location.href can be used as it is a string. "
},
{
"code": null,
"e": 25616,
"s": 25543,
"text": "Example: The following code demonstrates the DOM Location href property."
},
{
"code": null,
"e": 25621,
"s": 25616,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>Setting location and location.href</h2> <p> Click on the button to go to designated URL </p> <button ondblclick=\"myhref()\"> Destination URL </button> <p id=\"href\"></p> <script> function myhref() { location.href = \"https://www.geeksforgeeks.org\"; } </script> </body> </html> ",
"e": 26300,
"s": 25621,
"text": null
},
{
"code": null,
"e": 26308,
"s": 26300,
"text": "Output:"
},
{
"code": null,
"e": 26336,
"s": 26308,
"text": "Before Clicking the Button:"
},
{
"code": null,
"e": 26366,
"s": 26336,
"text": "After Double Click on Button:"
},
{
"code": null,
"e": 26375,
"s": 26366,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26385,
"s": 26375,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26401,
"s": 26385,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 26425,
"s": 26401,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26429,
"s": 26425,
"text": "CSS"
},
{
"code": null,
"e": 26434,
"s": 26429,
"text": "HTML"
},
{
"code": null,
"e": 26445,
"s": 26434,
"text": "JavaScript"
},
{
"code": null,
"e": 26464,
"s": 26445,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26481,
"s": 26464,
"text": "Web Technologies"
},
{
"code": null,
"e": 26508,
"s": 26481,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26513,
"s": 26508,
"text": "HTML"
},
{
"code": null,
"e": 26611,
"s": 26513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26620,
"s": 26611,
"text": "Comments"
},
{
"code": null,
"e": 26633,
"s": 26620,
"text": "Old Comments"
},
{
"code": null,
"e": 26691,
"s": 26633,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26728,
"s": 26691,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26769,
"s": 26728,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 26806,
"s": 26769,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26870,
"s": 26806,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 26930,
"s": 26870,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26991,
"s": 26930,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27028,
"s": 26991,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27081,
"s": 27028,
"text": "Hide or show elements in HTML using display property"
}
] |
Dashboard Tutorial (I): Flask and Chart.js | Towards Data Science
|
When it comes to creating the web with Python, Flask is often the common backend applied by developers. Flask enables HTTP requests’ management and templates rendering. For this blog, we’ll walk through the basic structure of flask and how flask is able to render the template from other webpages. Besides, you’ll learn to load a comma-separated value (CSV) file and visualize it using Chart.js.
In this article, you will learn:
(1) Creating a Basic Flask Application
(2) Chart.JS plot
First, we create a .py file to import flask packages and set up flask configuration. Flask would call HTML file from the templates folder without any specified path. In order to direct flask to the right folder, we specify template_folder and static_folder path. In the static folder, it normally stores javascript, CSS files, and images. In the template folder, it normally stores HTML files. Besides, we set app.config equal True for the terminal to show the error messages. In addition, the error message would be popped out in the console under the inspect element.
import flaskapp = flask.Flask(__name__, static_url_path='', static_folder='static', template_folder='template')app.config["DEBUG"] = True
Then, we move on to define the route for the home page. We are able to give a webpage name that can be passed into HTML. Render_template function would call the HTML file and display it on the specified webpage route. For the second function of user, the name tag embedded in the route can be passed into HTML. For instance, when (http://127.0.0.1:5000/home) is given, the content would be “Hello home”. Also, users are able to assign the route of HTML webpage by using redirect function and put the web page's name in url_for function.
from flask import render_template, redirect, [email protected]("/home")def home(): return render_template("home.html")@app.route("/<name>")def user(name): return f"Hello-- {name}!"@app.route("/admin")def admin(): return redirect(url_for("home"))
While the above set-up is completed, you are ready to run flask application by initiating the host and port.
if __name__ == '__main__': app.run(host="localhost", port=8000, debug=True)
Chart.JS becomes a popular and powerful data visualization library. The library adds its flexibility for users to customize the plots by feeding certain parameters, which meets users’ expectations. The main advantage of creating plots from Chart.js is the basic code structure that allows users to display plots without creating numerous lines of codes.
Before getting started, make sure to call the Chart.js files either by calling the webpage or specifying the local directory with the downloaded files.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
We also need to create a canvas node to render the chart and specify the size of the plot with its width and height.
<canvas id="myChart" width="400" height="400"></canvas>
For the following 4 plots examples using Chart.js, I mainly use the Epidemiological Data from the COVID-19 Outbreak in Canada data source. The data can be accessed with its link.
First, we will load the CSV file by calling the d3 library and the file would be rendered into makeChart function. Next, we define the function with the data parameter and map the columns of data into certain variables.
d3 .csv(“/file/Bar_cases.csv”) .then(makeChart);function makeChart(data) { var country = data.map(function(d) {return d.province;}); var value = data.map(function(d) {return d.cumulative_cases;});
Then, we create the chart by calling the canvas id through getElementById. Bar Chart is simply generated by specifying the type as the bar (to flip the direction of the bars, set type to horizontalBar). The label of the bar chart is set with the provinces’ names and data are the cumulative cases in May. You are able to create legend and title through parameters.
// Bar chart new Chart(document.getElementById("myCanvas"), { type: 'bar', data: { labels: country, datasets: [ { label: "Population (millions)", backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"], data: value } ] }, options: { legend: { display: false }, title: { display: true, text: 'Total Confirmed Cases of COVID in May' } } });
Through the bar chart below, we can see the information by the hovered information. Quebec has the most people infected with COVID among 5 provinces, while Ontario is the second highest one.
First, we need to prepare the dataset for the line plot. To create the time-series line plot, we need to filter monthly confirmed cases of COVID19 for each province. OnlyUnique function is to generate the unique values from an array. forEach function is able to locate the same index on the multiple arrays through the iteration of values and indexes on an array.
// get unique value of array function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var mon_unique = month.filter( onlyUnique );province.forEach((pro, index) => { if (pro =="Alberta") { ab_val.push(value[index]); } else if (pro =="BC") { BC_val.push(value[index]); } else if (pro =="Manitoba") { mb_val.push(value[index]); } else if (pro =="New Brunswick") { nb_val.push(value[index]); } else { nl_val.push(value[index]); } });
Line Chart is simply generated by specifying the type as the line. For each line, we can feed the label and data wrapped in a dataset list. By default, the area under each line is filled with color, covering the area between the line and the x-axis. The color can be removed by specifying (fill: false). Also, the color can be specified with the borderColor parameter.
// Line chart new Chart(document.getElementById("myCanvas"), { type: 'line', data: { labels: mon_unique, datasets: [{ data: ab_val, label: "Alberta", borderColor: "#3e95cd", fill: false }, { data: BC_val, label: "BC", borderColor: "#8e5ea2", fill: false }, { data: mb_val, label: "Manitoba", borderColor: "#3cba9f", fill: false }, { data: nb_val, label: "New Brunswick", borderColor: "#e8c3b9", fill: false }, { data: nl_val, label: "NL", borderColor: "#c45850", fill: false } ] }, options: { title: { display: true, text: 'Positive Cases of COVID in provinces of Canada' }, hover: { mode: 'index', intersect: true }, }});
From the line plot below, 4 provinces except BC are reported with 0 confirmed cases in January and February. From mid-February, there is a gradual increase in confirmed cases in Alberta and BC. Starting in March, a substantial increase of positive cases appear in Alberta as the AB province is the top among the 5 provinces. On the other hand, provinces like MB, NB, and NL are reported with low confirmed COVID cases. In May, the curve is flattened with fewer COVID cases.
First, we need to prepare the dataset for the doughnut plot. Each province array is processed and have the final input of the cumulative cases in May.
//donut chart, get the end of MAy & display the cumulative cases of 5 provinces// get unique value of array function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var pro_unique = province.filter( onlyUnique ); var ab_val = [] var BC_val = [] var mb_val = [] var nb_val = [] var nl_val = []date.forEach((i_dt, index) => { if (i_dt == '2020-05-31' && province[index] =="Alberta") { ab_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] =="BC") { BC_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] =="Manitoba") { mb_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] =="New Brunswick") { nb_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] =="NL") { nl_val.push(value[index]); } });
There are a total of 6 buttons. Button randomizeData enables data randomization while the area of each label can appear in proportion. For the other 4 buttons, they support the function to add or remove the data. Besides, the button like Semi/Full Circle, allows the circle to expand and shrink into fall and half size. Once every button is clicked, it will call the Doughnut.update() function to have the plot updated.
<button id="randomizeData">Randomize Data</button><button id="addDataset">Add Dataset</button><button id="removeDataset">Remove Dataset</button><button id="addData">Add Data</button><button id="removeData">Remove Data</button><button id="changeCircleSize">Semi/Full Circle</button>window.chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' };var config = { type: 'doughnut', data: { datasets: [{ data: [ ab_val, BC_val, mb_val, nb_val, nl_val, ], backgroundColor: [ window.chartColors.red, window.chartColors.orange, window.chartColors.yellow, window.chartColors.green, window.chartColors.blue, ], label: 'Dataset 1' }], labels: pro_unique }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Total counts of confirmed cases in Canada' }, animation: { animateScale: true, animateRotate: true } } };window.onload = function() { var ctx = document.getElementById('chart-area').getContext('2d'); window.myDoughnut = new Chart(ctx, config); };document.getElementById('randomizeData').addEventListener('click', function() { config.data.datasets.forEach(function(dataset) { dataset.data = dataset.data.map(function() { return randomScalingFactor(); }); });window.myDoughnut.update(); });var colorNames = Object.keys(window.chartColors); document.getElementById('addDataset').addEventListener('click', function() { var newDataset = { backgroundColor: [], data: [], label: 'New dataset ' + config.data.datasets.length, };for (var index = 0; index < config.data.labels.length; ++index) { newDataset.data.push(randomScalingFactor());var colorName = colorNames[index % colorNames.length]; var newColor = window.chartColors[colorName]; newDataset.backgroundColor.push(newColor); }config.data.datasets.push(newDataset); window.myDoughnut.update(); });document.getElementById('addData').addEventListener('click', function() { if (config.data.datasets.length > 0) { config.data.labels.push('data #' + config.data.labels.length);var colorName = colorNames[config.data.datasets[0].data.length % colorNames.length]; var newColor = window.chartColors[colorName];config.data.datasets.forEach(function(dataset) { dataset.data.push(randomScalingFactor()); dataset.backgroundColor.push(newColor); });window.myDoughnut.update(); } });document.getElementById('removeDataset').addEventListener('click', function() { config.data.datasets.splice(0, 1); window.myDoughnut.update(); });document.getElementById('removeData').addEventListener('click', function() { config.data.labels.splice(-1, 1); // remove the label firstconfig.data.datasets.forEach(function(dataset) { dataset.data.pop(); dataset.backgroundColor.pop(); });window.myDoughnut.update(); });document.getElementById('changeCircleSize').addEventListener('click', function() { if (window.myDoughnut.options.circumference === Math.PI) { window.myDoughnut.options.circumference = 2 * Math.PI; window.myDoughnut.options.rotation = -Math.PI / 2; } else { window.myDoughnut.options.circumference = Math.PI; window.myDoughnut.options.rotation = -Math.PI; }window.myDoughnut.update(); });
From the plot below, we can see that province of New Brunswick has the largest confirmed cases of COVID while Manitoba also shares a similar proportion of confirmed cases. For plot 4 below, it shows the different display of doughnut chart in a semi-circle layout.
First, we need to prepare the dataset for the Bar Line Chart. This chart mainly places focus on the cumulative_cases, cumulative_recovered, cumulative_deaths, and active_cases_change of COVID in Alberta from January to June. To make the values fairly distributed in the same range, I process the cumulative_cases and cumulative_recovered columns and take logs on the arrays.
// get unique value of array function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var date_unique = date.filter( onlyUnique ); var ab_case = [] var ab_recover = [] var ab_deaths = [] var ab_case_mean = [] var ab_case_log = [] var ab_recover_log = []province.forEach((i_pro, index) => { if (i_pro =="Alberta") { ab_case.push(case1[index]); ab_recover.push(recover[index]); ab_deaths.push(deaths[index]); ab_case_mean.push(case_mean[index]); } });// take log on ab_case, ab_recoverab_case.forEach((i_ab, index) => { ab_recover_log.push(Math.log(ab_recover[index])); ab_case_log.push(Math.log(i_ab)); });
In Chat.js, it’s flexible to create mixed charts that are a combination of two or more different chart types. For the following example, I create the bar-line chart with separated specification of type parameter.
new Chart(document.getElementById("canvas"), { type: 'bar', data: { datasets: [{ label: 'log on cumulative_cases in Alberta', backgroundColor: window.chartColors.red, data: ab_case_log, borderColor: 'white', borderWidth: 2 }, { label: 'log on cumulative_recovered in Alberta', backgroundColor: window.chartColors.green, data: ab_recover_log, borderColor: 'white', borderWidth: 2 },{ label: 'cumulative_deaths in Alberta', backgroundColor: window.chartColors.purple, data: ab_deaths, borderColor: 'white', borderWidth: 2 }, { label: 'Month average of active cases in Alberta', data: ab_case_mean, fill: false, borderColor:window.chartColors.blue, borderWidth: 2, // Changes this dataset to become a line type: 'line' }], labels: date_unique }, options: { title: { display: true, text: 'Positive Cases of COVID in provinces of Canada' }, hover: { mode: 'index', intersect: true }, }});
From the bar-line chart below, we can see a sharp increase in the average active cases in April and a dramatic decrease in the average active cases in May. From May to June, even though the number of active cases remains negative, there’s an upward curve showing that people infected with COVID get fewer and fewer.
Flask is a powerful backend that works well with HTML and javascript files. Once the directory is specified with the exact folder, the application would render the page by the specified route.
Chart.JS is a visualization library that supports numerous plots like Bar charts, Line Charts, Area Charts, Doughnut charts, etc. The best thing is that you are able to customize the layout like the hovered information, scale range, x and y-axis labels, and so on.
Chart.JS Documentation Website: https://www.chartjs.org/
|
[
{
"code": null,
"e": 568,
"s": 172,
"text": "When it comes to creating the web with Python, Flask is often the common backend applied by developers. Flask enables HTTP requests’ management and templates rendering. For this blog, we’ll walk through the basic structure of flask and how flask is able to render the template from other webpages. Besides, you’ll learn to load a comma-separated value (CSV) file and visualize it using Chart.js."
},
{
"code": null,
"e": 601,
"s": 568,
"text": "In this article, you will learn:"
},
{
"code": null,
"e": 640,
"s": 601,
"text": "(1) Creating a Basic Flask Application"
},
{
"code": null,
"e": 658,
"s": 640,
"text": "(2) Chart.JS plot"
},
{
"code": null,
"e": 1228,
"s": 658,
"text": "First, we create a .py file to import flask packages and set up flask configuration. Flask would call HTML file from the templates folder without any specified path. In order to direct flask to the right folder, we specify template_folder and static_folder path. In the static folder, it normally stores javascript, CSS files, and images. In the template folder, it normally stores HTML files. Besides, we set app.config equal True for the terminal to show the error messages. In addition, the error message would be popped out in the console under the inspect element."
},
{
"code": null,
"e": 1388,
"s": 1228,
"text": "import flaskapp = flask.Flask(__name__, static_url_path='', static_folder='static', template_folder='template')app.config[\"DEBUG\"] = True"
},
{
"code": null,
"e": 1925,
"s": 1388,
"text": "Then, we move on to define the route for the home page. We are able to give a webpage name that can be passed into HTML. Render_template function would call the HTML file and display it on the specified webpage route. For the second function of user, the name tag embedded in the route can be passed into HTML. For instance, when (http://127.0.0.1:5000/home) is given, the content would be “Hello home”. Also, users are able to assign the route of HTML webpage by using redirect function and put the web page's name in url_for function."
},
{
"code": null,
"e": 2180,
"s": 1925,
"text": "from flask import render_template, redirect, [email protected](\"/home\")def home(): return render_template(\"home.html\")@app.route(\"/<name>\")def user(name): return f\"Hello-- {name}!\"@app.route(\"/admin\")def admin(): return redirect(url_for(\"home\"))"
},
{
"code": null,
"e": 2289,
"s": 2180,
"text": "While the above set-up is completed, you are ready to run flask application by initiating the host and port."
},
{
"code": null,
"e": 2368,
"s": 2289,
"text": "if __name__ == '__main__': app.run(host=\"localhost\", port=8000, debug=True)"
},
{
"code": null,
"e": 2722,
"s": 2368,
"text": "Chart.JS becomes a popular and powerful data visualization library. The library adds its flexibility for users to customize the plots by feeding certain parameters, which meets users’ expectations. The main advantage of creating plots from Chart.js is the basic code structure that allows users to display plots without creating numerous lines of codes."
},
{
"code": null,
"e": 2874,
"s": 2722,
"text": "Before getting started, make sure to call the Chart.js files either by calling the webpage or specifying the local directory with the downloaded files."
},
{
"code": null,
"e": 2965,
"s": 2874,
"text": "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js\"></script>"
},
{
"code": null,
"e": 3082,
"s": 2965,
"text": "We also need to create a canvas node to render the chart and specify the size of the plot with its width and height."
},
{
"code": null,
"e": 3138,
"s": 3082,
"text": "<canvas id=\"myChart\" width=\"400\" height=\"400\"></canvas>"
},
{
"code": null,
"e": 3317,
"s": 3138,
"text": "For the following 4 plots examples using Chart.js, I mainly use the Epidemiological Data from the COVID-19 Outbreak in Canada data source. The data can be accessed with its link."
},
{
"code": null,
"e": 3537,
"s": 3317,
"text": "First, we will load the CSV file by calling the d3 library and the file would be rendered into makeChart function. Next, we define the function with the data parameter and map the columns of data into certain variables."
},
{
"code": null,
"e": 3744,
"s": 3537,
"text": "d3 .csv(“/file/Bar_cases.csv”) .then(makeChart);function makeChart(data) { var country = data.map(function(d) {return d.province;}); var value = data.map(function(d) {return d.cumulative_cases;});"
},
{
"code": null,
"e": 4109,
"s": 3744,
"text": "Then, we create the chart by calling the canvas id through getElementById. Bar Chart is simply generated by specifying the type as the bar (to flip the direction of the bars, set type to horizontalBar). The label of the bar chart is set with the provinces’ names and data are the cumulative cases in May. You are able to create legend and title through parameters."
},
{
"code": null,
"e": 4680,
"s": 4109,
"text": "// Bar chart new Chart(document.getElementById(\"myCanvas\"), { type: 'bar', data: { labels: country, datasets: [ { label: \"Population (millions)\", backgroundColor: [\"#3e95cd\", \"#8e5ea2\",\"#3cba9f\",\"#e8c3b9\",\"#c45850\"], data: value } ] }, options: { legend: { display: false }, title: { display: true, text: 'Total Confirmed Cases of COVID in May' } } });"
},
{
"code": null,
"e": 4871,
"s": 4680,
"text": "Through the bar chart below, we can see the information by the hovered information. Quebec has the most people infected with COVID among 5 provinces, while Ontario is the second highest one."
},
{
"code": null,
"e": 5235,
"s": 4871,
"text": "First, we need to prepare the dataset for the line plot. To create the time-series line plot, we need to filter monthly confirmed cases of COVID19 for each province. OnlyUnique function is to generate the unique values from an array. forEach function is able to locate the same index on the multiple arrays through the iteration of values and indexes on an array."
},
{
"code": null,
"e": 5756,
"s": 5235,
"text": "// get unique value of array function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var mon_unique = month.filter( onlyUnique );province.forEach((pro, index) => { if (pro ==\"Alberta\") { ab_val.push(value[index]); } else if (pro ==\"BC\") { BC_val.push(value[index]); } else if (pro ==\"Manitoba\") { mb_val.push(value[index]); } else if (pro ==\"New Brunswick\") { nb_val.push(value[index]); } else { nl_val.push(value[index]); } });"
},
{
"code": null,
"e": 6125,
"s": 5756,
"text": "Line Chart is simply generated by specifying the type as the line. For each line, we can feed the label and data wrapped in a dataset list. By default, the area under each line is filled with color, covering the area between the line and the x-axis. The color can be removed by specifying (fill: false). Also, the color can be specified with the borderColor parameter."
},
{
"code": null,
"e": 6960,
"s": 6125,
"text": "// Line chart new Chart(document.getElementById(\"myCanvas\"), { type: 'line', data: { labels: mon_unique, datasets: [{ data: ab_val, label: \"Alberta\", borderColor: \"#3e95cd\", fill: false }, { data: BC_val, label: \"BC\", borderColor: \"#8e5ea2\", fill: false }, { data: mb_val, label: \"Manitoba\", borderColor: \"#3cba9f\", fill: false }, { data: nb_val, label: \"New Brunswick\", borderColor: \"#e8c3b9\", fill: false }, { data: nl_val, label: \"NL\", borderColor: \"#c45850\", fill: false } ] }, options: { title: { display: true, text: 'Positive Cases of COVID in provinces of Canada' }, hover: { mode: 'index', intersect: true }, }});"
},
{
"code": null,
"e": 7434,
"s": 6960,
"text": "From the line plot below, 4 provinces except BC are reported with 0 confirmed cases in January and February. From mid-February, there is a gradual increase in confirmed cases in Alberta and BC. Starting in March, a substantial increase of positive cases appear in Alberta as the AB province is the top among the 5 provinces. On the other hand, provinces like MB, NB, and NL are reported with low confirmed COVID cases. In May, the curve is flattened with fewer COVID cases."
},
{
"code": null,
"e": 7585,
"s": 7434,
"text": "First, we need to prepare the dataset for the doughnut plot. Each province array is processed and have the final input of the cumulative cases in May."
},
{
"code": null,
"e": 8475,
"s": 7585,
"text": "//donut chart, get the end of MAy & display the cumulative cases of 5 provinces// get unique value of array function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var pro_unique = province.filter( onlyUnique ); var ab_val = [] var BC_val = [] var mb_val = [] var nb_val = [] var nl_val = []date.forEach((i_dt, index) => { if (i_dt == '2020-05-31' && province[index] ==\"Alberta\") { ab_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] ==\"BC\") { BC_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] ==\"Manitoba\") { mb_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] ==\"New Brunswick\") { nb_val.push(value[index]); } else if (i_dt == '2020-05-31' && province[index] ==\"NL\") { nl_val.push(value[index]); } });"
},
{
"code": null,
"e": 8895,
"s": 8475,
"text": "There are a total of 6 buttons. Button randomizeData enables data randomization while the area of each label can appear in proportion. For the other 4 buttons, they support the function to add or remove the data. Besides, the button like Semi/Full Circle, allows the circle to expand and shrink into fall and half size. Once every button is clicked, it will call the Doughnut.update() function to have the plot updated."
},
{
"code": null,
"e": 12383,
"s": 8895,
"text": "<button id=\"randomizeData\">Randomize Data</button><button id=\"addDataset\">Add Dataset</button><button id=\"removeDataset\">Remove Dataset</button><button id=\"addData\">Add Data</button><button id=\"removeData\">Remove Data</button><button id=\"changeCircleSize\">Semi/Full Circle</button>window.chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' };var config = { type: 'doughnut', data: { datasets: [{ data: [ ab_val, BC_val, mb_val, nb_val, nl_val, ], backgroundColor: [ window.chartColors.red, window.chartColors.orange, window.chartColors.yellow, window.chartColors.green, window.chartColors.blue, ], label: 'Dataset 1' }], labels: pro_unique }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Total counts of confirmed cases in Canada' }, animation: { animateScale: true, animateRotate: true } } };window.onload = function() { var ctx = document.getElementById('chart-area').getContext('2d'); window.myDoughnut = new Chart(ctx, config); };document.getElementById('randomizeData').addEventListener('click', function() { config.data.datasets.forEach(function(dataset) { dataset.data = dataset.data.map(function() { return randomScalingFactor(); }); });window.myDoughnut.update(); });var colorNames = Object.keys(window.chartColors); document.getElementById('addDataset').addEventListener('click', function() { var newDataset = { backgroundColor: [], data: [], label: 'New dataset ' + config.data.datasets.length, };for (var index = 0; index < config.data.labels.length; ++index) { newDataset.data.push(randomScalingFactor());var colorName = colorNames[index % colorNames.length]; var newColor = window.chartColors[colorName]; newDataset.backgroundColor.push(newColor); }config.data.datasets.push(newDataset); window.myDoughnut.update(); });document.getElementById('addData').addEventListener('click', function() { if (config.data.datasets.length > 0) { config.data.labels.push('data #' + config.data.labels.length);var colorName = colorNames[config.data.datasets[0].data.length % colorNames.length]; var newColor = window.chartColors[colorName];config.data.datasets.forEach(function(dataset) { dataset.data.push(randomScalingFactor()); dataset.backgroundColor.push(newColor); });window.myDoughnut.update(); } });document.getElementById('removeDataset').addEventListener('click', function() { config.data.datasets.splice(0, 1); window.myDoughnut.update(); });document.getElementById('removeData').addEventListener('click', function() { config.data.labels.splice(-1, 1); // remove the label firstconfig.data.datasets.forEach(function(dataset) { dataset.data.pop(); dataset.backgroundColor.pop(); });window.myDoughnut.update(); });document.getElementById('changeCircleSize').addEventListener('click', function() { if (window.myDoughnut.options.circumference === Math.PI) { window.myDoughnut.options.circumference = 2 * Math.PI; window.myDoughnut.options.rotation = -Math.PI / 2; } else { window.myDoughnut.options.circumference = Math.PI; window.myDoughnut.options.rotation = -Math.PI; }window.myDoughnut.update(); });"
},
{
"code": null,
"e": 12647,
"s": 12383,
"text": "From the plot below, we can see that province of New Brunswick has the largest confirmed cases of COVID while Manitoba also shares a similar proportion of confirmed cases. For plot 4 below, it shows the different display of doughnut chart in a semi-circle layout."
},
{
"code": null,
"e": 13022,
"s": 12647,
"text": "First, we need to prepare the dataset for the Bar Line Chart. This chart mainly places focus on the cumulative_cases, cumulative_recovered, cumulative_deaths, and active_cases_change of COVID in Alberta from January to June. To make the values fairly distributed in the same range, I process the cumulative_cases and cumulative_recovered columns and take logs on the arrays."
},
{
"code": null,
"e": 13693,
"s": 13022,
"text": "// get unique value of array function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var date_unique = date.filter( onlyUnique ); var ab_case = [] var ab_recover = [] var ab_deaths = [] var ab_case_mean = [] var ab_case_log = [] var ab_recover_log = []province.forEach((i_pro, index) => { if (i_pro ==\"Alberta\") { ab_case.push(case1[index]); ab_recover.push(recover[index]); ab_deaths.push(deaths[index]); ab_case_mean.push(case_mean[index]); } });// take log on ab_case, ab_recoverab_case.forEach((i_ab, index) => { ab_recover_log.push(Math.log(ab_recover[index])); ab_case_log.push(Math.log(i_ab)); });"
},
{
"code": null,
"e": 13906,
"s": 13693,
"text": "In Chat.js, it’s flexible to create mixed charts that are a combination of two or more different chart types. For the following example, I create the bar-line chart with separated specification of type parameter."
},
{
"code": null,
"e": 15144,
"s": 13906,
"text": "new Chart(document.getElementById(\"canvas\"), { type: 'bar', data: { datasets: [{ label: 'log on cumulative_cases in Alberta', backgroundColor: window.chartColors.red, data: ab_case_log, borderColor: 'white', borderWidth: 2 }, { label: 'log on cumulative_recovered in Alberta', backgroundColor: window.chartColors.green, data: ab_recover_log, borderColor: 'white', borderWidth: 2 },{ label: 'cumulative_deaths in Alberta', backgroundColor: window.chartColors.purple, data: ab_deaths, borderColor: 'white', borderWidth: 2 }, { label: 'Month average of active cases in Alberta', data: ab_case_mean, fill: false, borderColor:window.chartColors.blue, borderWidth: 2, // Changes this dataset to become a line type: 'line' }], labels: date_unique }, options: { title: { display: true, text: 'Positive Cases of COVID in provinces of Canada' }, hover: { mode: 'index', intersect: true }, }});"
},
{
"code": null,
"e": 15460,
"s": 15144,
"text": "From the bar-line chart below, we can see a sharp increase in the average active cases in April and a dramatic decrease in the average active cases in May. From May to June, even though the number of active cases remains negative, there’s an upward curve showing that people infected with COVID get fewer and fewer."
},
{
"code": null,
"e": 15653,
"s": 15460,
"text": "Flask is a powerful backend that works well with HTML and javascript files. Once the directory is specified with the exact folder, the application would render the page by the specified route."
},
{
"code": null,
"e": 15918,
"s": 15653,
"text": "Chart.JS is a visualization library that supports numerous plots like Bar charts, Line Charts, Area Charts, Doughnut charts, etc. The best thing is that you are able to customize the layout like the hovered information, scale range, x and y-axis labels, and so on."
}
] |
Pafy - Getting File Size of Stream - GeeksforGeeks
|
20 Jul, 2020
In this article we will see how we can get file size given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. File size is in the form of bytes normally the better the resolution the greater will be the file size.
We can get the pafy object with the help of new method and with the help of allstreams attribute we can get the all the streams available for the video, below is the command to get the pafy object for given video
video = pafy.new(url)
streams = video.allstreams
The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform.
In order to do this we use get_filesize method with the stream object of video
Syntax : stream.get_filesize()
Argument : It takes no argument
Return : It returns integer
Below is the implementation
# importing pafyimport pafy # url of video url = "https://www.youtube.com / watch?v = vG2PNdI8axo" # getting videovideo = pafy.new(url) # getting all the available streamsstreams = video.allstreams # selecting one streamstream = streams[1]# getting file size of streamvalue = stream.get_filesize() # printing the valueprint("File Size in bytes: " + str(value))
Output :
File Size in bytes: 554085
Another example
# importing pafyimport pafy # url of video url = "https://www.youtube.com / watch?v = i6rhnSoK_gc" # getting videovideo = pafy.new(url) # getting all the available streamsstreams = video.allstreams # selecting one streamstream = streams[4] # getting file size of streamvalue = stream.get_filesize() # printing the valueprint("File Size in bytes: " + str(value))
Output :
File Size in bytes: 8125774
Python-Pafy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 24816,
"s": 24788,
"text": "\n20 Jul, 2020"
},
{
"code": null,
"e": 25244,
"s": 24816,
"text": "In this article we will see how we can get file size given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. File size is in the form of bytes normally the better the resolution the greater will be the file size."
},
{
"code": null,
"e": 25457,
"s": 25244,
"text": "We can get the pafy object with the help of new method and with the help of allstreams attribute we can get the all the streams available for the video, below is the command to get the pafy object for given video"
},
{
"code": null,
"e": 25507,
"s": 25457,
"text": "video = pafy.new(url)\nstreams = video.allstreams\n"
},
{
"code": null,
"e": 25675,
"s": 25507,
"text": "The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform."
},
{
"code": null,
"e": 25754,
"s": 25675,
"text": "In order to do this we use get_filesize method with the stream object of video"
},
{
"code": null,
"e": 25785,
"s": 25754,
"text": "Syntax : stream.get_filesize()"
},
{
"code": null,
"e": 25817,
"s": 25785,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 25845,
"s": 25817,
"text": "Return : It returns integer"
},
{
"code": null,
"e": 25873,
"s": 25845,
"text": "Below is the implementation"
},
{
"code": "# importing pafyimport pafy # url of video url = \"https://www.youtube.com / watch?v = vG2PNdI8axo\" # getting videovideo = pafy.new(url) # getting all the available streamsstreams = video.allstreams # selecting one streamstream = streams[1]# getting file size of streamvalue = stream.get_filesize() # printing the valueprint(\"File Size in bytes: \" + str(value))",
"e": 26245,
"s": 25873,
"text": null
},
{
"code": null,
"e": 26254,
"s": 26245,
"text": "Output :"
},
{
"code": null,
"e": 26282,
"s": 26254,
"text": "File Size in bytes: 554085\n"
},
{
"code": null,
"e": 26298,
"s": 26282,
"text": "Another example"
},
{
"code": "# importing pafyimport pafy # url of video url = \"https://www.youtube.com / watch?v = i6rhnSoK_gc\" # getting videovideo = pafy.new(url) # getting all the available streamsstreams = video.allstreams # selecting one streamstream = streams[4] # getting file size of streamvalue = stream.get_filesize() # printing the valueprint(\"File Size in bytes: \" + str(value))",
"e": 26672,
"s": 26298,
"text": null
},
{
"code": null,
"e": 26681,
"s": 26672,
"text": "Output :"
},
{
"code": null,
"e": 26710,
"s": 26681,
"text": "File Size in bytes: 8125774\n"
},
{
"code": null,
"e": 26722,
"s": 26710,
"text": "Python-Pafy"
},
{
"code": null,
"e": 26729,
"s": 26722,
"text": "Python"
},
{
"code": null,
"e": 26827,
"s": 26729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26836,
"s": 26827,
"text": "Comments"
},
{
"code": null,
"e": 26849,
"s": 26836,
"text": "Old Comments"
},
{
"code": null,
"e": 26867,
"s": 26849,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26899,
"s": 26867,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26921,
"s": 26899,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26963,
"s": 26921,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27007,
"s": 26963,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27028,
"s": 27007,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27065,
"s": 27028,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27094,
"s": 27065,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27150,
"s": 27094,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
How to change the 'text-decoration' property with jQuery?
|
To change text decoration property with jQuery, use the jQuery css() property.
You can try to run the following code to change text-decoration property from underline to overline:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").on({
mouseenter: function(){
$(this).css({"text-decoration": "overline"});
}
});
});
</script>
<style>
p {
text-decoration: underline;
}
</style>
</head>
<body>
<p>Move the mouse pointer on the text to remove underline and add overline.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "To change text decoration property with jQuery, use the jQuery css() property."
},
{
"code": null,
"e": 1242,
"s": 1141,
"text": "You can try to run the following code to change text-decoration property from underline to overline:"
},
{
"code": null,
"e": 1252,
"s": 1242,
"text": "Live Demo"
},
{
"code": null,
"e": 1713,
"s": 1252,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"p\").on({\n mouseenter: function(){\n $(this).css({\"text-decoration\": \"overline\"});\n }\n }); \n});\n</script>\n<style>\np {\n text-decoration: underline;\n}\n</style>\n</head>\n<body>\n<p>Move the mouse pointer on the text to remove underline and add overline.</p>\n</body>\n</html>"
}
] |
Red OR Green | Practice | GeeksforGeeks
|
Given a string of length N, made up of only uppercase characters 'R' and 'G', where 'R' stands for Red and 'G' stands for Green.Find out the minimum number of characters you need to change to make the whole string of the same colour.
Example 1:
Input:
N=5
S="RGRGR"
Output:
2
Explanation:
We need to change only the 2nd and
4th(1-index based) characters to 'R',
so that the whole string becomes
the same colour.
Example 2:
Input:
N=7
S="GGGGGGR"
Output:
1
Explanation:
We need to change only the last
character to 'G' to make the string
same-coloured.
Your Task:
You don't need to read input or print anything. Your task is to complete the function RedOrGreen() which takes the Integer N and the string S as input parameters and returns the minimum number of characters that have to be swapped to make the string same-coloured.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1<=N<=105
S consists only of characters 'R' and 'G'.
0
akash22bhin 9 hours
Total Time Taken:
0.31/1.5
int RedOrGreen(int N,string S) { //code here int cR=0,cG=0; for(int i=0;i<N;i++) { if(S[i]=='R') cR++; else cG++; } if(cG>=cR) return cR; else return cG; }
0
aniket6518gadhe2 days ago
JAVA SOLUTION
Total Time Taken:
0.41/1.5
static int RedOrGreen(int N, String S) {
int rCount=0;
for(Character c:S.toCharArray()){
if(c=='R')
rCount++;
}
rCount=Math.min(rCount,N-rCount);
return rCount;
}
0
thaloravinash101 week ago
class Solution: def RedOrGreen(self,N,S): r=0 g=0 for i in S: if i=="R": r=r+1 else: g=g+1 return min(r,g)
0
nishraut72 weeks ago
python code:
class Solution: def RedOrGreen(self,N,S): #code here count_R = 0 count_G = 0 finalcount = 0 for i in S: if i == "G": count_G += 1 else: count_R += 1 if count_G < count_R: finalcount = count_G else: finalcount = count_R return finalcount
+1
sindhumaram121 month ago
class Solution: def RedOrGreen(self,N,S): #code here l=[] l.append(S.count('G')) l.append(S.count('R')) return min(l)
0
rahulrs2 months ago
JAVA EASY CODE.......................
static int RedOrGreen(int N, String S) { //code here int green = 0,red=0; for(int i=0;i<N;i++){ if(S.charAt(i)=='G'){ green++; }else{ red++; } } int change = Math.min(green, red); return change; }
0
akhilkhan0786khan2 months ago
js code
class Solution{ RedOrGreen(n, str){ //code here var Rcount = 0; var Gcount = 0; var sub = n; for(var i = 0; i<n; i++) { if(str[i]=="R") { Rcount++; }else { Gcount++; } } if(Rcount>Gcount) { var x = sub-Rcount; return x; }else { var y = sub-Gcount; return y; } }}
0
tejaschavan81712 months ago
Cpp code
int count1=0; int count2=0; for(int i=0;i<S.size();i++) { if(S[i]=='G') { count1++; }else if(S[i]=='R') { count2++; } } if(count1>count2) { return count2; }else return count1;
0
vikkrammor2 months ago
static int RedOrGreen(int N, String S) {
int red = 0;
int green = 0;
int n = S.length();
for(int i=0; i<n; i++){
if(S.charAt(i) == 'R'){
red++;
}
else{
green++;
}
}
if(red >= green){
return green;
}
else{
return red;
}
}
0
vikkrammor
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 460,
"s": 226,
"text": "Given a string of length N, made up of only uppercase characters 'R' and 'G', where 'R' stands for Red and 'G' stands for Green.Find out the minimum number of characters you need to change to make the whole string of the same colour."
},
{
"code": null,
"e": 471,
"s": 460,
"text": "Example 1:"
},
{
"code": null,
"e": 641,
"s": 471,
"text": "Input:\nN=5\nS=\"RGRGR\"\nOutput:\n2\nExplanation:\nWe need to change only the 2nd and \n4th(1-index based) characters to 'R', \nso that the whole string becomes \nthe same colour."
},
{
"code": null,
"e": 652,
"s": 641,
"text": "Example 2:"
},
{
"code": null,
"e": 783,
"s": 652,
"text": "Input:\nN=7\nS=\"GGGGGGR\"\nOutput:\n1\nExplanation:\nWe need to change only the last \ncharacter to 'G' to make the string \nsame-coloured."
},
{
"code": null,
"e": 1061,
"s": 785,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function RedOrGreen() which takes the Integer N and the string S as input parameters and returns the minimum number of characters that have to be swapped to make the string same-coloured."
},
{
"code": null,
"e": 1123,
"s": 1061,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1189,
"s": 1123,
"text": "Constraints:\n1<=N<=105\nS consists only of characters 'R' and 'G'."
},
{
"code": null,
"e": 1191,
"s": 1189,
"text": "0"
},
{
"code": null,
"e": 1211,
"s": 1191,
"text": "akash22bhin 9 hours"
},
{
"code": null,
"e": 1229,
"s": 1211,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 1238,
"s": 1229,
"text": "0.31/1.5"
},
{
"code": null,
"e": 1539,
"s": 1238,
"text": "int RedOrGreen(int N,string S) { //code here int cR=0,cG=0; for(int i=0;i<N;i++) { if(S[i]=='R') cR++; else cG++; } if(cG>=cR) return cR; else return cG; }"
},
{
"code": null,
"e": 1543,
"s": 1541,
"text": "0"
},
{
"code": null,
"e": 1569,
"s": 1543,
"text": "aniket6518gadhe2 days ago"
},
{
"code": null,
"e": 1583,
"s": 1569,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 1601,
"s": 1583,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 1610,
"s": 1601,
"text": "0.41/1.5"
},
{
"code": null,
"e": 1847,
"s": 1612,
"text": "static int RedOrGreen(int N, String S) {\n int rCount=0;\n for(Character c:S.toCharArray()){\n if(c=='R')\n rCount++;\n }\n rCount=Math.min(rCount,N-rCount);\n return rCount;\n }"
},
{
"code": null,
"e": 1849,
"s": 1847,
"text": "0"
},
{
"code": null,
"e": 1875,
"s": 1849,
"text": "thaloravinash101 week ago"
},
{
"code": null,
"e": 2056,
"s": 1875,
"text": "class Solution: def RedOrGreen(self,N,S): r=0 g=0 for i in S: if i==\"R\": r=r+1 else: g=g+1 return min(r,g)"
},
{
"code": null,
"e": 2058,
"s": 2056,
"text": "0"
},
{
"code": null,
"e": 2079,
"s": 2058,
"text": "nishraut72 weeks ago"
},
{
"code": null,
"e": 2092,
"s": 2079,
"text": "python code:"
},
{
"code": null,
"e": 2482,
"s": 2094,
"text": "class Solution: def RedOrGreen(self,N,S): #code here count_R = 0 count_G = 0 finalcount = 0 for i in S: if i == \"G\": count_G += 1 else: count_R += 1 if count_G < count_R: finalcount = count_G else: finalcount = count_R return finalcount"
},
{
"code": null,
"e": 2485,
"s": 2482,
"text": "+1"
},
{
"code": null,
"e": 2510,
"s": 2485,
"text": "sindhumaram121 month ago"
},
{
"code": null,
"e": 2660,
"s": 2510,
"text": "class Solution: def RedOrGreen(self,N,S): #code here l=[] l.append(S.count('G')) l.append(S.count('R')) return min(l)"
},
{
"code": null,
"e": 2662,
"s": 2660,
"text": "0"
},
{
"code": null,
"e": 2682,
"s": 2662,
"text": "rahulrs2 months ago"
},
{
"code": null,
"e": 2720,
"s": 2682,
"text": "JAVA EASY CODE......................."
},
{
"code": null,
"e": 3015,
"s": 2722,
"text": "static int RedOrGreen(int N, String S) { //code here int green = 0,red=0; for(int i=0;i<N;i++){ if(S.charAt(i)=='G'){ green++; }else{ red++; } } int change = Math.min(green, red); return change; }"
},
{
"code": null,
"e": 3017,
"s": 3015,
"text": "0"
},
{
"code": null,
"e": 3047,
"s": 3017,
"text": "akhilkhan0786khan2 months ago"
},
{
"code": null,
"e": 3055,
"s": 3047,
"text": "js code"
},
{
"code": null,
"e": 3514,
"s": 3057,
"text": "class Solution{ RedOrGreen(n, str){ //code here var Rcount = 0; var Gcount = 0; var sub = n; for(var i = 0; i<n; i++) { if(str[i]==\"R\") { Rcount++; }else { Gcount++; } } if(Rcount>Gcount) { var x = sub-Rcount; return x; }else { var y = sub-Gcount; return y; } }}"
},
{
"code": null,
"e": 3516,
"s": 3514,
"text": "0"
},
{
"code": null,
"e": 3544,
"s": 3516,
"text": "tejaschavan81712 months ago"
},
{
"code": null,
"e": 3553,
"s": 3544,
"text": "Cpp code"
},
{
"code": null,
"e": 3936,
"s": 3553,
"text": " int count1=0; int count2=0; for(int i=0;i<S.size();i++) { if(S[i]=='G') { count1++; }else if(S[i]=='R') { count2++; } } if(count1>count2) { return count2; }else return count1; "
},
{
"code": null,
"e": 3938,
"s": 3936,
"text": "0"
},
{
"code": null,
"e": 3961,
"s": 3938,
"text": "vikkrammor2 months ago"
},
{
"code": null,
"e": 4410,
"s": 3961,
"text": "static int RedOrGreen(int N, String S) {\n int red = 0;\n int green = 0;\n int n = S.length();\n for(int i=0; i<n; i++){\n if(S.charAt(i) == 'R'){\n red++;\n }\n else{\n green++;\n }\n }\n if(red >= green){\n return green;\n }\n else{\n return red;\n }\n }"
},
{
"code": null,
"e": 4412,
"s": 4410,
"text": "0"
},
{
"code": null,
"e": 4423,
"s": 4412,
"text": "vikkrammor"
},
{
"code": null,
"e": 4449,
"s": 4423,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4595,
"s": 4449,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4631,
"s": 4595,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4641,
"s": 4631,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4651,
"s": 4641,
"text": "\nContest\n"
},
{
"code": null,
"e": 4714,
"s": 4651,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4862,
"s": 4714,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5070,
"s": 4862,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5176,
"s": 5070,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JavaScript function to accept a string and mirrors its alphabet
|
We have to write a function that accepts a string and mirrors its alphabet. For example −
If the input is ‘abcd’
The output should be ‘zyxw’
The function simply takes every character and map to the that is (26 - N) alphabets away from
it, where is the 1 based index of that alphabet like 5 for e and 10 for j.
We will use the String.prototype.replace() method here, to match all the English alphabets
irrespective of their case. The full code for this function will be −
const str = 'ABCD';
const mirrorString = str => {
const regex = /[A-Za-z]/g;
return str.replace(regex, char => {
const ascii = char.charCodeAt();
let start, end;
if(ascii > 96){
start = 97;
end = 122;
} else {
start = 65;
end = 90;
}
return String.fromCharCode(end - (ascii-start));
});
}
console.log(mirrorString(str));
console.log(mirrorString('Can we flip this as well'));
console.log(mirrorString('SOME UPPERCASE STUFF'));
The output in the console will be −
ZYXW
Xzm dv uork gsrh zh dvoo
HLNV FKKVIXZHV HGFUU
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "We have to write a function that accepts a string and mirrors its alphabet. For example −"
},
{
"code": null,
"e": 1203,
"s": 1152,
"text": "If the input is ‘abcd’\nThe output should be ‘zyxw’"
},
{
"code": null,
"e": 1372,
"s": 1203,
"text": "The function simply takes every character and map to the that is (26 - N) alphabets away from\nit, where is the 1 based index of that alphabet like 5 for e and 10 for j."
},
{
"code": null,
"e": 1533,
"s": 1372,
"text": "We will use the String.prototype.replace() method here, to match all the English alphabets\nirrespective of their case. The full code for this function will be −"
},
{
"code": null,
"e": 2041,
"s": 1533,
"text": "const str = 'ABCD';\nconst mirrorString = str => {\n const regex = /[A-Za-z]/g;\n return str.replace(regex, char => {\n const ascii = char.charCodeAt();\n let start, end;\n if(ascii > 96){\n start = 97;\n end = 122;\n } else {\n start = 65;\n end = 90;\n }\n return String.fromCharCode(end - (ascii-start));\n });\n}\nconsole.log(mirrorString(str));\nconsole.log(mirrorString('Can we flip this as well'));\nconsole.log(mirrorString('SOME UPPERCASE STUFF'));"
},
{
"code": null,
"e": 2077,
"s": 2041,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2128,
"s": 2077,
"text": "ZYXW\nXzm dv uork gsrh zh dvoo\nHLNV FKKVIXZHV HGFUU"
}
] |
TCP Server-Client implementation in C - GeeksforGeeks
|
02 Feb, 2022
Prerequisites – Socket Programming in C/C++, TCP and UDP server using select, UDP Server-Client implementation in C If we are creating a connection between client and server using TCP then it has few functionality like, TCP is suited for applications that require high reliability, and transmission time is relatively less critical. It is used by other protocols like HTTP, HTTPs, FTP, SMTP, Telnet. TCP rearranges data packets in the order specified. There is absolute guarantee that the data transferred remains intact and arrives in the same order in which it was sent. TCP does Flow Control and requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control. It also does error checking and error recovery. Erroneous packets are retransmitted from the source to the destination.
The entire process can be broken down into following steps:
The entire process can be broken down into following steps:
TCP Server –
using create(), Create TCP socket.using bind(), Bind the socket to server address.using listen(), put the server socket in a passive mode, where it waits for the client to approach the server to make a connectionusing accept(), At this point, connection is established between client and server, and they are ready to transfer data.Go back to Step 3.
using create(), Create TCP socket.
using bind(), Bind the socket to server address.
using listen(), put the server socket in a passive mode, where it waits for the client to approach the server to make a connection
using accept(), At this point, connection is established between client and server, and they are ready to transfer data.
Go back to Step 3.
TCP Client –
Create TCP socket.connect newly created client socket to server.
Create TCP socket.
connect newly created client socket to server.
TCP Server:
C
#include <stdio.h>#include <netdb.h>#include <netinet/in.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <sys/types.h>#define MAX 80#define PORT 8080#define SA struct sockaddr // Function designed for chat between client and server.void func(int connfd){ char buff[MAX]; int n; // infinite loop for chat for (;;) { bzero(buff, MAX); // read the message from client and copy it in buffer read(connfd, buff, sizeof(buff)); // print buffer which contains the client contents printf("From client: %s\t To client : ", buff); bzero(buff, MAX); n = 0; // copy server message in the buffer while ((buff[n++] = getchar()) != '\n') ; // and send that buffer to client write(connfd, buff, sizeof(buff)); // if msg contains "Exit" then server exit and chat ended. if (strncmp("exit", buff, 4) == 0) { printf("Server Exit...\n"); break; } }} // Driver functionint main(){ int sockfd, connfd, len; struct sockaddr_in servaddr, cli; // socket create and verification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf("socket creation failed...\n"); exit(0); } else printf("Socket successfully created..\n"); bzero(&servaddr, sizeof(servaddr)); // assign IP, PORT servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); // Binding newly created socket to given IP and verification if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) { printf("socket bind failed...\n"); exit(0); } else printf("Socket successfully binded..\n"); // Now server is ready to listen and verification if ((listen(sockfd, 5)) != 0) { printf("Listen failed...\n"); exit(0); } else printf("Server listening..\n"); len = sizeof(cli); // Accept the data packet from client and verification connfd = accept(sockfd, (SA*)&cli, &len); if (connfd < 0) { printf("server accept failed...\n"); exit(0); } else printf("server accept the client...\n"); // Function for chatting between client and server func(connfd); // After chatting close the socket close(sockfd);}
TCP Client:
C
#include <netdb.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#define MAX 80#define PORT 8080#define SA struct sockaddrvoid func(int sockfd){ char buff[MAX]; int n; for (;;) { bzero(buff, sizeof(buff)); printf("Enter the string : "); n = 0; while ((buff[n++] = getchar()) != '\n') ; write(sockfd, buff, sizeof(buff)); bzero(buff, sizeof(buff)); read(sockfd, buff, sizeof(buff)); printf("From Server : %s", buff); if ((strncmp(buff, "exit", 4)) == 0) { printf("Client Exit...\n"); break; } }} int main(){ int sockfd, connfd; struct sockaddr_in servaddr, cli; // socket create and verification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf("socket creation failed...\n"); exit(0); } else printf("Socket successfully created..\n"); bzero(&servaddr, sizeof(servaddr)); // assign IP, PORT servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(PORT); // connect the client socket to server socket if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) { printf("connection with the server failed...\n"); exit(0); } else printf("connected to the server..\n"); // function for chat func(sockfd); // close the socket close(sockfd);}
Compilation – Server side: gcc server.c -o server ./server
Client side: gcc client.c -o client ./client
Output –
Server side:
Socket successfully created..
Socket successfully binded..
Server listening..
server accept the client...
From client: hi
To client : hello
From client: exit
To client : exit
Server Exit...
Client side:
Socket successfully created..
connected to the server..
Enter the string : hi
From Server : hello
Enter the string : exit
From Server : exit
Client Exit...
Anviti_Sr
sweetyty
simmytarika5
arubrahjo
sumitgumber28
c-network-programming
system-programming
C Language
Computer Networks
Linux-Unix
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Socket Programming in Python
Caesar Cipher in Cryptography
UDP Server-Client implementation in C
Differences between IPv4 and IPv6
Socket Programming in Java
|
[
{
"code": null,
"e": 36201,
"s": 36173,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 37056,
"s": 36201,
"text": "Prerequisites – Socket Programming in C/C++, TCP and UDP server using select, UDP Server-Client implementation in C If we are creating a connection between client and server using TCP then it has few functionality like, TCP is suited for applications that require high reliability, and transmission time is relatively less critical. It is used by other protocols like HTTP, HTTPs, FTP, SMTP, Telnet. TCP rearranges data packets in the order specified. There is absolute guarantee that the data transferred remains intact and arrives in the same order in which it was sent. TCP does Flow Control and requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control. It also does error checking and error recovery. Erroneous packets are retransmitted from the source to the destination."
},
{
"code": null,
"e": 37117,
"s": 37056,
"text": "The entire process can be broken down into following steps: "
},
{
"code": null,
"e": 37177,
"s": 37117,
"text": "The entire process can be broken down into following steps:"
},
{
"code": null,
"e": 37191,
"s": 37177,
"text": "TCP Server – "
},
{
"code": null,
"e": 37542,
"s": 37191,
"text": "using create(), Create TCP socket.using bind(), Bind the socket to server address.using listen(), put the server socket in a passive mode, where it waits for the client to approach the server to make a connectionusing accept(), At this point, connection is established between client and server, and they are ready to transfer data.Go back to Step 3."
},
{
"code": null,
"e": 37577,
"s": 37542,
"text": "using create(), Create TCP socket."
},
{
"code": null,
"e": 37626,
"s": 37577,
"text": "using bind(), Bind the socket to server address."
},
{
"code": null,
"e": 37757,
"s": 37626,
"text": "using listen(), put the server socket in a passive mode, where it waits for the client to approach the server to make a connection"
},
{
"code": null,
"e": 37878,
"s": 37757,
"text": "using accept(), At this point, connection is established between client and server, and they are ready to transfer data."
},
{
"code": null,
"e": 37897,
"s": 37878,
"text": "Go back to Step 3."
},
{
"code": null,
"e": 37911,
"s": 37897,
"text": "TCP Client – "
},
{
"code": null,
"e": 37976,
"s": 37911,
"text": "Create TCP socket.connect newly created client socket to server."
},
{
"code": null,
"e": 37995,
"s": 37976,
"text": "Create TCP socket."
},
{
"code": null,
"e": 38042,
"s": 37995,
"text": "connect newly created client socket to server."
},
{
"code": null,
"e": 38054,
"s": 38042,
"text": "TCP Server:"
},
{
"code": null,
"e": 38056,
"s": 38054,
"text": "C"
},
{
"code": "#include <stdio.h>#include <netdb.h>#include <netinet/in.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <sys/types.h>#define MAX 80#define PORT 8080#define SA struct sockaddr // Function designed for chat between client and server.void func(int connfd){ char buff[MAX]; int n; // infinite loop for chat for (;;) { bzero(buff, MAX); // read the message from client and copy it in buffer read(connfd, buff, sizeof(buff)); // print buffer which contains the client contents printf(\"From client: %s\\t To client : \", buff); bzero(buff, MAX); n = 0; // copy server message in the buffer while ((buff[n++] = getchar()) != '\\n') ; // and send that buffer to client write(connfd, buff, sizeof(buff)); // if msg contains \"Exit\" then server exit and chat ended. if (strncmp(\"exit\", buff, 4) == 0) { printf(\"Server Exit...\\n\"); break; } }} // Driver functionint main(){ int sockfd, connfd, len; struct sockaddr_in servaddr, cli; // socket create and verification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf(\"socket creation failed...\\n\"); exit(0); } else printf(\"Socket successfully created..\\n\"); bzero(&servaddr, sizeof(servaddr)); // assign IP, PORT servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); // Binding newly created socket to given IP and verification if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) { printf(\"socket bind failed...\\n\"); exit(0); } else printf(\"Socket successfully binded..\\n\"); // Now server is ready to listen and verification if ((listen(sockfd, 5)) != 0) { printf(\"Listen failed...\\n\"); exit(0); } else printf(\"Server listening..\\n\"); len = sizeof(cli); // Accept the data packet from client and verification connfd = accept(sockfd, (SA*)&cli, &len); if (connfd < 0) { printf(\"server accept failed...\\n\"); exit(0); } else printf(\"server accept the client...\\n\"); // Function for chatting between client and server func(connfd); // After chatting close the socket close(sockfd);}",
"e": 40430,
"s": 38056,
"text": null
},
{
"code": null,
"e": 40442,
"s": 40430,
"text": "TCP Client:"
},
{
"code": null,
"e": 40444,
"s": 40442,
"text": "C"
},
{
"code": "#include <netdb.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#define MAX 80#define PORT 8080#define SA struct sockaddrvoid func(int sockfd){ char buff[MAX]; int n; for (;;) { bzero(buff, sizeof(buff)); printf(\"Enter the string : \"); n = 0; while ((buff[n++] = getchar()) != '\\n') ; write(sockfd, buff, sizeof(buff)); bzero(buff, sizeof(buff)); read(sockfd, buff, sizeof(buff)); printf(\"From Server : %s\", buff); if ((strncmp(buff, \"exit\", 4)) == 0) { printf(\"Client Exit...\\n\"); break; } }} int main(){ int sockfd, connfd; struct sockaddr_in servaddr, cli; // socket create and verification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf(\"socket creation failed...\\n\"); exit(0); } else printf(\"Socket successfully created..\\n\"); bzero(&servaddr, sizeof(servaddr)); // assign IP, PORT servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(\"127.0.0.1\"); servaddr.sin_port = htons(PORT); // connect the client socket to server socket if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) { printf(\"connection with the server failed...\\n\"); exit(0); } else printf(\"connected to the server..\\n\"); // function for chat func(sockfd); // close the socket close(sockfd);}",
"e": 41919,
"s": 40444,
"text": null
},
{
"code": null,
"e": 41978,
"s": 41919,
"text": "Compilation – Server side: gcc server.c -o server ./server"
},
{
"code": null,
"e": 42023,
"s": 41978,
"text": "Client side: gcc client.c -o client ./client"
},
{
"code": null,
"e": 42033,
"s": 42023,
"text": "Output – "
},
{
"code": null,
"e": 42047,
"s": 42033,
"text": "Server side: "
},
{
"code": null,
"e": 42248,
"s": 42047,
"text": "Socket successfully created..\nSocket successfully binded..\nServer listening..\nserver accept the client...\nFrom client: hi\n To client : hello\nFrom client: exit\n To client : exit\nServer Exit... "
},
{
"code": null,
"e": 42262,
"s": 42248,
"text": "Client side: "
},
{
"code": null,
"e": 42419,
"s": 42262,
"text": "Socket successfully created..\nconnected to the server..\nEnter the string : hi\nFrom Server : hello\nEnter the string : exit\nFrom Server : exit\nClient Exit... "
},
{
"code": null,
"e": 42429,
"s": 42419,
"text": "Anviti_Sr"
},
{
"code": null,
"e": 42438,
"s": 42429,
"text": "sweetyty"
},
{
"code": null,
"e": 42451,
"s": 42438,
"text": "simmytarika5"
},
{
"code": null,
"e": 42461,
"s": 42451,
"text": "arubrahjo"
},
{
"code": null,
"e": 42475,
"s": 42461,
"text": "sumitgumber28"
},
{
"code": null,
"e": 42497,
"s": 42475,
"text": "c-network-programming"
},
{
"code": null,
"e": 42516,
"s": 42497,
"text": "system-programming"
},
{
"code": null,
"e": 42527,
"s": 42516,
"text": "C Language"
},
{
"code": null,
"e": 42545,
"s": 42527,
"text": "Computer Networks"
},
{
"code": null,
"e": 42556,
"s": 42545,
"text": "Linux-Unix"
},
{
"code": null,
"e": 42574,
"s": 42556,
"text": "Computer Networks"
},
{
"code": null,
"e": 42672,
"s": 42574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42681,
"s": 42672,
"text": "Comments"
},
{
"code": null,
"e": 42694,
"s": 42681,
"text": "Old Comments"
},
{
"code": null,
"e": 42772,
"s": 42694,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 42788,
"s": 42772,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 42811,
"s": 42788,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 42838,
"s": 42811,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 42873,
"s": 42838,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 42902,
"s": 42873,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 42932,
"s": 42902,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 42970,
"s": 42932,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 43004,
"s": 42970,
"text": "Differences between IPv4 and IPv6"
}
] |
How to write MySQL procedure to insert data into a table?
|
To write stored procedure to insert data into a table, at first you need to create a table −
mysql> create table insertDataUsingStoredProcedure
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY ,
-> Name varchar(20),
-> Age int
-> );
Query OK, 0 rows affected (0.51 sec)
Following is the query to write stored procedure to insert data into the table −
mysql> DELIMITER //
mysql> CREATE PROCEDURE StoredProcedureInsertData(IN StudentName varchar(100),IN
StudentAge int)
-> BEGIN
-> insert into insertDataUsingStoredProcedure(Name,Age) values (StudentName, StudentAge );
-> END
-> //
Query OK, 0 rows affected (0.13 sec)
mysql> DELIMITER ;
Following is the query to call the above stored procedure to insert data into the table −
mysql> call StoredProcedureInsertData('Chris',24);
Query OK, 1 row affected (0.18 sec)
Now check the data has been inserted into the table or not −
mysql> select * from insertDataUsingStoredProcedure;
This will produce the following output −
+----+-------+------+
| Id | Name | Age |
+----+-------+------+
| 1 | Chris | 24 |
+----+-------+------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To write stored procedure to insert data into a table, at first you need to create a table −"
},
{
"code": null,
"e": 1349,
"s": 1155,
"text": "mysql> create table insertDataUsingStoredProcedure\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY ,\n -> Name varchar(20),\n -> Age int\n -> );\nQuery OK, 0 rows affected (0.51 sec)"
},
{
"code": null,
"e": 1430,
"s": 1349,
"text": "Following is the query to write stored procedure to insert data into the table −"
},
{
"code": null,
"e": 1728,
"s": 1430,
"text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE StoredProcedureInsertData(IN StudentName varchar(100),IN\nStudentAge int)\n -> BEGIN\n -> insert into insertDataUsingStoredProcedure(Name,Age) values (StudentName, StudentAge );\n -> END\n -> //\nQuery OK, 0 rows affected (0.13 sec)\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 1818,
"s": 1728,
"text": "Following is the query to call the above stored procedure to insert data into the table −"
},
{
"code": null,
"e": 1905,
"s": 1818,
"text": "mysql> call StoredProcedureInsertData('Chris',24);\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 1966,
"s": 1905,
"text": "Now check the data has been inserted into the table or not −"
},
{
"code": null,
"e": 2019,
"s": 1966,
"text": "mysql> select * from insertDataUsingStoredProcedure;"
},
{
"code": null,
"e": 2060,
"s": 2019,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2194,
"s": 2060,
"text": "+----+-------+------+\n| Id | Name | Age |\n+----+-------+------+\n| 1 | Chris | 24 |\n+----+-------+------+\n1 row in set (0.00 sec)"
}
] |
DSA using Java - Tree
|
Tree represents nodes connected by edges. We'll going to discuss binary tree or binary search tree specifically.
Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special condition that each node can have two children at maximum. A binary tree have benefits of both an ordered array and a linked list as search is as quick as in sorted array and insertion or deletion operation are as fast as in linked list.
Following are important terms with respect to tree.
Path − Path refers to sequence of nodes along the edges of a tree.
Path − Path refers to sequence of nodes along the edges of a tree.
Root − Node at the top of the tree is called root. There is only one root per tree and one path from root node to any node.
Root − Node at the top of the tree is called root. There is only one root per tree and one path from root node to any node.
Parent − Any node except root node has one edge upward to a node called parent.
Parent − Any node except root node has one edge upward to a node called parent.
Child − Node below a given node connected by its edge downward is called its child node.
Child − Node below a given node connected by its edge downward is called its child node.
Leaf − Node which does not have any child node is called leaf node.
Leaf − Node which does not have any child node is called leaf node.
Subtree − Subtree represents descendents of a node.
Subtree − Subtree represents descendents of a node.
Visiting − Visiting refers to checking value of a node when control is on the node.
Visiting − Visiting refers to checking value of a node when control is on the node.
Traversing − Traversing means passing through nodes in a specific order.
Traversing − Traversing means passing through nodes in a specific order.
Levels − Level of a node represents the generation of a node. If root node is at level 0, then its next child node is at level 1, its grandchild is at level 2 and so on.
Levels − Level of a node represents the generation of a node. If root node is at level 0, then its next child node is at level 1, its grandchild is at level 2 and so on.
keys − Key represents a value of a node based on which a search operation is to be carried out for a node.
keys − Key represents a value of a node based on which a search operation is to be carried out for a node.
Binary Search tree exibits a special behaviour. A node's left child must have value less than its parent's value and node's right child must have value greater than it's parent value.
We're going to implement tree using node object and connecting them through references.
Following are basic primary operations of a tree which are following.
Search − search an element in a tree.
Search − search an element in a tree.
Insert − insert an element in a tree.
Insert − insert an element in a tree.
Preorder Traversal − traverse a tree in a preorder manner.
Preorder Traversal − traverse a tree in a preorder manner.
Inorder Traversal − traverse a tree in an inorder manner.
Inorder Traversal − traverse a tree in an inorder manner.
Postorder Traversal − traverse a tree in a postorder manner.
Postorder Traversal − traverse a tree in a postorder manner.
Define a node having some data, references to its left and right child nodes.
public class Node {
public int data;
public Node leftChild;
public Node rightChild;
public Node(){}
public void display(){
System.out.print("("+data+ ")");
}
}
Whenever an element is to be search. Start search from root node then if data is less than key value, search element in left subtree otherwise search element in right subtree. Follow the same algorithm for each node.
public Node search(int data){
Node current = root;
System.out.print("Visiting elements: ");
while(current.data != data){
if(current != null)
System.out.print(current.data + " ");
//go to left tree
if(current.data > data){
current = current.leftChild;
}//else go to right tree
else{
current = current.rightChild;
}
//not found
if(current == null){
return null;
}
}
return current;
}
Whenever an element is to be inserted. First locate its proper location. Start search from root node then if data is less than key value, search empty location in left subtree and insert the data. Otherwise search empty location in right subtree and insert the data.
public void insert(int data){
Node tempNode = new Node();
tempNode.data = data;
//if tree is empty
if(root == null){
root = tempNode;
}else{
Node current = root;
Node parent = null;
while(true){
parent = current;
//go to left of the tree
if(data < parent.data){
current = current.leftChild;
//insert to the left
if(current == null){
parent.leftChild = tempNode;
return;
}
}//go to right of the tree
else{
current = current.rightChild;
//insert to the right
if(current == null){
parent.rightChild = tempNode;
return;
}
}
}
}
}
It is a simple three step process.
visit root node
visit root node
traverse left subtree
traverse left subtree
traverse right subtree
traverse right subtree
private void preOrder(Node root){
if(root!=null){
System.out.print(root.data + " ");
preOrder(root.leftChild);
preOrder(root.rightChild);
}
}
It is a simple three step process.
traverse left subtree
traverse left subtree
visit root node
visit root node
traverse right subtree
traverse right subtree
private void inOrder(Node root){
if(root!=null){
inOrder(root.leftChild);
System.out.print(root.data + " ");
inOrder(root.rightChild);
}
}
It is a simple three step process.
traverse left subtree
traverse left subtree
traverse right subtree
traverse right subtree
visit root node
visit root node
private void postOrder(Node root){
if(root!=null){
postOrder(root.leftChild);
postOrder(root.rightChild);
System.out.print(root.data + " ");
}
}
Node.java
package com.tutorialspoint.datastructure;
public class Node {
public int data;
public Node leftChild;
public Node rightChild;
public Node(){}
public void display(){
System.out.print("("+data+ ")");
}
}
Tree.java
package com.tutorialspoint.datastructure;
public class Tree {
private Node root;
public Tree(){
root = null;
}
public Node search(int data){
Node current = root;
System.out.print("Visiting elements: ");
while(current.data != data){
if(current != null)
System.out.print(current.data + " ");
//go to left tree
if(current.data > data){
current = current.leftChild;
}//else go to right tree
else{
current = current.rightChild;
}
//not found
if(current == null){
return null;
}
}
return current;
}
public void insert(int data){
Node tempNode = new Node();
tempNode.data = data;
//if tree is empty
if(root == null){
root = tempNode;
}else{
Node current = root;
Node parent = null;
while(true){
parent = current;
//go to left of the tree
if(data < parent.data){
current = current.leftChild;
//insert to the left
if(current == null){
parent.leftChild = tempNode;
return;
}
}//go to right of the tree
else{
current = current.rightChild;
//insert to the right
if(current == null){
parent.rightChild = tempNode;
return;
}
}
}
}
}
public void traverse(int traversalType){
switch(traversalType){
case 1:
System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2:
System.out.print("\nInorder traversal: ");
inOrder(root);
break;
case 3:
System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
}
}
private void preOrder(Node root){
if(root!=null){
System.out.print(root.data + " ");
preOrder(root.leftChild);
preOrder(root.rightChild);
}
}
private void inOrder(Node root){
if(root!=null){
inOrder(root.leftChild);
System.out.print(root.data + " ");
inOrder(root.rightChild);
}
}
private void postOrder(Node root){
if(root!=null){
postOrder(root.leftChild);
postOrder(root.rightChild);
System.out.print(root.data + " ");
}
}
}
TreeDemo.java
package com.tutorialspoint.datastructure;
public class TreeDemo {
public static void main(String[] args){
Tree tree = new Tree();
/* 11 //Level 0
*/
tree.insert(11);
/* 11 //Level 0
* |
* |---20 //Level 1
*/
tree.insert(20);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
*/
tree.insert(3);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
* |
* |--42 //Level 2
*/
tree.insert(42);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
* |
* |--42 //Level 2
* |
* |--54 //Level 3
*/
tree.insert(54);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
* |
* 16--|--42 //Level 2
* |
* |--54 //Level 3
*/
tree.insert(16);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
* |
* 16--|--42 //Level 2
* |
* 32--|--54 //Level 3
*/
tree.insert(32);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
* | |
* |--9 16--|--42 //Level 2
* |
* 32--|--54 //Level 3
*/
tree.insert(9);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
* | |
* |--9 16--|--42 //Level 2
* | |
* 4--| 32--|--54 //Level 3
*/
tree.insert(4);
/* 11 //Level 0
* |
* 3---|---20 //Level 1
* | |
* |--9 16--|--42 //Level 2
* | |
* 4--|--10 32--|--54 //Level 3
*/
tree.insert(10);
Node node = tree.search(32);
if(node!=null){
System.out.print("Element found.");
node.display();
System.out.println();
}else{
System.out.println("Element not found.");
}
Node node1 = tree.search(2);
if(node1!=null){
System.out.println("Element found.");
node1.display();
System.out.println();
}else{
System.out.println("Element not found.");
}
//pre-order traversal
//root, left ,right
tree.traverse(1);
//in-order traversal
//left, root ,right
tree.traverse(2);
//post order traversal
//left, right, root
tree.traverse(3);
}
}
If we compile and run the above program then it would produce following result −
Visiting elements: 11 20 42 Element found.(32)
Visiting elements: 11 3 Element not found.
Preorder traversal: 11 3 9 4 10 20 16 42 32 54
Inorder traversal: 3 4 9 10 11 16 20 32 42 54
Postorder traversal: 4 10 9 3 16 32 54 42 20 11
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2281,
"s": 2168,
"text": "Tree represents nodes connected by edges. We'll going to discuss binary tree or binary search tree specifically."
},
{
"code": null,
"e": 2619,
"s": 2281,
"text": "Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special condition that each node can have two children at maximum. A binary tree have benefits of both an ordered array and a linked list as search is as quick as in sorted array and insertion or deletion operation are as fast as in linked list. "
},
{
"code": null,
"e": 2671,
"s": 2619,
"text": "Following are important terms with respect to tree."
},
{
"code": null,
"e": 2738,
"s": 2671,
"text": "Path − Path refers to sequence of nodes along the edges of a tree."
},
{
"code": null,
"e": 2805,
"s": 2738,
"text": "Path − Path refers to sequence of nodes along the edges of a tree."
},
{
"code": null,
"e": 2929,
"s": 2805,
"text": "Root − Node at the top of the tree is called root. There is only one root per tree and one path from root node to any node."
},
{
"code": null,
"e": 3053,
"s": 2929,
"text": "Root − Node at the top of the tree is called root. There is only one root per tree and one path from root node to any node."
},
{
"code": null,
"e": 3133,
"s": 3053,
"text": "Parent − Any node except root node has one edge upward to a node called parent."
},
{
"code": null,
"e": 3213,
"s": 3133,
"text": "Parent − Any node except root node has one edge upward to a node called parent."
},
{
"code": null,
"e": 3302,
"s": 3213,
"text": "Child − Node below a given node connected by its edge downward is called its child node."
},
{
"code": null,
"e": 3391,
"s": 3302,
"text": "Child − Node below a given node connected by its edge downward is called its child node."
},
{
"code": null,
"e": 3459,
"s": 3391,
"text": "Leaf − Node which does not have any child node is called leaf node."
},
{
"code": null,
"e": 3527,
"s": 3459,
"text": "Leaf − Node which does not have any child node is called leaf node."
},
{
"code": null,
"e": 3579,
"s": 3527,
"text": "Subtree − Subtree represents descendents of a node."
},
{
"code": null,
"e": 3631,
"s": 3579,
"text": "Subtree − Subtree represents descendents of a node."
},
{
"code": null,
"e": 3715,
"s": 3631,
"text": "Visiting − Visiting refers to checking value of a node when control is on the node."
},
{
"code": null,
"e": 3799,
"s": 3715,
"text": "Visiting − Visiting refers to checking value of a node when control is on the node."
},
{
"code": null,
"e": 3872,
"s": 3799,
"text": "Traversing − Traversing means passing through nodes in a specific order."
},
{
"code": null,
"e": 3945,
"s": 3872,
"text": "Traversing − Traversing means passing through nodes in a specific order."
},
{
"code": null,
"e": 4115,
"s": 3945,
"text": "Levels − Level of a node represents the generation of a node. If root node is at level 0, then its next child node is at level 1, its grandchild is at level 2 and so on."
},
{
"code": null,
"e": 4285,
"s": 4115,
"text": "Levels − Level of a node represents the generation of a node. If root node is at level 0, then its next child node is at level 1, its grandchild is at level 2 and so on."
},
{
"code": null,
"e": 4392,
"s": 4285,
"text": "keys − Key represents a value of a node based on which a search operation is to be carried out for a node."
},
{
"code": null,
"e": 4499,
"s": 4392,
"text": "keys − Key represents a value of a node based on which a search operation is to be carried out for a node."
},
{
"code": null,
"e": 4683,
"s": 4499,
"text": "Binary Search tree exibits a special behaviour. A node's left child must have value less than its parent's value and node's right child must have value greater than it's parent value."
},
{
"code": null,
"e": 4771,
"s": 4683,
"text": "We're going to implement tree using node object and connecting them through references."
},
{
"code": null,
"e": 4841,
"s": 4771,
"text": "Following are basic primary operations of a tree which are following."
},
{
"code": null,
"e": 4879,
"s": 4841,
"text": "Search − search an element in a tree."
},
{
"code": null,
"e": 4917,
"s": 4879,
"text": "Search − search an element in a tree."
},
{
"code": null,
"e": 4955,
"s": 4917,
"text": "Insert − insert an element in a tree."
},
{
"code": null,
"e": 4993,
"s": 4955,
"text": "Insert − insert an element in a tree."
},
{
"code": null,
"e": 5052,
"s": 4993,
"text": "Preorder Traversal − traverse a tree in a preorder manner."
},
{
"code": null,
"e": 5111,
"s": 5052,
"text": "Preorder Traversal − traverse a tree in a preorder manner."
},
{
"code": null,
"e": 5169,
"s": 5111,
"text": "Inorder Traversal − traverse a tree in an inorder manner."
},
{
"code": null,
"e": 5227,
"s": 5169,
"text": "Inorder Traversal − traverse a tree in an inorder manner."
},
{
"code": null,
"e": 5288,
"s": 5227,
"text": "Postorder Traversal − traverse a tree in a postorder manner."
},
{
"code": null,
"e": 5349,
"s": 5288,
"text": "Postorder Traversal − traverse a tree in a postorder manner."
},
{
"code": null,
"e": 5427,
"s": 5349,
"text": "Define a node having some data, references to its left and right child nodes."
},
{
"code": null,
"e": 5613,
"s": 5427,
"text": "public class Node {\n public int data;\n public Node leftChild;\n public Node rightChild;\n\n public Node(){}\n\n public void display(){\n System.out.print(\"(\"+data+ \")\");\n }\n}"
},
{
"code": null,
"e": 5830,
"s": 5613,
"text": "Whenever an element is to be search. Start search from root node then if data is less than key value, search element in left subtree otherwise search element in right subtree. Follow the same algorithm for each node."
},
{
"code": null,
"e": 6370,
"s": 5830,
"text": "public Node search(int data){\n Node current = root;\n System.out.print(\"Visiting elements: \");\n while(current.data != data){\n if(current != null)\n System.out.print(current.data + \" \"); \n //go to left tree\n if(current.data > data){\n current = current.leftChild;\n }//else go to right tree\n else{ \n current = current.rightChild;\n }\n //not found\n if(current == null){\n return null;\n }\n }\n return current;\n}"
},
{
"code": null,
"e": 6638,
"s": 6370,
"text": "Whenever an element is to be inserted. First locate its proper location. Start search from root node then if data is less than key value, search empty location in left subtree and insert the data. Otherwise search empty location in right subtree and insert the data."
},
{
"code": null,
"e": 7472,
"s": 6638,
"text": "public void insert(int data){\n Node tempNode = new Node();\n tempNode.data = data;\n\n //if tree is empty\n if(root == null){\n root = tempNode;\n }else{\n Node current = root;\n Node parent = null;\n\n while(true){ \n parent = current;\n //go to left of the tree\n if(data < parent.data){\n current = current.leftChild; \n //insert to the left\n if(current == null){\n parent.leftChild = tempNode;\n return;\n }\n }//go to right of the tree\n else{\n current = current.rightChild;\n //insert to the right\n if(current == null){\n parent.rightChild = tempNode;\n return;\n }\n }\n } \n }\n} "
},
{
"code": null,
"e": 7507,
"s": 7472,
"text": "It is a simple three step process."
},
{
"code": null,
"e": 7523,
"s": 7507,
"text": "visit root node"
},
{
"code": null,
"e": 7539,
"s": 7523,
"text": "visit root node"
},
{
"code": null,
"e": 7561,
"s": 7539,
"text": "traverse left subtree"
},
{
"code": null,
"e": 7583,
"s": 7561,
"text": "traverse left subtree"
},
{
"code": null,
"e": 7606,
"s": 7583,
"text": "traverse right subtree"
},
{
"code": null,
"e": 7629,
"s": 7606,
"text": "traverse right subtree"
},
{
"code": null,
"e": 7795,
"s": 7629,
"text": "private void preOrder(Node root){\n if(root!=null){\n System.out.print(root.data + \" \");\n preOrder(root.leftChild);\n preOrder(root.rightChild);\n }\n}"
},
{
"code": null,
"e": 7830,
"s": 7795,
"text": "It is a simple three step process."
},
{
"code": null,
"e": 7852,
"s": 7830,
"text": "traverse left subtree"
},
{
"code": null,
"e": 7874,
"s": 7852,
"text": "traverse left subtree"
},
{
"code": null,
"e": 7890,
"s": 7874,
"text": "visit root node"
},
{
"code": null,
"e": 7906,
"s": 7890,
"text": "visit root node"
},
{
"code": null,
"e": 7929,
"s": 7906,
"text": "traverse right subtree"
},
{
"code": null,
"e": 7952,
"s": 7929,
"text": "traverse right subtree"
},
{
"code": null,
"e": 8127,
"s": 7952,
"text": "private void inOrder(Node root){\n if(root!=null){\n inOrder(root.leftChild);\n System.out.print(root.data + \" \"); \n inOrder(root.rightChild);\n }\n}"
},
{
"code": null,
"e": 8162,
"s": 8127,
"text": "It is a simple three step process."
},
{
"code": null,
"e": 8184,
"s": 8162,
"text": "traverse left subtree"
},
{
"code": null,
"e": 8206,
"s": 8184,
"text": "traverse left subtree"
},
{
"code": null,
"e": 8229,
"s": 8206,
"text": "traverse right subtree"
},
{
"code": null,
"e": 8252,
"s": 8229,
"text": "traverse right subtree"
},
{
"code": null,
"e": 8268,
"s": 8252,
"text": "visit root node"
},
{
"code": null,
"e": 8284,
"s": 8268,
"text": "visit root node"
},
{
"code": null,
"e": 8465,
"s": 8284,
"text": "private void postOrder(Node root){\n if(root!=null){ \n postOrder(root.leftChild);\n postOrder(root.rightChild);\n System.out.print(root.data + \" \");\n }\n}"
},
{
"code": null,
"e": 8475,
"s": 8465,
"text": "Node.java"
},
{
"code": null,
"e": 8704,
"s": 8475,
"text": "package com.tutorialspoint.datastructure;\n\npublic class Node {\n public int data;\n public Node leftChild;\n public Node rightChild;\n\n public Node(){}\n\n public void display(){\n System.out.print(\"(\"+data+ \")\");\n }\n}"
},
{
"code": null,
"e": 8714,
"s": 8704,
"text": "Tree.java"
},
{
"code": null,
"e": 11428,
"s": 8714,
"text": "package com.tutorialspoint.datastructure;\n\npublic class Tree {\n private Node root;\n\n public Tree(){\n root = null;\n }\n \n public Node search(int data){\n Node current = root;\n System.out.print(\"Visiting elements: \");\n while(current.data != data){\n if(current != null)\n System.out.print(current.data + \" \"); \n //go to left tree\n if(current.data > data){\n current = current.leftChild;\n }//else go to right tree\n else{ \n current = current.rightChild;\n }\n //not found\n if(current == null){\n return null;\n }\n }\n return current;\n }\n\n public void insert(int data){\n Node tempNode = new Node();\n tempNode.data = data;\n\n //if tree is empty\n if(root == null){\n root = tempNode;\n }else{\n Node current = root;\n Node parent = null;\n\n while(true){ \n parent = current;\n //go to left of the tree\n if(data < parent.data){\n current = current.leftChild; \n //insert to the left\n if(current == null){\n parent.leftChild = tempNode;\n return;\n }\n }//go to right of the tree\n else{\n current = current.rightChild;\n //insert to the right\n if(current == null){\n parent.rightChild = tempNode;\n return;\n }\n }\n } \n }\n } \n\n public void traverse(int traversalType){\n switch(traversalType){\n case 1:\n System.out.print(\"\\nPreorder traversal: \");\n preOrder(root);\n break;\n case 2:\n System.out.print(\"\\nInorder traversal: \");\n inOrder(root);\n break;\n case 3:\n System.out.print(\"\\nPostorder traversal: \");\n postOrder(root);\n break;\n } \n } \n\n private void preOrder(Node root){\n if(root!=null){\n System.out.print(root.data + \" \");\n preOrder(root.leftChild);\n preOrder(root.rightChild);\n }\n }\n\n private void inOrder(Node root){\n if(root!=null){\n inOrder(root.leftChild);\n System.out.print(root.data + \" \"); \n inOrder(root.rightChild);\n }\n }\n\n private void postOrder(Node root){\n if(root!=null){ \n postOrder(root.leftChild);\n postOrder(root.rightChild);\n System.out.print(root.data + \" \");\n }\n }\n}"
},
{
"code": null,
"e": 11442,
"s": 11428,
"text": "TreeDemo.java"
},
{
"code": null,
"e": 15193,
"s": 11442,
"text": "package com.tutorialspoint.datastructure;\n\npublic class TreeDemo {\n public static void main(String[] args){\n Tree tree = new Tree();\n\n /* 11 //Level 0\n */\n tree.insert(11);\n /* 11 //Level 0\n * |\n * |---20 //Level 1\n */\n tree.insert(20);\n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n */\n tree.insert(3); \n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n * |\n * |--42 //Level 2\n */\n tree.insert(42);\n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n * |\n * |--42 //Level 2\n * |\n * |--54 //Level 3\n */\n tree.insert(54);\n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n * |\n * 16--|--42 //Level 2\n * |\n * |--54 //Level 3\n */\n tree.insert(16);\n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n * |\n * 16--|--42 //Level 2\n * |\n * 32--|--54 //Level 3\n */\n tree.insert(32);\n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n * | |\n * |--9 16--|--42 //Level 2\n * |\n * 32--|--54 //Level 3\n */\n tree.insert(9);\n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n * | |\n * |--9 16--|--42 //Level 2\n * | |\n * 4--| 32--|--54 //Level 3\n */\n tree.insert(4);\n /* 11 //Level 0\n * |\n * 3---|---20 //Level 1\n * | |\n * |--9 16--|--42 //Level 2\n * | |\n * 4--|--10 32--|--54 //Level 3\n */\n tree.insert(10);\n Node node = tree.search(32);\n if(node!=null){\n System.out.print(\"Element found.\");\n node.display();\n System.out.println();\n }else{\n System.out.println(\"Element not found.\");\n }\n\n Node node1 = tree.search(2);\n if(node1!=null){\n System.out.println(\"Element found.\");\n node1.display();\n System.out.println();\n }else{\n System.out.println(\"Element not found.\");\n } \n\n //pre-order traversal\n //root, left ,right\n tree.traverse(1);\n //in-order traversal\n //left, root ,right\n tree.traverse(2);\n //post order traversal\n //left, right, root\n tree.traverse(3); \n }\n}"
},
{
"code": null,
"e": 15274,
"s": 15193,
"text": "If we compile and run the above program then it would produce following result −"
},
{
"code": null,
"e": 15509,
"s": 15274,
"text": "Visiting elements: 11 20 42 Element found.(32)\nVisiting elements: 11 3 Element not found.\n\nPreorder traversal: 11 3 9 4 10 20 16 42 32 54 \nInorder traversal: 3 4 9 10 11 16 20 32 42 54 \nPostorder traversal: 4 10 9 3 16 32 54 42 20 11\n"
},
{
"code": null,
"e": 15516,
"s": 15509,
"text": " Print"
},
{
"code": null,
"e": 15527,
"s": 15516,
"text": " Add Notes"
}
] |
How to get a number of days in a specified month using JavaScript?
|
To get numbers of days in a month, use the getDate() method and get the days.
You can try to run the following code to get a number of days in a month −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var days = function(month,year) {
return new Date(year, month, 0).getDate();
};
document.write("Days in July: "+days(7, 2012)); // July month
document.write("<br>Days in September: "+days(9, 2012)); // September Month
</script>
</body>
</html>
Days in July: 31
Days in September: 30
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To get numbers of days in a month, use the getDate() method and get the days."
},
{
"code": null,
"e": 1215,
"s": 1140,
"text": "You can try to run the following code to get a number of days in a month −"
},
{
"code": null,
"e": 1225,
"s": 1215,
"text": "Live Demo"
},
{
"code": null,
"e": 1559,
"s": 1225,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var days = function(month,year) {\n return new Date(year, month, 0).getDate();\n };\n document.write(\"Days in July: \"+days(7, 2012)); // July month\n document.write(\"<br>Days in September: \"+days(9, 2012)); // September Month\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1598,
"s": 1559,
"text": "Days in July: 31\nDays in September: 30"
}
] |
How to Use the Google Places API for Location Analysis and More | by Jordan Bean | Towards Data Science
|
One topic in analytics that interests me is location analytics and thinking about how to bring a more data-driven approach to location scouting, especially for smaller companies that don’t have the resources of, say, a Target or Starbucks. I’ve written a couple of articles (here, here, and here) about different approaches we can take and examples of how to put them into practice.
As a part of a recent consulting project, I found myself searching how to gather location-level competitive information. Not just how many competitors exist in a region, but at a specific street level. Further, the information available from official sources didn’t work for this business because the categorization was too broad and would include companies this business wouldn’t consider like-for-like competitors.
During this search, I came across the Google Places API. Imagine you want to find a coffee shop near you. You head to Google Maps and do a freeform search for coffee. Several pins pop up with local results that match your search.
When you click on one, it displays some helpful information about the location, like its Google Reviews rating, number of reviews, price category (the single $ next to the reviews), address, and more.
The Google Places API effectively executes this search for you within the specified parameters and returns the results for each location that appears from the search. This allows us to pull information on any business type that appears in a Google Maps search in any location where Google Maps operates (which, according to Google, is 200+ countries and 99% global coverage).
As someone without a programming background, I found it a little difficult to try and interpret how to use the API for the first time and to understand how pricing works (it’s not free, but they have recurring monthly credits that give you substantial access before you start paying).
Below, I’ll lay out easy-to-follow steps on how to access the API to use the data for your own projects and purposes. As an example I’m going to walk through the process I used to pull coffee shop locations in a series of zip codes as a part of a hypothetical location analysis for Starbucks.
First thing first is to register for a Google Cloud account. Upon signing up, you may receive a $300 credit in addition to a free $200 per month in credits.
Once you’ve made an account and are on the Google Cloud platform, you’ll want to go to use the drop down navigation in the top left and choose API & Services > Credentials. Once there, you’ll want to hit Create Credentials on the top followed by API key. This will generate an alphanumeric string that identifies your Google Cloud account when you make a call to the API.
We’ll use the credential later when making a call to the Places API, but for now, that’s all you need to get going!
Once you have your API credential, the next part of the process can be done in the programming language of your choice. I’ve used Python but if you’re an R user you can very easily modify the last steps of the process to be done with R code.
Though intimidating at first, the Places API Documentation has all of the information you need to execute the call to the API with your specified parameters.
Since we’ll be executing an “ambiguous text string” (i.e. not searching for a specific location but rather for coffee shops generally), I’ll cover how to use the Text Search requests within the Places documentation/API.
To make a call to the API, we need to construct a URL string. Each required and optional parameter that we want to use needs to be included in the string. We can find each of the parameter options, what they are, and how to use them under the Optional Parameters section of the documentation.
To construct the string, let’s go step-by-step to see what’s actually happening and how to use it. Most of these are optional parameters that you can switch out depending on your use case but the essence of how to use any parameters in the documentation is the same.
https://maps.googleapis.com/maps/api/place/textsearch/
The above connects to the Google Maps API (maps.googleapis.com/maps/api) and establishes that we want to use the place API (/place) and the text search (/textsearch) component of the Places API.
https://maps.googleapis.com/maps/api/place/textsearch/output_type?
the output_type? defines how we want the output to be created. The options are json or xml, and you’ll simply replace output_type? with either json? or xml? depending on your choice.
https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query
The query parameter defines our “ambiguous” search term. We separate any words with a plus sign. So, to search for coffee shop, we’ll replace your_query with coffee+shop.
https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude
We separate parameters with the & symbol. We can define our desired location by providing a latitude and longitude coordinate. This will be the center point for the search. You could also put a location in your search term and skip the lat/lon, something like “coffee+shop+raleigh+nc”.
https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters
The radius parameters define how wide the search will occur. To search within 1,000 meters from the latitude and longitude coordinate, we can replace the number of meters with 1000 (don’t use a comma in the string). A higher radius will cover a wider area. That said, it’s also susceptible to missing locations.
Think about when you zoom out on a Google Maps search — you’ll get a wider range of locations but not as many actually pop up. Check out the images below — on the right-hand side, we have a wider Zoom radius for the search. We get more results, but some from the left-hand image don’t show up even though they’re still in the search area. Test a couple of different radiuses to see what works best for your use case. A smaller radius will give you more accurate results but also take longer to run and cost more as a result of making more calls to the API.
https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters®ion=region_code
Region code is a 2-digit code for the country where you want to search. For example, working with a UK company I used the code uk, while in the United States, we could use the region code of us.
https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters®ion=region_code&type=establishment_type
The type parameter allows us to specify the type of establishment as tagged in the Google data. For coffee shops, we can provide bakery and café as types to ensure that we don’t get results that aren’t relevant. The full list of types can be found here. We separate types with a comma and no space. For bakeries and cafe, the type parameter would be bakery,cafe.
https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters®ion=region_code&type=establishment_type&key=YOUR_API_KEY
Last but not least is entering the API key. Use the API key created earlier in this parameter.
Bring it all together and you get something like this that was used for this project:
"https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee+shop&location=35.792491,-78.653009&radius=2000®ion=us&type=cafe,bakery&key=MY_API_KEY"
Many of these are optional parameters that may or may not be relevant for your use, but the essence of the API is choosing your relevant parameters, entering the required value, and separating your parameters with the & symbol. All required and optional parameters can be found under the Text Search header of the documentation page.
Once we’ve constructed our URL string, we access and parse the information using a mix of basic coding and web scrapes. Below is how I approached it but there are likely more efficient ways to pull it. You’ll need the requests, json, and time packages.
In the code shortly below, I start by establishing an empty list to place the results and an empty dictionary for future parameters, then establish the URL we just created as its own variable.
I send a URL request using requests.get then, since I used a json output, use json.loads on the result to translate the URL output to a workable json output. I append the results to the empty list that I created then put in a brief pause before making the next call using time.sleep(2).
Each call to the API returns up to 20 results per page and up to 3 total pages for a total of 60 results. The time.sleep argument is required as the API will not return results if you try to just send all of your requests at once without a break.
The while loop recognizes when there are additional results in the call and makes the proper API call to also grab those by adding the next page token parameter to the empty dictionary.
import requestsimport jsonimport timecoffee_shops = []params = {} endpoint_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee+shop&location=35.7790905,-78.642413&radius=2000®ion=us&type=cafe,bakery&key=MY_API_KEY" res = requests.get(endpoint_url, params = params)results = json.loads(res.content)coffee_shops.extend(results['results'])time.sleep(2)while "next_page_token" in results: params['pagetoken'] = results['next_page_token'], res = requests.get(endpoint_url, params = params) results = json.loads(res.content) coffee_shops.extend(results['results']) time.sleep(2)
The output is a list of dictionaries where each dictionary contains the information for a single coffee shop.
We can pull all kinds of information from this, including the address, latitude/longitude coordinates, business name, price level, rating, number of ratings, photos, and more. Depending on your use case you can use all or some of this data.
To extract the information in the dictionaries, I established an empty list for each of the fields that I wanted to extract, then wrote a simple for loop that accesses each shop (i.e. dictionary) by index and the relevant fields, then added that value to list. Finally, you can convert the output to a data frame. Since I was looping through several zip codes to do searches, I then appended that data frame to a master data frame and constructed a new column to filter out duplicates to only keep unique values.
Just like that, we have a clean, ready-to-use data frame with all of our data elements in a cleanly formatted table!
If you’re using R or another programming language, you’ll create the URL string the same then adjust the code to do a URL request, set up empty vectors as opposed to lists, and so forth.
I’ve only scratched the surface with how the output can be used and there are several exciting possibilities both for location analysis or other use cases.
One of the ways I used this in a separate project was using a geopandas spatial join to map the latitude/longitude coordinates to a custom output level then assessing competition within each of those bounded areas. We can also look at customer satisfaction, in addition to competitive density, using the weighted average rating within a geographic area.
A simple and powerful tool is to drop this data onto a Tableau map to see exactly where competitors are (and aren’t) located. This can be combined with a demographic analysis to prioritize which locations have the right demographics for your business to succeed, then see exactly where the competition is to avoid cannibalization or overlap.
The Places API is among the more expensive of the Google Maps API, but there’s ample work you can do with it before having to go out-of-pocket. When I signed up, there was a $300 credit that had to be used within 3 months. Google also provides a free $200 credit every single month. This doesn’t carry over, so you have up to $200 to use each month which then resets.
An approximate rule of thumb for the API is that it will cost about $40 for every 1,000 API requests. Remember, you can get up to 20 locations per request, so you can get up to 20,000 locations for $40. With the $200 monthly credit, this equates to about 5,000 free requests before you start paying.
Full pricing details are available here, but an example is below for the Text Search API. We cannot control which data points are returned; the Places, Basic Data, Contact Data, and Atmosphere Data are all returned for each API call.
One last note on pricing that I didn’t understand at first is that each time you submit a URL string to pull information, it can be up to 3 total requests. I mentioned above that each URL call provides up to 20 results across 3 pages. To access each additional page is a new request to the API. So, to get all 60 results will be considered 3 total requests to the API.
I’m excited by the possibilities unlocked by understanding how to access and work with the data from this API. Across my time using it I’ve found a couple pros and cons to where and how the data can be used.
The optimal use case is for a targeted search in a narrow geographic area. In dense places like a city with broad search terms like coffee shop, you need to get very narrow in your search radius, as low as 500 meters for best results. The way I’ve accounted for this is to get bounded lat/lon geographic areas, like a zip code, and write code to do a grid search across that location that iteratively executes the search at staggered lat/lon entries with a small search radius, then filters out duplicate results on the back end.
This approach is not always the best option for wide search areas as the number of requests to the API may be excessive/expensive and time consuming (remember, it’s a 2-second break after each call, so 1,000 calls to the API will take 2,000+ seconds/more than 30 minutes).
It’s best to start by using a handful of targeted search areas, testing the code and results (and understanding how pricing works), then expanding out to a broader geographic area.
Do you have other thoughts on how the data can be used? Interested in learning more or connecting? Reach out to me on LinkedIn or by email at [email protected].
|
[
{
"code": null,
"e": 555,
"s": 172,
"text": "One topic in analytics that interests me is location analytics and thinking about how to bring a more data-driven approach to location scouting, especially for smaller companies that don’t have the resources of, say, a Target or Starbucks. I’ve written a couple of articles (here, here, and here) about different approaches we can take and examples of how to put them into practice."
},
{
"code": null,
"e": 972,
"s": 555,
"text": "As a part of a recent consulting project, I found myself searching how to gather location-level competitive information. Not just how many competitors exist in a region, but at a specific street level. Further, the information available from official sources didn’t work for this business because the categorization was too broad and would include companies this business wouldn’t consider like-for-like competitors."
},
{
"code": null,
"e": 1202,
"s": 972,
"text": "During this search, I came across the Google Places API. Imagine you want to find a coffee shop near you. You head to Google Maps and do a freeform search for coffee. Several pins pop up with local results that match your search."
},
{
"code": null,
"e": 1403,
"s": 1202,
"text": "When you click on one, it displays some helpful information about the location, like its Google Reviews rating, number of reviews, price category (the single $ next to the reviews), address, and more."
},
{
"code": null,
"e": 1779,
"s": 1403,
"text": "The Google Places API effectively executes this search for you within the specified parameters and returns the results for each location that appears from the search. This allows us to pull information on any business type that appears in a Google Maps search in any location where Google Maps operates (which, according to Google, is 200+ countries and 99% global coverage)."
},
{
"code": null,
"e": 2064,
"s": 1779,
"text": "As someone without a programming background, I found it a little difficult to try and interpret how to use the API for the first time and to understand how pricing works (it’s not free, but they have recurring monthly credits that give you substantial access before you start paying)."
},
{
"code": null,
"e": 2357,
"s": 2064,
"text": "Below, I’ll lay out easy-to-follow steps on how to access the API to use the data for your own projects and purposes. As an example I’m going to walk through the process I used to pull coffee shop locations in a series of zip codes as a part of a hypothetical location analysis for Starbucks."
},
{
"code": null,
"e": 2514,
"s": 2357,
"text": "First thing first is to register for a Google Cloud account. Upon signing up, you may receive a $300 credit in addition to a free $200 per month in credits."
},
{
"code": null,
"e": 2886,
"s": 2514,
"text": "Once you’ve made an account and are on the Google Cloud platform, you’ll want to go to use the drop down navigation in the top left and choose API & Services > Credentials. Once there, you’ll want to hit Create Credentials on the top followed by API key. This will generate an alphanumeric string that identifies your Google Cloud account when you make a call to the API."
},
{
"code": null,
"e": 3002,
"s": 2886,
"text": "We’ll use the credential later when making a call to the Places API, but for now, that’s all you need to get going!"
},
{
"code": null,
"e": 3244,
"s": 3002,
"text": "Once you have your API credential, the next part of the process can be done in the programming language of your choice. I’ve used Python but if you’re an R user you can very easily modify the last steps of the process to be done with R code."
},
{
"code": null,
"e": 3402,
"s": 3244,
"text": "Though intimidating at first, the Places API Documentation has all of the information you need to execute the call to the API with your specified parameters."
},
{
"code": null,
"e": 3622,
"s": 3402,
"text": "Since we’ll be executing an “ambiguous text string” (i.e. not searching for a specific location but rather for coffee shops generally), I’ll cover how to use the Text Search requests within the Places documentation/API."
},
{
"code": null,
"e": 3915,
"s": 3622,
"text": "To make a call to the API, we need to construct a URL string. Each required and optional parameter that we want to use needs to be included in the string. We can find each of the parameter options, what they are, and how to use them under the Optional Parameters section of the documentation."
},
{
"code": null,
"e": 4182,
"s": 3915,
"text": "To construct the string, let’s go step-by-step to see what’s actually happening and how to use it. Most of these are optional parameters that you can switch out depending on your use case but the essence of how to use any parameters in the documentation is the same."
},
{
"code": null,
"e": 4237,
"s": 4182,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/"
},
{
"code": null,
"e": 4432,
"s": 4237,
"text": "The above connects to the Google Maps API (maps.googleapis.com/maps/api) and establishes that we want to use the place API (/place) and the text search (/textsearch) component of the Places API."
},
{
"code": null,
"e": 4499,
"s": 4432,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/output_type?"
},
{
"code": null,
"e": 4682,
"s": 4499,
"text": "the output_type? defines how we want the output to be created. The options are json or xml, and you’ll simply replace output_type? with either json? or xml? depending on your choice."
},
{
"code": null,
"e": 4765,
"s": 4682,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query"
},
{
"code": null,
"e": 4936,
"s": 4765,
"text": "The query parameter defines our “ambiguous” search term. We separate any words with a plus sign. So, to search for coffee shop, we’ll replace your_query with coffee+shop."
},
{
"code": null,
"e": 5047,
"s": 4936,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude"
},
{
"code": null,
"e": 5333,
"s": 5047,
"text": "We separate parameters with the & symbol. We can define our desired location by providing a latitude and longitude coordinate. This will be the center point for the search. You could also put a location in your search term and skip the lat/lon, something like “coffee+shop+raleigh+nc”."
},
{
"code": null,
"e": 5468,
"s": 5333,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters"
},
{
"code": null,
"e": 5780,
"s": 5468,
"text": "The radius parameters define how wide the search will occur. To search within 1,000 meters from the latitude and longitude coordinate, we can replace the number of meters with 1000 (don’t use a comma in the string). A higher radius will cover a wider area. That said, it’s also susceptible to missing locations."
},
{
"code": null,
"e": 6337,
"s": 5780,
"text": "Think about when you zoom out on a Google Maps search — you’ll get a wider range of locations but not as many actually pop up. Check out the images below — on the right-hand side, we have a wider Zoom radius for the search. We get more results, but some from the left-hand image don’t show up even though they’re still in the search area. Test a couple of different radiuses to see what works best for your use case. A smaller radius will give you more accurate results but also take longer to run and cost more as a result of making more calls to the API."
},
{
"code": null,
"e": 6491,
"s": 6337,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters®ion=region_code"
},
{
"code": null,
"e": 6686,
"s": 6491,
"text": "Region code is a 2-digit code for the country where you want to search. For example, working with a UK company I used the code uk, while in the United States, we could use the region code of us."
},
{
"code": null,
"e": 6864,
"s": 6686,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters®ion=region_code&type=establishment_type"
},
{
"code": null,
"e": 7228,
"s": 6864,
"text": "The type parameter allows us to specify the type of establishment as tagged in the Google data. For coffee shops, we can provide bakery and café as types to ensure that we don’t get results that aren’t relevant. The full list of types can be found here. We separate types with a comma and no space. For bakeries and cafe, the type parameter would be bakery,cafe."
},
{
"code": null,
"e": 7423,
"s": 7228,
"text": "https://maps.googleapis.com/maps/api/place/textsearch/output_type?query=your_query&location=latitude,longitude&radius=number_of_meters®ion=region_code&type=establishment_type&key=YOUR_API_KEY"
},
{
"code": null,
"e": 7518,
"s": 7423,
"text": "Last but not least is entering the API key. Use the API key created earlier in this parameter."
},
{
"code": null,
"e": 7604,
"s": 7518,
"text": "Bring it all together and you get something like this that was used for this project:"
},
{
"code": null,
"e": 7767,
"s": 7604,
"text": "\"https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee+shop&location=35.792491,-78.653009&radius=2000®ion=us&type=cafe,bakery&key=MY_API_KEY\""
},
{
"code": null,
"e": 8101,
"s": 7767,
"text": "Many of these are optional parameters that may or may not be relevant for your use, but the essence of the API is choosing your relevant parameters, entering the required value, and separating your parameters with the & symbol. All required and optional parameters can be found under the Text Search header of the documentation page."
},
{
"code": null,
"e": 8354,
"s": 8101,
"text": "Once we’ve constructed our URL string, we access and parse the information using a mix of basic coding and web scrapes. Below is how I approached it but there are likely more efficient ways to pull it. You’ll need the requests, json, and time packages."
},
{
"code": null,
"e": 8547,
"s": 8354,
"text": "In the code shortly below, I start by establishing an empty list to place the results and an empty dictionary for future parameters, then establish the URL we just created as its own variable."
},
{
"code": null,
"e": 8834,
"s": 8547,
"text": "I send a URL request using requests.get then, since I used a json output, use json.loads on the result to translate the URL output to a workable json output. I append the results to the empty list that I created then put in a brief pause before making the next call using time.sleep(2)."
},
{
"code": null,
"e": 9081,
"s": 8834,
"text": "Each call to the API returns up to 20 results per page and up to 3 total pages for a total of 60 results. The time.sleep argument is required as the API will not return results if you try to just send all of your requests at once without a break."
},
{
"code": null,
"e": 9267,
"s": 9081,
"text": "The while loop recognizes when there are additional results in the call and makes the proper API call to also grab those by adding the next page token parameter to the empty dictionary."
},
{
"code": null,
"e": 9900,
"s": 9267,
"text": "import requestsimport jsonimport timecoffee_shops = []params = {} endpoint_url = \"https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee+shop&location=35.7790905,-78.642413&radius=2000®ion=us&type=cafe,bakery&key=MY_API_KEY\" res = requests.get(endpoint_url, params = params)results = json.loads(res.content)coffee_shops.extend(results['results'])time.sleep(2)while \"next_page_token\" in results: params['pagetoken'] = results['next_page_token'], res = requests.get(endpoint_url, params = params) results = json.loads(res.content) coffee_shops.extend(results['results']) time.sleep(2)"
},
{
"code": null,
"e": 10010,
"s": 9900,
"text": "The output is a list of dictionaries where each dictionary contains the information for a single coffee shop."
},
{
"code": null,
"e": 10251,
"s": 10010,
"text": "We can pull all kinds of information from this, including the address, latitude/longitude coordinates, business name, price level, rating, number of ratings, photos, and more. Depending on your use case you can use all or some of this data."
},
{
"code": null,
"e": 10764,
"s": 10251,
"text": "To extract the information in the dictionaries, I established an empty list for each of the fields that I wanted to extract, then wrote a simple for loop that accesses each shop (i.e. dictionary) by index and the relevant fields, then added that value to list. Finally, you can convert the output to a data frame. Since I was looping through several zip codes to do searches, I then appended that data frame to a master data frame and constructed a new column to filter out duplicates to only keep unique values."
},
{
"code": null,
"e": 10881,
"s": 10764,
"text": "Just like that, we have a clean, ready-to-use data frame with all of our data elements in a cleanly formatted table!"
},
{
"code": null,
"e": 11068,
"s": 10881,
"text": "If you’re using R or another programming language, you’ll create the URL string the same then adjust the code to do a URL request, set up empty vectors as opposed to lists, and so forth."
},
{
"code": null,
"e": 11224,
"s": 11068,
"text": "I’ve only scratched the surface with how the output can be used and there are several exciting possibilities both for location analysis or other use cases."
},
{
"code": null,
"e": 11578,
"s": 11224,
"text": "One of the ways I used this in a separate project was using a geopandas spatial join to map the latitude/longitude coordinates to a custom output level then assessing competition within each of those bounded areas. We can also look at customer satisfaction, in addition to competitive density, using the weighted average rating within a geographic area."
},
{
"code": null,
"e": 11920,
"s": 11578,
"text": "A simple and powerful tool is to drop this data onto a Tableau map to see exactly where competitors are (and aren’t) located. This can be combined with a demographic analysis to prioritize which locations have the right demographics for your business to succeed, then see exactly where the competition is to avoid cannibalization or overlap."
},
{
"code": null,
"e": 12288,
"s": 11920,
"text": "The Places API is among the more expensive of the Google Maps API, but there’s ample work you can do with it before having to go out-of-pocket. When I signed up, there was a $300 credit that had to be used within 3 months. Google also provides a free $200 credit every single month. This doesn’t carry over, so you have up to $200 to use each month which then resets."
},
{
"code": null,
"e": 12588,
"s": 12288,
"text": "An approximate rule of thumb for the API is that it will cost about $40 for every 1,000 API requests. Remember, you can get up to 20 locations per request, so you can get up to 20,000 locations for $40. With the $200 monthly credit, this equates to about 5,000 free requests before you start paying."
},
{
"code": null,
"e": 12822,
"s": 12588,
"text": "Full pricing details are available here, but an example is below for the Text Search API. We cannot control which data points are returned; the Places, Basic Data, Contact Data, and Atmosphere Data are all returned for each API call."
},
{
"code": null,
"e": 13191,
"s": 12822,
"text": "One last note on pricing that I didn’t understand at first is that each time you submit a URL string to pull information, it can be up to 3 total requests. I mentioned above that each URL call provides up to 20 results across 3 pages. To access each additional page is a new request to the API. So, to get all 60 results will be considered 3 total requests to the API."
},
{
"code": null,
"e": 13399,
"s": 13191,
"text": "I’m excited by the possibilities unlocked by understanding how to access and work with the data from this API. Across my time using it I’ve found a couple pros and cons to where and how the data can be used."
},
{
"code": null,
"e": 13929,
"s": 13399,
"text": "The optimal use case is for a targeted search in a narrow geographic area. In dense places like a city with broad search terms like coffee shop, you need to get very narrow in your search radius, as low as 500 meters for best results. The way I’ve accounted for this is to get bounded lat/lon geographic areas, like a zip code, and write code to do a grid search across that location that iteratively executes the search at staggered lat/lon entries with a small search radius, then filters out duplicate results on the back end."
},
{
"code": null,
"e": 14202,
"s": 13929,
"text": "This approach is not always the best option for wide search areas as the number of requests to the API may be excessive/expensive and time consuming (remember, it’s a 2-second break after each call, so 1,000 calls to the API will take 2,000+ seconds/more than 30 minutes)."
},
{
"code": null,
"e": 14383,
"s": 14202,
"text": "It’s best to start by using a handful of targeted search areas, testing the code and results (and understanding how pricing works), then expanding out to a broader geographic area."
}
] |
Box Stacking Problem
|
In this problem a set of different boxes are given, the length, breadth, and width may differ for different boxes. Our task is to find a stack of these boxes, whose height is as much as possible. We can rotate any box as we wish. But there is a rule to maintain.
One can place a box on another box if the area of the top surface for the bottom box is larger than the lower area of the top box.
Input:
A list of boxes is given. Each box is denoted by (length, bredth, height).
{ (4, 6, 7), (1, 2, 3), (4, 5, 6), (10, 12, 32) }
Output:
The maximum possible height of box stack is: 60
maxHeight(boxList, n)
Input − The list of different boxes, number of boxes.
Output − maximum height found by making the stacking of boxes.
Begin
define rotation array rot of size 3n.
index := 0
for all boxes i, in the boxList, do
rot[index].len := boxList[i].len
rot[index].hei := maximum of boxList[i].hei and boxList[i].bre
rot[index].bre := minimum of boxList[i].hei and boxList[i].bre
index := index + 1
rot[index].len := boxList[i].bre
rot[index].hei := maximum of boxList[i].len and boxList[i].hei
rot[index].bre := minimum of boxList[i].len and boxList[i].hei
index := index + 1
rot[index].len := boxList[i].hei
rot[index].hei := maximum of boxList[i].len and boxList[i].bre
rot[index].bre := minimum of boxList[i].len and boxList[i].bre
index := index + 1
n := 3n
sort the rot list
define maxHeightTemp array
for i := 1 to n-1, do
for j := 0 to i-1, do
if rot[i].bre < rot[j].bre AND
rot[i].hei < rot[j].hei AND
maxHeightTemp[i] < maxHeightTemp + rot[i].len, then
maxHeightTemp[i] := maxHeightTemp[j] +
rot[i].len
done
done
maxHeight := -1
for i := 0 to n-1, do
if maxHeight < maxHeightTemp[i], then
maxHeight := maxHeightTemp[i]
done
done
return maxHeight
End
#include<iostream>
#include<algorithm>
using namespace std;
struct Box {
int length, bredth, height;
};
int min (int x, int y) {
return (x < y)? x : y;
}
int max (int x, int y) {
return (x > y)? x : y;
}
bool compare(Box b1, Box b2) {
return b1.height > b2.height; //to sort the box as descending order of height
}
int maxHeight( Box boxList[], int n ) {
Box rotation[3*n]; //a box can be rotared as 3 type, so there is 3n number of rotations
int index = 0;
for (int i = 0; i < n; i++) {
//store initial position of the box
rotation[index].length = boxList[i].length;
rotation[index].height = max(boxList[i].height, boxList[i].bredth);
rotation[index].bredth = min(boxList[i].height, boxList[i].bredth);
index++;
//dimention after first rotation
rotation[index].length = boxList[i].bredth;
rotation[index].height = max(boxList[i].length, boxList[i].height);
rotation[index].bredth = min(boxList[i].length, boxList[i].height);
index++;
//Dimention after second rotation
rotation[index].length = boxList[i].height;
rotation[index].height = max(boxList[i].length, boxList[i].bredth);
rotation[index].bredth = min(boxList[i].length, boxList[i].bredth);
index++;
}
n = 3*n; //set n as 3n for 3 rotations of each boxes
sort(rotation, rotation+n, compare); //sort rotation array as descending order
int maxHTemp[n]; //temporary max height if ith box is stacked
for (int i = 0; i < n; i++ )
maxHTemp[i] = rotation[i].length;
for (int i = 1; i < n; i++ ) //find optimized stack height
for (int j = 0; j < i; j++ )
if ( rotation[i].bredth < rotation[j].bredth && rotation[i].height < rotation[j].height
&& maxHTemp[i] < maxHTemp[j] + rotation[i].length) {
maxHTemp[i] = maxHTemp[j] + rotation[i].length;
}
int maxHeight = -1;
for ( int i = 0; i < n; i++ ) //find the maximum height from all temporary heights
if ( maxHeight < maxHTemp[i] )
maxHeight = maxHTemp[i];
return maxHeight;
}
int main() {
Box arr[] = { {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} };
int n = 4;
cout<<"The maximum possible height of box stack is: " << maxHeight (arr, n) << endl;
}
The maximum possible height of box stack is: 60
|
[
{
"code": null,
"e": 1325,
"s": 1062,
"text": "In this problem a set of different boxes are given, the length, breadth, and width may differ for different boxes. Our task is to find a stack of these boxes, whose height is as much as possible. We can rotate any box as we wish. But there is a rule to maintain."
},
{
"code": null,
"e": 1456,
"s": 1325,
"text": "One can place a box on another box if the area of the top surface for the bottom box is larger than the lower area of the top box."
},
{
"code": null,
"e": 1644,
"s": 1456,
"text": "Input:\nA list of boxes is given. Each box is denoted by (length, bredth, height).\n{ (4, 6, 7), (1, 2, 3), (4, 5, 6), (10, 12, 32) }\nOutput:\nThe maximum possible height of box stack is: 60"
},
{
"code": null,
"e": 1666,
"s": 1644,
"text": "maxHeight(boxList, n)"
},
{
"code": null,
"e": 1720,
"s": 1666,
"text": "Input − The list of different boxes, number of boxes."
},
{
"code": null,
"e": 1783,
"s": 1720,
"text": "Output − maximum height found by making the stacking of boxes."
},
{
"code": null,
"e": 3065,
"s": 1783,
"text": "Begin\n define rotation array rot of size 3n.\n index := 0\n\n for all boxes i, in the boxList, do\n rot[index].len := boxList[i].len\n rot[index].hei := maximum of boxList[i].hei and boxList[i].bre\n rot[index].bre := minimum of boxList[i].hei and boxList[i].bre\n index := index + 1\n\n rot[index].len := boxList[i].bre\n rot[index].hei := maximum of boxList[i].len and boxList[i].hei\n rot[index].bre := minimum of boxList[i].len and boxList[i].hei\n index := index + 1\n\n rot[index].len := boxList[i].hei\n rot[index].hei := maximum of boxList[i].len and boxList[i].bre\n rot[index].bre := minimum of boxList[i].len and boxList[i].bre\n index := index + 1\n\n n := 3n\n sort the rot list\n define maxHeightTemp array\n\n for i := 1 to n-1, do\n for j := 0 to i-1, do\n if rot[i].bre < rot[j].bre AND\n rot[i].hei < rot[j].hei AND\n maxHeightTemp[i] < maxHeightTemp + rot[i].len, then\n maxHeightTemp[i] := maxHeightTemp[j] +\n rot[i].len\n done\n done\n\n maxHeight := -1\n for i := 0 to n-1, do\n if maxHeight < maxHeightTemp[i], then\n maxHeight := maxHeightTemp[i]\n done\n done\n return maxHeight\nEnd"
},
{
"code": null,
"e": 5399,
"s": 3065,
"text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\nstruct Box {\n int length, bredth, height;\n};\n\nint min (int x, int y) {\n return (x < y)? x : y;\n}\n\nint max (int x, int y) {\n return (x > y)? x : y;\n}\n\nbool compare(Box b1, Box b2) {\n return b1.height > b2.height; //to sort the box as descending order of height\n}\n\nint maxHeight( Box boxList[], int n ) {\n Box rotation[3*n]; //a box can be rotared as 3 type, so there is 3n number of rotations\n int index = 0;\n\n for (int i = 0; i < n; i++) {\n //store initial position of the box\n rotation[index].length = boxList[i].length;\n rotation[index].height = max(boxList[i].height, boxList[i].bredth);\n rotation[index].bredth = min(boxList[i].height, boxList[i].bredth);\n index++;\n\n //dimention after first rotation\n rotation[index].length = boxList[i].bredth;\n rotation[index].height = max(boxList[i].length, boxList[i].height);\n rotation[index].bredth = min(boxList[i].length, boxList[i].height);\n index++; \n \n //Dimention after second rotation\n rotation[index].length = boxList[i].height;\n rotation[index].height = max(boxList[i].length, boxList[i].bredth);\n rotation[index].bredth = min(boxList[i].length, boxList[i].bredth);\n index++;\n }\n\n n = 3*n; //set n as 3n for 3 rotations of each boxes\n\n sort(rotation, rotation+n, compare); //sort rotation array as descending order\n\n int maxHTemp[n]; //temporary max height if ith box is stacked\n\n for (int i = 0; i < n; i++ )\n maxHTemp[i] = rotation[i].length;\n \n for (int i = 1; i < n; i++ ) //find optimized stack height\n for (int j = 0; j < i; j++ )\n if ( rotation[i].bredth < rotation[j].bredth && rotation[i].height < rotation[j].height\n && maxHTemp[i] < maxHTemp[j] + rotation[i].length) {\n maxHTemp[i] = maxHTemp[j] + rotation[i].length;\n }\n int maxHeight = -1;\n for ( int i = 0; i < n; i++ ) //find the maximum height from all temporary heights\n \n if ( maxHeight < maxHTemp[i] )\n maxHeight = maxHTemp[i];\n \n return maxHeight;\n}\n\nint main() {\n Box arr[] = { {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32} };\n int n = 4;\n cout<<\"The maximum possible height of box stack is: \" << maxHeight (arr, n) << endl;\n}"
},
{
"code": null,
"e": 5447,
"s": 5399,
"text": "The maximum possible height of box stack is: 60"
}
] |
Timer1 based PWM in Arduino Uno
|
In an earlier article, we have seen how PWM can be set on Arduino Uno using the analogWrite() function. Pins 3,5,6,9,10 and 11 of Arduino Uno can support PWM. The frequency of the square wave is 490 Hz (about 2 ms time period) on all pins except 5 and 6, on which it is 980 Hz (about 1s time period). With analogWrite() you get control over the duty cycle, but not on the frequency of the generated square wave.
In this article, we will look at another way of setting PWM in Arduino Uno, specific to Timer1. The advantage of this method is that it allows us to control the frequency of the PWM signal as well, along with the duty cycle. This is based on the TimerOne library that we have seen in the past, in the article concerning Timer Interrupts in Arduino. Go to Tools → Library Manager, and download the TimerOne library.
The syntax for PWM is −
Timer1.pwm(pin, duty);
Where pin is the pin number on which you wish to set the PWM. Only pins 9 and 10 allow Timer1 based PWM.
Duty is the duty cycle (from 0 to 1023). 0 represents a duty cycle of 0%, while 1023 represents 100%.
If you wish to change the duty cycle mid-execution, you can use −
Timer1.setPwmDuty(pin, duty);
And to disable PWM, you can use −
Timer1.disablePwm(pin);
You may be wondering where did we set the frequency of the PWM. We do that in the setup, using the Timer.initialize() function.
Timer1.initialize(microseconds);
Where the argument is the microsecond interval of the wave. Thus, if you want a frequency of 100kHz, you set the microseconds time as 10.
Timer1.initialize(10);
We will look at the example that comes with the TimerOne library. Go to File → Examples → TimerOne → FanSpeed
You can also find the code on GitHub here − https://github.com/PaulStoffregen/TimerOne/blob/master/examples/FanSpeed/FanSpeed.pde
Over here, the speed of the fan, connected to pin 4 (you need to change it to pin 9 or 10 for Arduino Uno), is changed using PWM.
We include the library and begin with specifying the fan pin.
#include −TimerOne.h>
const int fanPin = 9;
In the setup, we initialize the Timer1 library at 40 microseconds interval (or 25 kHz frequency), and we also initialize Serial.
void setup(void)
{
Timer1.initialize(40); // 40 us = 25 kHz
Serial.begin(9600);
}
In the loop, we increase the duty cycle from 30% to 100%, in steps of 1% in a for loop.
void loop(void)
{
// slowly increase the PWM fan speed
//
for (float dutyCycle = 30.0; dutyCycle < 100.0; dutyCycle++) {
Serial.print("PWM Fan, Duty Cycle = ");
Serial.println(dutyCycle);
Timer1.pwm(fanPin, (dutyCycle / 100) * 1023);
delay(500);
}
}
|
[
{
"code": null,
"e": 1474,
"s": 1062,
"text": "In an earlier article, we have seen how PWM can be set on Arduino Uno using the analogWrite() function. Pins 3,5,6,9,10 and 11 of Arduino Uno can support PWM. The frequency of the square wave is 490 Hz (about 2 ms time period) on all pins except 5 and 6, on which it is 980 Hz (about 1s time period). With analogWrite() you get control over the duty cycle, but not on the frequency of the generated square wave."
},
{
"code": null,
"e": 1889,
"s": 1474,
"text": "In this article, we will look at another way of setting PWM in Arduino Uno, specific to Timer1. The advantage of this method is that it allows us to control the frequency of the PWM signal as well, along with the duty cycle. This is based on the TimerOne library that we have seen in the past, in the article concerning Timer Interrupts in Arduino. Go to Tools → Library Manager, and download the TimerOne library."
},
{
"code": null,
"e": 1913,
"s": 1889,
"text": "The syntax for PWM is −"
},
{
"code": null,
"e": 1936,
"s": 1913,
"text": "Timer1.pwm(pin, duty);"
},
{
"code": null,
"e": 2041,
"s": 1936,
"text": "Where pin is the pin number on which you wish to set the PWM. Only pins 9 and 10 allow Timer1 based PWM."
},
{
"code": null,
"e": 2143,
"s": 2041,
"text": "Duty is the duty cycle (from 0 to 1023). 0 represents a duty cycle of 0%, while 1023 represents 100%."
},
{
"code": null,
"e": 2209,
"s": 2143,
"text": "If you wish to change the duty cycle mid-execution, you can use −"
},
{
"code": null,
"e": 2239,
"s": 2209,
"text": "Timer1.setPwmDuty(pin, duty);"
},
{
"code": null,
"e": 2273,
"s": 2239,
"text": "And to disable PWM, you can use −"
},
{
"code": null,
"e": 2297,
"s": 2273,
"text": "Timer1.disablePwm(pin);"
},
{
"code": null,
"e": 2425,
"s": 2297,
"text": "You may be wondering where did we set the frequency of the PWM. We do that in the setup, using the Timer.initialize() function."
},
{
"code": null,
"e": 2458,
"s": 2425,
"text": "Timer1.initialize(microseconds);"
},
{
"code": null,
"e": 2596,
"s": 2458,
"text": "Where the argument is the microsecond interval of the wave. Thus, if you want a frequency of 100kHz, you set the microseconds time as 10."
},
{
"code": null,
"e": 2619,
"s": 2596,
"text": "Timer1.initialize(10);"
},
{
"code": null,
"e": 2729,
"s": 2619,
"text": "We will look at the example that comes with the TimerOne library. Go to File → Examples → TimerOne → FanSpeed"
},
{
"code": null,
"e": 2859,
"s": 2729,
"text": "You can also find the code on GitHub here − https://github.com/PaulStoffregen/TimerOne/blob/master/examples/FanSpeed/FanSpeed.pde"
},
{
"code": null,
"e": 2989,
"s": 2859,
"text": "Over here, the speed of the fan, connected to pin 4 (you need to change it to pin 9 or 10 for Arduino Uno), is changed using PWM."
},
{
"code": null,
"e": 3051,
"s": 2989,
"text": "We include the library and begin with specifying the fan pin."
},
{
"code": null,
"e": 3095,
"s": 3051,
"text": "#include −TimerOne.h>\nconst int fanPin = 9;"
},
{
"code": null,
"e": 3224,
"s": 3095,
"text": "In the setup, we initialize the Timer1 library at 40 microseconds interval (or 25 kHz frequency), and we also initialize Serial."
},
{
"code": null,
"e": 3312,
"s": 3224,
"text": "void setup(void)\n{\n Timer1.initialize(40); // 40 us = 25 kHz\n Serial.begin(9600);\n}"
},
{
"code": null,
"e": 3400,
"s": 3312,
"text": "In the loop, we increase the duty cycle from 30% to 100%, in steps of 1% in a for loop."
},
{
"code": null,
"e": 3686,
"s": 3400,
"text": "void loop(void)\n{\n // slowly increase the PWM fan speed\n //\n for (float dutyCycle = 30.0; dutyCycle < 100.0; dutyCycle++) {\n Serial.print(\"PWM Fan, Duty Cycle = \");\n Serial.println(dutyCycle);\n Timer1.pwm(fanPin, (dutyCycle / 100) * 1023);\n delay(500);\n }\n}"
}
] |
SAP Testing - Modules
|
There are different SAP modules implemented in an organization that can be tested using various testing tools like HP Quick Test Professional (QTP), IBM Rational Functional Tester (RFT), and SAP Test Acceleration and Optimization (TAO) tool.
The common SAP modules are listed below −
Financial Modules − Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC).
Financial Modules − Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC).
Logistics Modules − Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc.
Logistics Modules − Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc.
Human Resource Management − Accounting Payroll, Time Management, Training and Event Management.
Human Resource Management − Accounting Payroll, Time Management, Training and Event Management.
All these modules are inter-dependent and the functionality of one module affects the functionality of other modules.
Suppose you have to create a Sales Order in Sales and Distribution (SD) module. Here, you first need to enter the transaction code(e.g., Transaction Code VA01). Next, check the stock of the item in Inventory module and check the credit limit available on Customer profile in Customer Relationship Module. It shows that all these modules are interdependent; if you customize any of these modules, it will affect the related ERP system.
To perform SAP testing, you need to understand the features, functionalities, and how the workflow takes place in these SAP modules. Most of the common reasons of failure of ERP implementation project is incorrect test planning and the use of wrong test-cases.
Non SAP ERP systems like PeopleSoft, Edwards, Oracle E business suite have different customers and capabilities. The testing team needs to understand the functionality of complete system.
There are normally two types of testers available in SAP projects −
Core Testers − who are responsible to perform basic testing of ERP system and modules.
Core Testers − who are responsible to perform basic testing of ERP system and modules.
Implementation Testers − who work on implementation project and cover the customization functionalities of SAP modules.
Implementation Testers − who work on implementation project and cover the customization functionalities of SAP modules.
Customization requests from clients can impact the modules of a SAP system. The testing team should be able to record each customization request and its impact on the other SAP modules.
ERP systems are large systems and therefore the testing process should ideally be automated. It is always advisable to perform automated testing for ERP systems, as manual testing is a very time-consuming and lengthy process. Without testing each component of the SAP system, it is really tough to achieve 100% quality and successful implementation of SAP project.
To perform SAP testing for the above example, follow the steps given below −
The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system.
The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system.
The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP.
The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP.
Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM.
Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM.
After you are done with the recording in QTP tool, create a script in VB.
After you are done with the recording in QTP tool, create a script in VB.
SAPGuiSession("Session").SAPGuiWindow("SAP Easy Access - User")
.SAPGuiOKCode("OKCode").Set "/nVA01"
SAPGuiSession("Session").SAPGuiWindow("SAP Easy Access - User"). SendKey ENTER
You can also add different parameters and customizations as per your requirement.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2488,
"s": 2246,
"text": "There are different SAP modules implemented in an organization that can be tested using various testing tools like HP Quick Test Professional (QTP), IBM Rational Functional Tester (RFT), and SAP Test Acceleration and Optimization (TAO) tool."
},
{
"code": null,
"e": 2530,
"s": 2488,
"text": "The common SAP modules are listed below −"
},
{
"code": null,
"e": 2637,
"s": 2530,
"text": "Financial Modules − Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC)."
},
{
"code": null,
"e": 2744,
"s": 2637,
"text": "Financial Modules − Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC)."
},
{
"code": null,
"e": 2873,
"s": 2744,
"text": "Logistics Modules − Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc."
},
{
"code": null,
"e": 3002,
"s": 2873,
"text": "Logistics Modules − Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc."
},
{
"code": null,
"e": 3098,
"s": 3002,
"text": "Human Resource Management − Accounting Payroll, Time Management, Training and Event Management."
},
{
"code": null,
"e": 3194,
"s": 3098,
"text": "Human Resource Management − Accounting Payroll, Time Management, Training and Event Management."
},
{
"code": null,
"e": 3312,
"s": 3194,
"text": "All these modules are inter-dependent and the functionality of one module affects the functionality of other modules."
},
{
"code": null,
"e": 3747,
"s": 3312,
"text": "Suppose you have to create a Sales Order in Sales and Distribution (SD) module. Here, you first need to enter the transaction code(e.g., Transaction Code VA01). Next, check the stock of the item in Inventory module and check the credit limit available on Customer profile in Customer Relationship Module. It shows that all these modules are interdependent; if you customize any of these modules, it will affect the related ERP system."
},
{
"code": null,
"e": 4008,
"s": 3747,
"text": "To perform SAP testing, you need to understand the features, functionalities, and how the workflow takes place in these SAP modules. Most of the common reasons of failure of ERP implementation project is incorrect test planning and the use of wrong test-cases."
},
{
"code": null,
"e": 4196,
"s": 4008,
"text": "Non SAP ERP systems like PeopleSoft, Edwards, Oracle E business suite have different customers and capabilities. The testing team needs to understand the functionality of complete system."
},
{
"code": null,
"e": 4264,
"s": 4196,
"text": "There are normally two types of testers available in SAP projects −"
},
{
"code": null,
"e": 4351,
"s": 4264,
"text": "Core Testers − who are responsible to perform basic testing of ERP system and modules."
},
{
"code": null,
"e": 4438,
"s": 4351,
"text": "Core Testers − who are responsible to perform basic testing of ERP system and modules."
},
{
"code": null,
"e": 4558,
"s": 4438,
"text": "Implementation Testers − who work on implementation project and cover the customization functionalities of SAP modules."
},
{
"code": null,
"e": 4678,
"s": 4558,
"text": "Implementation Testers − who work on implementation project and cover the customization functionalities of SAP modules."
},
{
"code": null,
"e": 4864,
"s": 4678,
"text": "Customization requests from clients can impact the modules of a SAP system. The testing team should be able to record each customization request and its impact on the other SAP modules."
},
{
"code": null,
"e": 5229,
"s": 4864,
"text": "ERP systems are large systems and therefore the testing process should ideally be automated. It is always advisable to perform automated testing for ERP systems, as manual testing is a very time-consuming and lengthy process. Without testing each component of the SAP system, it is really tough to achieve 100% quality and successful implementation of SAP project."
},
{
"code": null,
"e": 5306,
"s": 5229,
"text": "To perform SAP testing for the above example, follow the steps given below −"
},
{
"code": null,
"e": 5440,
"s": 5306,
"text": "The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system."
},
{
"code": null,
"e": 5574,
"s": 5440,
"text": "The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system."
},
{
"code": null,
"e": 5759,
"s": 5574,
"text": "The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP."
},
{
"code": null,
"e": 5944,
"s": 5759,
"text": "The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP."
},
{
"code": null,
"e": 6053,
"s": 5944,
"text": "Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM."
},
{
"code": null,
"e": 6162,
"s": 6053,
"text": "Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM."
},
{
"code": null,
"e": 6236,
"s": 6162,
"text": "After you are done with the recording in QTP tool, create a script in VB."
},
{
"code": null,
"e": 6310,
"s": 6236,
"text": "After you are done with the recording in QTP tool, create a script in VB."
},
{
"code": null,
"e": 6494,
"s": 6310,
"text": "SAPGuiSession(\"Session\").SAPGuiWindow(\"SAP Easy Access - User\")\n .SAPGuiOKCode(\"OKCode\").Set \"/nVA01\"\n\nSAPGuiSession(\"Session\").SAPGuiWindow(\"SAP Easy Access - User\"). SendKey ENTER"
},
{
"code": null,
"e": 6576,
"s": 6494,
"text": "You can also add different parameters and customizations as per your requirement."
},
{
"code": null,
"e": 6609,
"s": 6576,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6623,
"s": 6609,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 6656,
"s": 6623,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6668,
"s": 6656,
"text": " Neha Gupta"
},
{
"code": null,
"e": 6703,
"s": 6668,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6718,
"s": 6703,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6751,
"s": 6718,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6766,
"s": 6751,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6801,
"s": 6766,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6813,
"s": 6801,
"text": " Neha Malik"
},
{
"code": null,
"e": 6848,
"s": 6813,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6860,
"s": 6848,
"text": " Neha Malik"
},
{
"code": null,
"e": 6867,
"s": 6860,
"text": " Print"
},
{
"code": null,
"e": 6878,
"s": 6867,
"text": " Add Notes"
}
] |
How to Add User Registration with Email Verification in Android? - GeeksforGeeks
|
06 Nov, 2021
We have seen most of the apps verify their user via the user’s email addresses or phone numbers by sending them either a verification link or sending an OTP to the user’s mobile numbers. In this article, we will take a look at the implementation of user Registration in Android with its email verification. For this, we will be using the Back4App service which provides us a feature so that we can send the automated email verification links to our users for verification.
We will be building a simple application in which we will be displaying a simple user registration and login form. After user registration, we will be sending a verification link to our user’s email address to verify the user’s email address. Below is the video in which we will get to see what we are going to build in this article.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Back4App
Please refer to How to Connect Android App with Back4App for this task.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--text view for heading--> <TextView android:id="@+id/idTVHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:gravity="center_horizontal" android:padding="5dp" android:text="Welcome to Geeks for Geeks \n Register Form" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="18sp" /> <!--edit text for user name--> <EditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeader" android:layout_marginStart="10dp" android:layout_marginTop="50dp" android:layout_marginEnd="10dp" android:hint="Enter UserName" android:inputType="text" /> <!--edit text for user email--> <EditText android:id="@+id/idEdtEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtUserName" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Enter Email Address" android:inputType="textEmailAddress" /> <!--edit text for user password--> <EditText android:id="@+id/idEdtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtEmail" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Enter Password" android:inputType="textPassword" /> <!--button to register our new user--> <Button android:id="@+id/idBtnRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtPassword" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:text="Register User" android:textAllCaps="false" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseException;import com.parse.ParseUser;import com.parse.SignUpCallback; public class MainActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt, userEmailEdt; private Button registerBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); userEmailEdt = findViewById(R.id.idEdtEmail); registerBtn = findViewById(R.id.idBtnRegister); // adding on click listener for our button registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); String email = userEmailEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password) && TextUtils.isEmpty(email)) { Toast.makeText(MainActivity.this, "Please enter user name and password", Toast.LENGTH_SHORT).show(); } // calling a method to register a user. registerUser(userName, password, email); } }); } private void registerUser(String userName, String password, String email) { // on below line we are creating // a new user using parse user. ParseUser user = new ParseUser(); // Set the user's username, user email and password, // which can be obtained from edit text user.setUsername(userName); user.setEmail(email); user.setPassword(password); // calling a method to register the user. user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { // on user registration checking // if the error is null or not. if (e == null) { // if the error is null we are displaying a toast message and // redirecting our user to login activity and passing the user name. Toast.makeText(MainActivity.this, "User Registered successfully \n Please verify your email", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, LoginActivity.class); i.putExtra("usereName", userName); i.putExtra("password", password); startActivity(i); } else { // if we get any error then we are logging out // our user and displaying an error message ParseUser.logOut(); Toast.makeText(MainActivity.this, "Fail to Register User..", Toast.LENGTH_SHORT).show(); } } }); }}
Step 5: Creating a new Activity for Login into our App
Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Empty activity and then name your activity as LoginActivity.
Step 6: Working with the activity_login.xml file
Navigate to the app > res > layout > activity_login.xml and add the below code to that file. Below is the code for the activity_login.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".LoginActivity"> <!--text view for heading--> <TextView android:id="@+id/idTVHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:gravity="center_horizontal" android:padding="5dp" android:text="Welcome to Geeks for Geeks \n Login Form" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="18sp" /> <!--edit text for user name--> <EditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeader" android:layout_marginStart="10dp" android:layout_marginTop="50dp" android:layout_marginEnd="10dp" android:hint="Enter UserName" android:inputType="textEmailAddress" /> <!--edit text for user password--> <EditText android:id="@+id/idEdtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtUserName" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Enter Password" android:inputType="textPassword" /> <!--button to register our new user--> <Button android:id="@+id/idBtnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtPassword" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:text="Login" android:textAllCaps="false" /> </RelativeLayout>
Step 7: Working with the LoginActivity.java file
Go to the LoginActivity.java file and refer to the following code. Below is the code for the LoginActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseUser; public class LoginActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt; private Button loginBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loginBtn = findViewById(R.id.idBtnLogin); userNameEdt.setText(getIntent().getStringExtra("usereName")); passwordEdt.setText(getIntent().getStringExtra("password")); // adding on click listener for our button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password)) { Toast.makeText(LoginActivity.this, "Please enter user name and password", Toast.LENGTH_SHORT).show(); } // calling a method to login our user. loginUser(userName, password); } }); } private void loginUser(String userName, String password) { // calling a method to login a user. ParseUser.logInInBackground(userName, password, (parseUser, e) -> { // after login checking if the user is null or not. if (parseUser != null) { // if the user is not null then we will display a toast message // with user login and passing that user to new activity. Toast.makeText(this, "Login Successful ", Toast.LENGTH_SHORT).show(); Intent i = new Intent(LoginActivity.this, HomeActivity.class); i.putExtra("username", userName); startActivity(i); } else { // display an toast message when user logout of the app. ParseUser.logOut(); Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); }}
Step 8: Creating a new Activity for displaying Home Screen
After the user login, we will redirect our user to the app’s home page. So for that, we will be creating a new activity. Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Empty Activity and then name your activity as HomeActivity.
Step 9: Working with the activity_home.xml file
Navigate to the app > res > layout > activity_home.xml and add the below code to that file. Below is the code for the activity_home.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".HomeActivity"> <!--text view for displaying heading--> <TextView android:id="@+id/idTVHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center_horizontal" android:text="Welcome back again to Geeks for Geeks" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="18sp" /> <!--text view for displaying user name--> <TextView android:id="@+id/idTVUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeader" android:layout_centerInParent="true" android:layout_marginTop="20dp" android:gravity="center_horizontal" android:text="UserName" android:textAlignment="center" android:textColor="@color/purple_700" android:textSize="25sp" /> </RelativeLayout>
Step 10: Working with the HomeActivity.java file
Go to the HomeActivity.java file and refer to the following code. Below is the code for the HomeActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class HomeActivity extends AppCompatActivity { // creating a variable for our text view.. private TextView userNameTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // initializing our variables userNameTV = findViewById(R.id.idTVUserName); // getting data from intent. String name = getIntent().getStringExtra("username"); // setting data to our text view. userNameTV.setText(name); }}
Now we have completed the work on our app and now we will move towards the email verification in the Back4App console.
Step 11: Adding email template which you will be sent to your user for email verification
Navigate to the app’s dashboard in the Back4App console. Inside this console. Navigate to the Server Settings option in the left nav drawer and inside your screen. Click on the Settings option in the Verification emails part. You can get to see the below screenshot.
After going to this option you can see the email template. You can add or edit this email template according to your requirement. After updating the email template. Make sure to save your email template.
After updating the email template save your email template and then run your app. You can get to see the output on the below screen.
Output:
Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Back4App/tree/EmailVerification
kalrap615
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
How to Change the Background Color After Clicking the Button in Android?
Android Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n06 Nov, 2021"
},
{
"code": null,
"e": 25590,
"s": 25116,
"text": "We have seen most of the apps verify their user via the user’s email addresses or phone numbers by sending them either a verification link or sending an OTP to the user’s mobile numbers. In this article, we will take a look at the implementation of user Registration in Android with its email verification. For this, we will be using the Back4App service which provides us a feature so that we can send the automated email verification links to our users for verification. "
},
{
"code": null,
"e": 25925,
"s": 25590,
"text": "We will be building a simple application in which we will be displaying a simple user registration and login form. After user registration, we will be sending a verification link to our user’s email address to verify the user’s email address. Below is the video in which we will get to see what we are going to build in this article. "
},
{
"code": null,
"e": 25954,
"s": 25925,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26116,
"s": 25954,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26153,
"s": 26116,
"text": "Step 2: Connect your app to Back4App"
},
{
"code": null,
"e": 26225,
"s": 26153,
"text": "Please refer to How to Connect Android App with Back4App for this task."
},
{
"code": null,
"e": 26273,
"s": 26225,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26416,
"s": 26273,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 26420,
"s": 26416,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--text view for heading--> <TextView android:id=\"@+id/idTVHeader\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"30dp\" android:gravity=\"center_horizontal\" android:padding=\"5dp\" android:text=\"Welcome to Geeks for Geeks \\n Register Form\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"18sp\" /> <!--edit text for user name--> <EditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeader\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter UserName\" android:inputType=\"text\" /> <!--edit text for user email--> <EditText android:id=\"@+id/idEdtEmail\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtUserName\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter Email Address\" android:inputType=\"textEmailAddress\" /> <!--edit text for user password--> <EditText android:id=\"@+id/idEdtPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtEmail\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter Password\" android:inputType=\"textPassword\" /> <!--button to register our new user--> <Button android:id=\"@+id/idBtnRegister\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtPassword\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:text=\"Register User\" android:textAllCaps=\"false\" /> </RelativeLayout>",
"e": 28903,
"s": 26420,
"text": null
},
{
"code": null,
"e": 28952,
"s": 28903,
"text": " Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 29143,
"s": 28952,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 29148,
"s": 29143,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseException;import com.parse.ParseUser;import com.parse.SignUpCallback; public class MainActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt, userEmailEdt; private Button registerBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); userEmailEdt = findViewById(R.id.idEdtEmail); registerBtn = findViewById(R.id.idBtnRegister); // adding on click listener for our button registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); String email = userEmailEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password) && TextUtils.isEmpty(email)) { Toast.makeText(MainActivity.this, \"Please enter user name and password\", Toast.LENGTH_SHORT).show(); } // calling a method to register a user. registerUser(userName, password, email); } }); } private void registerUser(String userName, String password, String email) { // on below line we are creating // a new user using parse user. ParseUser user = new ParseUser(); // Set the user's username, user email and password, // which can be obtained from edit text user.setUsername(userName); user.setEmail(email); user.setPassword(password); // calling a method to register the user. user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { // on user registration checking // if the error is null or not. if (e == null) { // if the error is null we are displaying a toast message and // redirecting our user to login activity and passing the user name. Toast.makeText(MainActivity.this, \"User Registered successfully \\n Please verify your email\", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, LoginActivity.class); i.putExtra(\"usereName\", userName); i.putExtra(\"password\", password); startActivity(i); } else { // if we get any error then we are logging out // our user and displaying an error message ParseUser.logOut(); Toast.makeText(MainActivity.this, \"Fail to Register User..\", Toast.LENGTH_SHORT).show(); } } }); }}",
"e": 32707,
"s": 29148,
"text": null
},
{
"code": null,
"e": 32763,
"s": 32707,
"text": " Step 5: Creating a new Activity for Login into our App"
},
{
"code": null,
"e": 32917,
"s": 32763,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Empty activity and then name your activity as LoginActivity. "
},
{
"code": null,
"e": 32966,
"s": 32917,
"text": "Step 6: Working with the activity_login.xml file"
},
{
"code": null,
"e": 33112,
"s": 32966,
"text": "Navigate to the app > res > layout > activity_login.xml and add the below code to that file. Below is the code for the activity_login.xml file. "
},
{
"code": null,
"e": 33116,
"s": 33112,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".LoginActivity\"> <!--text view for heading--> <TextView android:id=\"@+id/idTVHeader\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"30dp\" android:gravity=\"center_horizontal\" android:padding=\"5dp\" android:text=\"Welcome to Geeks for Geeks \\n Login Form\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"18sp\" /> <!--edit text for user name--> <EditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeader\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter UserName\" android:inputType=\"textEmailAddress\" /> <!--edit text for user password--> <EditText android:id=\"@+id/idEdtPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtUserName\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter Password\" android:inputType=\"textPassword\" /> <!--button to register our new user--> <Button android:id=\"@+id/idBtnLogin\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtPassword\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:text=\"Login\" android:textAllCaps=\"false\" /> </RelativeLayout>",
"e": 35135,
"s": 33116,
"text": null
},
{
"code": null,
"e": 35185,
"s": 35135,
"text": " Step 7: Working with the LoginActivity.java file"
},
{
"code": null,
"e": 35378,
"s": 35185,
"text": "Go to the LoginActivity.java file and refer to the following code. Below is the code for the LoginActivity.java file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 35383,
"s": 35378,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.ParseUser; public class LoginActivity extends AppCompatActivity { // creating variables for our edit text and buttons. private EditText userNameEdt, passwordEdt; private Button loginBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // initializing our edit text and buttons. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loginBtn = findViewById(R.id.idBtnLogin); userNameEdt.setText(getIntent().getStringExtra(\"usereName\")); passwordEdt.setText(getIntent().getStringExtra(\"password\")); // adding on click listener for our button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String userName = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // checking if the entered text is empty or not. if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(password)) { Toast.makeText(LoginActivity.this, \"Please enter user name and password\", Toast.LENGTH_SHORT).show(); } // calling a method to login our user. loginUser(userName, password); } }); } private void loginUser(String userName, String password) { // calling a method to login a user. ParseUser.logInInBackground(userName, password, (parseUser, e) -> { // after login checking if the user is null or not. if (parseUser != null) { // if the user is not null then we will display a toast message // with user login and passing that user to new activity. Toast.makeText(this, \"Login Successful \", Toast.LENGTH_SHORT).show(); Intent i = new Intent(LoginActivity.this, HomeActivity.class); i.putExtra(\"username\", userName); startActivity(i); } else { // display an toast message when user logout of the app. ParseUser.logOut(); Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); }}",
"e": 38149,
"s": 35383,
"text": null
},
{
"code": null,
"e": 38209,
"s": 38149,
"text": " Step 8: Creating a new Activity for displaying Home Screen"
},
{
"code": null,
"e": 38483,
"s": 38209,
"text": "After the user login, we will redirect our user to the app’s home page. So for that, we will be creating a new activity. Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Empty Activity and then name your activity as HomeActivity. "
},
{
"code": null,
"e": 38531,
"s": 38483,
"text": "Step 9: Working with the activity_home.xml file"
},
{
"code": null,
"e": 38676,
"s": 38531,
"text": "Navigate to the app > res > layout > activity_home.xml and add the below code to that file. Below is the code for the activity_home.xml file. "
},
{
"code": null,
"e": 38680,
"s": 38676,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".HomeActivity\"> <!--text view for displaying heading--> <TextView android:id=\"@+id/idTVHeader\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:gravity=\"center_horizontal\" android:text=\"Welcome back again to Geeks for Geeks\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"18sp\" /> <!--text view for displaying user name--> <TextView android:id=\"@+id/idTVUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeader\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"20dp\" android:gravity=\"center_horizontal\" android:text=\"UserName\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:textSize=\"25sp\" /> </RelativeLayout>",
"e": 39936,
"s": 38680,
"text": null
},
{
"code": null,
"e": 39986,
"s": 39936,
"text": " Step 10: Working with the HomeActivity.java file"
},
{
"code": null,
"e": 40177,
"s": 39986,
"text": "Go to the HomeActivity.java file and refer to the following code. Below is the code for the HomeActivity.java file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 40182,
"s": 40177,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class HomeActivity extends AppCompatActivity { // creating a variable for our text view.. private TextView userNameTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // initializing our variables userNameTV = findViewById(R.id.idTVUserName); // getting data from intent. String name = getIntent().getStringExtra(\"username\"); // setting data to our text view. userNameTV.setText(name); }}",
"e": 40867,
"s": 40182,
"text": null
},
{
"code": null,
"e": 40988,
"s": 40867,
"text": " Now we have completed the work on our app and now we will move towards the email verification in the Back4App console. "
},
{
"code": null,
"e": 41078,
"s": 40988,
"text": "Step 11: Adding email template which you will be sent to your user for email verification"
},
{
"code": null,
"e": 41347,
"s": 41078,
"text": "Navigate to the app’s dashboard in the Back4App console. Inside this console. Navigate to the Server Settings option in the left nav drawer and inside your screen. Click on the Settings option in the Verification emails part. You can get to see the below screenshot. "
},
{
"code": null,
"e": 41553,
"s": 41347,
"text": "After going to this option you can see the email template. You can add or edit this email template according to your requirement. After updating the email template. Make sure to save your email template. "
},
{
"code": null,
"e": 41687,
"s": 41553,
"text": "After updating the email template save your email template and then run your app. You can get to see the output on the below screen. "
},
{
"code": null,
"e": 41696,
"s": 41687,
"text": "Output: "
},
{
"code": null,
"e": 41807,
"s": 41696,
"text": "Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Back4App/tree/EmailVerification"
},
{
"code": null,
"e": 41819,
"s": 41809,
"text": "kalrap615"
},
{
"code": null,
"e": 41827,
"s": 41819,
"text": "Android"
},
{
"code": null,
"e": 41832,
"s": 41827,
"text": "Java"
},
{
"code": null,
"e": 41837,
"s": 41832,
"text": "Java"
},
{
"code": null,
"e": 41845,
"s": 41837,
"text": "Android"
},
{
"code": null,
"e": 41943,
"s": 41845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41952,
"s": 41943,
"text": "Comments"
},
{
"code": null,
"e": 41965,
"s": 41952,
"text": "Old Comments"
},
{
"code": null,
"e": 42004,
"s": 41965,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 42046,
"s": 42004,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 42079,
"s": 42046,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 42152,
"s": 42079,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 42190,
"s": 42152,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 42205,
"s": 42190,
"text": "Arrays in Java"
},
{
"code": null,
"e": 42249,
"s": 42205,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 42271,
"s": 42249,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 42307,
"s": 42271,
"text": "Arrays.sort() in Java with examples"
}
] |
How do I use InputFilter to limit characters in an EditText in Android Kotlin?
|
This example demonstrates how to use InputFilter to limit characters in an EditText in Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
editText = findViewById(R.id.editText)
val maxTextLength = 15
editText.filters = arrayOf<InputFilter>(LengthFilter(maxTextLength))
Toast.makeText(this, "EditText limit set to 15 characters", Toast.LENGTH_SHORT).show()
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "This example demonstrates how to use InputFilter to limit characters in an EditText in Android Kotlin."
},
{
"code": null,
"e": 1294,
"s": 1165,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1359,
"s": 1294,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1871,
"s": 1359,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"40dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1926,
"s": 1871,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2630,
"s": 1926,
"text": "import android.os.Bundle\nimport android.text.InputFilter\nimport android.text.InputFilter.LengthFilter\nimport android.widget.EditText\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var editText: EditText\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n editText = findViewById(R.id.editText)\n val maxTextLength = 15\n editText.filters = arrayOf<InputFilter>(LengthFilter(maxTextLength))\n Toast.makeText(this, \"EditText limit set to 15 characters\", Toast.LENGTH_SHORT).show()\n }\n}"
},
{
"code": null,
"e": 2685,
"s": 2630,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3356,
"s": 2685,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3704,
"s": 3356,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Python Group by matching second tuple value in list of tuples - GeeksforGeeks
|
11 Dec, 2020
Given a list of tuples, the task is to group the tuples by matching the second element in the tuples. We can achieve this using dictionary by checking the second element in each tuple.
Examples:
Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)]
Output: {80: [(20, 80), (31, 80)],
11: [(88, 11), (27, 11)],
22: [(1, 22)]}
Input : [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')]
Output: {'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
'Geek': [(20, 'Geek'), (31, 'Geek')]}
Code #1:
# Python program to group tuples by matching # second tuple value in list of tuples # Initialisation Input = [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)] Output = {}for x, y in Input: if y in Output: Output[y].append((x, y)) else: Output[y] = [(x, y)] # Printing Outputprint(Output)
{80: [(20, 80), (31, 80)], 11: [(88, 11), (27, 11)], 22: [(1, 22)]}
Code #2:
# Python program to group tuples by matching # second tuple value in list of tuples # Initialisation Input = [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')] Output = {}for x, y in Input: if y in Output: Output[y].append((x, y)) else: Output[y] = [(x, y)] # Printing Outputprint(Output)
{'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
'Geek': [(20, 'Geek'), (31, 'Geek')]}
Python tuple-programs
python-tuple
Python
Python Programs
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
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24878,
"s": 24850,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 25063,
"s": 24878,
"text": "Given a list of tuples, the task is to group the tuples by matching the second element in the tuples. We can achieve this using dictionary by checking the second element in each tuple."
},
{
"code": null,
"e": 25073,
"s": 25063,
"text": "Examples:"
},
{
"code": null,
"e": 25402,
"s": 25073,
"text": "Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)]\nOutput: {80: [(20, 80), (31, 80)],\n 11: [(88, 11), (27, 11)],\n 22: [(1, 22)]}\n\nInput : [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')]\nOutput: {'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],\n 'Geek': [(20, 'Geek'), (31, 'Geek')]}\n\n"
},
{
"code": null,
"e": 25413,
"s": 25404,
"text": "Code #1:"
},
{
"code": "# Python program to group tuples by matching # second tuple value in list of tuples # Initialisation Input = [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)] Output = {}for x, y in Input: if y in Output: Output[y].append((x, y)) else: Output[y] = [(x, y)] # Printing Outputprint(Output)",
"e": 25724,
"s": 25413,
"text": null
},
{
"code": null,
"e": 25793,
"s": 25724,
"text": "{80: [(20, 80), (31, 80)], 11: [(88, 11), (27, 11)], 22: [(1, 22)]}\n"
},
{
"code": null,
"e": 25803,
"s": 25793,
"text": " Code #2:"
},
{
"code": "# Python program to group tuples by matching # second tuple value in list of tuples # Initialisation Input = [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')] Output = {}for x, y in Input: if y in Output: Output[y].append((x, y)) else: Output[y] = [(x, y)] # Printing Outputprint(Output)",
"e": 26127,
"s": 25803,
"text": null
},
{
"code": null,
"e": 26215,
"s": 26127,
"text": "{'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],\n 'Geek': [(20, 'Geek'), (31, 'Geek')]}\n"
},
{
"code": null,
"e": 26237,
"s": 26215,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 26250,
"s": 26237,
"text": "python-tuple"
},
{
"code": null,
"e": 26257,
"s": 26250,
"text": "Python"
},
{
"code": null,
"e": 26273,
"s": 26257,
"text": "Python Programs"
},
{
"code": null,
"e": 26371,
"s": 26273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26389,
"s": 26371,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26424,
"s": 26389,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26446,
"s": 26424,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26478,
"s": 26446,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26508,
"s": 26478,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26551,
"s": 26508,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26573,
"s": 26551,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26619,
"s": 26573,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26658,
"s": 26619,
"text": "Python | Get dictionary keys as a list"
}
] |
Element with left side smaller and right side greater | Practice | GeeksforGeeks
|
Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it.
Note: Left and right side elements can be equal to required element. And extreme elements cannot be required element.
Example 1:
Input:
N = 4
A[] = {4, 2, 5, 7}
Output:
5
Explanation:
Elements on left of 5 are smaller than 5
and on right of it are greater than 5.
Example 2:
Input:
N = 3
A[] = {11, 9, 12}
Output:
-1
Your Task:
You don't need to read input or print anything. Your task is to complete the function findElement() which takes the array A[] and its size N as inputs and returns the required element. If no such element present in array then return -1.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
3 <= N <= 106
1 <= A[i] <= 106
+1
ajaypal1920023 weeks ago
// C++ solution
int findElement(int a[], int n)
{
int l[n];
int r[n];
int maxi = a[0];
for (int i = 0; i < n; i++)
{
maxi = max(maxi, a[i]);
l[i] = maxi;
}
int mini = a[n - 1];
for (int i = n - 1; i >= 0; i--)
{
mini = min(mini, a[i]);
r[i] = mini;
}
for (int i = 1; i < n - 1; i++)
{
if (a[i] >= l[i - 1] and a[i] <= r[i + 1])
{
return a[i];
}
}
return -1;
}
0
jayesh293 weeks ago
JAVA 0.64 seconds -
public int findElement(int arr[], int n){
int big = arr[0], small = arr[n-1],ele=-1;
int[] max = new int[n];
int[] min = new int[n];
max[0]=big;min[n-1]=small;
int lo = 1,hi=n-2;
while(lo<n){
if(arr[lo]>big){
big = arr[lo];
}
max[lo++]=big;
if(arr[hi]<small){
small=arr[hi];
}
min[hi--]=small;
}
for(int i=1;i<n-1;i++){
if(max[i]==min[i]){
ele = arr[i];
break;
}
}
return ele;
}
0
swapniltayal4221 month ago
int findElement(int arr[], int n) { int maxi = INT_MIN; int mini = INT_MAX; int lrg[n]; int sml[n]; for (int i=0; i<n; i++){ maxi = max(arr[i], maxi); lrg[i] = maxi; } for (int i=n-1; i>=0; i--){ mini = min(arr[i], mini); sml[i] = mini; } for (int i=1; i<n-1; i++){ if (arr[i] >= lrg[i-1] && arr[i] <= sml[i+1]){ return arr[i]; } }return -1; }
0
pratikbhankhodiya1 month ago
int findElement(int arr[], int n) {
vector<int> left(n),right(n);
for(int i=0,maxi=INT_MIN,j=n-1,mini=INT_MAX;i<n;i++,j--){
maxi=max(maxi,arr[i]);
left[i]=maxi;
mini=min(mini,arr[j]);
right[j]=mini;
}
for(int i=1;i<n-1;i++){
if(left[i]<=arr[i] and right[i]>=arr[i]) return arr[i];
}
return -1;
}
-1
hargunsinghsahni2 months ago
int findElement(int arr[], int n) {
int l[n],r[n];
int mx=-1;
for(int i=0;i<n;i++)
{
if(arr[i]>mx)
mx=arr[i];
l[i]=mx;
}
mx=INT_MAX;
for(int i=n-1;i>=0;i--)
{
if(arr[i]<mx)
mx=arr[i];
r[i]=mx;
}
int ans=-1;
for(int i=0;i<n;i++)
if(arr[i]>=l[i] && arr[i]<=r[i] && i!=0 && i!=n-1 && ans==-1)
ans=arr[i];
return ans;
}
0
pawan kumar 332 months ago
// Working Code:-
int findElement(int arr[], int n) { int left[n],right[n]; left[0] = -1; right[n-1] = -1; int max = arr[0]; int min = arr[n-1]; for(int i=1;i<n;i++) { left[i] = max; if(arr[i] > max) max = arr[i]; } for(int i=n-2;i>=0;i--) { right[i] = min; if(arr[i] < min) min = arr[i]; } for(int i=1;i<n-1;i++) { if(left[i]<=arr[i] && right[i]>=arr[i]) return arr[i]; } return -1; }
+3
vaibhav motwani2 months ago
// Shortest solution with least conditionsint findElement(int arr[], int n) { int curr_ans=arr[0], return_value=-1; for(int i=0;i<n;i++){ if(arr[i]>=curr_ans && return_value == -1 && i!=0 && i!= n-1){ curr_ans = arr[i]; return_value = curr_ans; } else if(arr[i]<curr_ans){ return_value = -1; } } return return_value;}
0
gupta2411sumit2 months ago
// Easy and fast c++ solution
int findElement(int arr[], int n) {
int left[n] ; int right[n] ; int mx = arr[0] ; int mn = arr[n-1] ; left[0] = 0 ; left[n-1] = 0 ; right[0] = 0 ; right[n-1] = 0 ; for( int i = 1 ; i<n-1 ; i++) { if(arr[i]<mx) { left[i] = 0 ; } else{ left[i] = 1 ; mx = arr[i] ; } } for( int i = n-2 ; i>0 ; i--) { if(arr[i]>mn) { right[i] = 0 ; } else{ right[i] = 1 ; mn = arr[i] ; } } for( int i = 0 ; i<n ; i++) { if( left[i]==1 && right[i]==1) { return arr[i] ; } } return -1 ;}
0
aarthinarayanan2 months ago
int findElement(int arr[], int n) { int max_left[n],min_right[n]; max_left[0]=INT_MIN; min_right[n-1]=INT_MAX; for(int i=1;i<n;i++) { if(arr[i-1]>max_left[i-1]) max_left[i]=arr[i-1]; else max_left[i]=max_left[i-1]; } for(int i=n-2;i>=0;i--) { if(arr[i+1]<min_right[i+1]) min_right[i]=arr[i+1]; else min_right[i]=min_right[i+1]; } for(int i=1;i<n-1;i++) if(arr[i]>=max_left[i] && arr[i]<=min_right[i]) return arr[i]; return -1;}
0
sadhvik03033 months ago
python 3:
def findElement(a, n): ele=-1 big=a[0] small=a[len(a)-1] _max=list(range(n+1)) _min=list(range(n+1)) for i in range(0,len(a)): if(a[i]>big): big=a[i] _max[i]=big for j in range(len(a)-1,-1,-1): if(a[j]<small): small=a[j] _min[j]=small for i in range(0,len(a)): if (i!=0 and i!=len(a)-1): if(_min[i]==_max[i]): ele=_min[i] break return ele
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 402,
"s": 238,
"text": "Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it."
},
{
"code": null,
"e": 520,
"s": 402,
"text": "Note: Left and right side elements can be equal to required element. And extreme elements cannot be required element."
},
{
"code": null,
"e": 533,
"s": 522,
"text": "Example 1:"
},
{
"code": null,
"e": 668,
"s": 533,
"text": "Input:\nN = 4\nA[] = {4, 2, 5, 7}\nOutput:\n5\nExplanation:\nElements on left of 5 are smaller than 5\nand on right of it are greater than 5."
},
{
"code": null,
"e": 681,
"s": 670,
"text": "Example 2:"
},
{
"code": null,
"e": 723,
"s": 681,
"text": "Input:\nN = 3\nA[] = {11, 9, 12}\nOutput:\n-1"
},
{
"code": null,
"e": 975,
"s": 725,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function findElement() which takes the array A[] and its size N as inputs and returns the required element. If no such element present in array then return -1."
},
{
"code": null,
"e": 1039,
"s": 977,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1085,
"s": 1041,
"text": "Constraints:\n3 <= N <= 106\n1 <= A[i] <= 106"
},
{
"code": null,
"e": 1088,
"s": 1085,
"text": "+1"
},
{
"code": null,
"e": 1113,
"s": 1088,
"text": "ajaypal1920023 weeks ago"
},
{
"code": null,
"e": 1602,
"s": 1113,
"text": "// C++ solution\nint findElement(int a[], int n)\n{\n int l[n];\n int r[n];\n\n int maxi = a[0];\n for (int i = 0; i < n; i++)\n {\n maxi = max(maxi, a[i]);\n l[i] = maxi;\n }\n\n int mini = a[n - 1];\n for (int i = n - 1; i >= 0; i--)\n {\n\n mini = min(mini, a[i]);\n r[i] = mini;\n }\n\n for (int i = 1; i < n - 1; i++)\n {\n if (a[i] >= l[i - 1] and a[i] <= r[i + 1])\n {\n return a[i];\n }\n }\n\n return -1;\n}"
},
{
"code": null,
"e": 1604,
"s": 1602,
"text": "0"
},
{
"code": null,
"e": 1624,
"s": 1604,
"text": "jayesh293 weeks ago"
},
{
"code": null,
"e": 1644,
"s": 1624,
"text": "JAVA 0.64 seconds -"
},
{
"code": null,
"e": 2251,
"s": 1644,
"text": " public int findElement(int arr[], int n){\n int big = arr[0], small = arr[n-1],ele=-1;\n int[] max = new int[n];\n int[] min = new int[n];\n max[0]=big;min[n-1]=small;\n int lo = 1,hi=n-2;\n while(lo<n){\n if(arr[lo]>big){\n big = arr[lo];\n }\n max[lo++]=big;\n if(arr[hi]<small){\n small=arr[hi];\n }\n min[hi--]=small;\n }\n for(int i=1;i<n-1;i++){\n if(max[i]==min[i]){\n ele = arr[i];\n break;\n }\n }\n return ele; \n }"
},
{
"code": null,
"e": 2253,
"s": 2251,
"text": "0"
},
{
"code": null,
"e": 2280,
"s": 2253,
"text": "swapniltayal4221 month ago"
},
{
"code": null,
"e": 2701,
"s": 2280,
"text": "int findElement(int arr[], int n) { int maxi = INT_MIN; int mini = INT_MAX; int lrg[n]; int sml[n]; for (int i=0; i<n; i++){ maxi = max(arr[i], maxi); lrg[i] = maxi; } for (int i=n-1; i>=0; i--){ mini = min(arr[i], mini); sml[i] = mini; } for (int i=1; i<n-1; i++){ if (arr[i] >= lrg[i-1] && arr[i] <= sml[i+1]){ return arr[i]; } }return -1; }"
},
{
"code": null,
"e": 2703,
"s": 2701,
"text": "0"
},
{
"code": null,
"e": 2732,
"s": 2703,
"text": "pratikbhankhodiya1 month ago"
},
{
"code": null,
"e": 3092,
"s": 2732,
"text": "int findElement(int arr[], int n) {\n vector<int> left(n),right(n);\n for(int i=0,maxi=INT_MIN,j=n-1,mini=INT_MAX;i<n;i++,j--){\n maxi=max(maxi,arr[i]);\n left[i]=maxi;\n mini=min(mini,arr[j]);\n right[j]=mini;\n }\n for(int i=1;i<n-1;i++){\n if(left[i]<=arr[i] and right[i]>=arr[i]) return arr[i];\n }\n return -1;\n}"
},
{
"code": null,
"e": 3095,
"s": 3092,
"text": "-1"
},
{
"code": null,
"e": 3124,
"s": 3095,
"text": "hargunsinghsahni2 months ago"
},
{
"code": null,
"e": 3535,
"s": 3124,
"text": "int findElement(int arr[], int n) {\n int l[n],r[n];\n int mx=-1;\n for(int i=0;i<n;i++)\n {\n if(arr[i]>mx)\n mx=arr[i];\n l[i]=mx; \n }\n mx=INT_MAX;\n for(int i=n-1;i>=0;i--)\n {\n if(arr[i]<mx)\n mx=arr[i];\n r[i]=mx; \n }\n int ans=-1;\n for(int i=0;i<n;i++)\n if(arr[i]>=l[i] && arr[i]<=r[i] && i!=0 && i!=n-1 && ans==-1)\n ans=arr[i];\n return ans; \n}"
},
{
"code": null,
"e": 3537,
"s": 3535,
"text": "0"
},
{
"code": null,
"e": 3564,
"s": 3537,
"text": "pawan kumar 332 months ago"
},
{
"code": null,
"e": 3582,
"s": 3564,
"text": "// Working Code:-"
},
{
"code": null,
"e": 4050,
"s": 3584,
"text": "int findElement(int arr[], int n) { int left[n],right[n]; left[0] = -1; right[n-1] = -1; int max = arr[0]; int min = arr[n-1]; for(int i=1;i<n;i++) { left[i] = max; if(arr[i] > max) max = arr[i]; } for(int i=n-2;i>=0;i--) { right[i] = min; if(arr[i] < min) min = arr[i]; } for(int i=1;i<n-1;i++) { if(left[i]<=arr[i] && right[i]>=arr[i]) return arr[i]; } return -1; }"
},
{
"code": null,
"e": 4053,
"s": 4050,
"text": "+3"
},
{
"code": null,
"e": 4081,
"s": 4053,
"text": "vaibhav motwani2 months ago"
},
{
"code": null,
"e": 4455,
"s": 4081,
"text": "// Shortest solution with least conditionsint findElement(int arr[], int n) { int curr_ans=arr[0], return_value=-1; for(int i=0;i<n;i++){ if(arr[i]>=curr_ans && return_value == -1 && i!=0 && i!= n-1){ curr_ans = arr[i]; return_value = curr_ans; } else if(arr[i]<curr_ans){ return_value = -1; } } return return_value;}"
},
{
"code": null,
"e": 4457,
"s": 4455,
"text": "0"
},
{
"code": null,
"e": 4484,
"s": 4457,
"text": "gupta2411sumit2 months ago"
},
{
"code": null,
"e": 4514,
"s": 4484,
"text": "// Easy and fast c++ solution"
},
{
"code": null,
"e": 4552,
"s": 4516,
"text": "int findElement(int arr[], int n) {"
},
{
"code": null,
"e": 5239,
"s": 4552,
"text": " int left[n] ; int right[n] ; int mx = arr[0] ; int mn = arr[n-1] ; left[0] = 0 ; left[n-1] = 0 ; right[0] = 0 ; right[n-1] = 0 ; for( int i = 1 ; i<n-1 ; i++) { if(arr[i]<mx) { left[i] = 0 ; } else{ left[i] = 1 ; mx = arr[i] ; } } for( int i = n-2 ; i>0 ; i--) { if(arr[i]>mn) { right[i] = 0 ; } else{ right[i] = 1 ; mn = arr[i] ; } } for( int i = 0 ; i<n ; i++) { if( left[i]==1 && right[i]==1) { return arr[i] ; } } return -1 ;}"
},
{
"code": null,
"e": 5241,
"s": 5239,
"text": "0"
},
{
"code": null,
"e": 5269,
"s": 5241,
"text": "aarthinarayanan2 months ago"
},
{
"code": null,
"e": 5774,
"s": 5269,
"text": "int findElement(int arr[], int n) { int max_left[n],min_right[n]; max_left[0]=INT_MIN; min_right[n-1]=INT_MAX; for(int i=1;i<n;i++) { if(arr[i-1]>max_left[i-1]) max_left[i]=arr[i-1]; else max_left[i]=max_left[i-1]; } for(int i=n-2;i>=0;i--) { if(arr[i+1]<min_right[i+1]) min_right[i]=arr[i+1]; else min_right[i]=min_right[i+1]; } for(int i=1;i<n-1;i++) if(arr[i]>=max_left[i] && arr[i]<=min_right[i]) return arr[i]; return -1;}"
},
{
"code": null,
"e": 5776,
"s": 5774,
"text": "0"
},
{
"code": null,
"e": 5800,
"s": 5776,
"text": "sadhvik03033 months ago"
},
{
"code": null,
"e": 5810,
"s": 5800,
"text": "python 3:"
},
{
"code": null,
"e": 6256,
"s": 5810,
"text": "def findElement(a, n): ele=-1 big=a[0] small=a[len(a)-1] _max=list(range(n+1)) _min=list(range(n+1)) for i in range(0,len(a)): if(a[i]>big): big=a[i] _max[i]=big for j in range(len(a)-1,-1,-1): if(a[j]<small): small=a[j] _min[j]=small for i in range(0,len(a)): if (i!=0 and i!=len(a)-1): if(_min[i]==_max[i]): ele=_min[i] break return ele "
},
{
"code": null,
"e": 6402,
"s": 6256,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6438,
"s": 6402,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6448,
"s": 6438,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6458,
"s": 6448,
"text": "\nContest\n"
},
{
"code": null,
"e": 6521,
"s": 6458,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6669,
"s": 6521,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6877,
"s": 6669,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6983,
"s": 6877,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Matplotlib.figure.Figure.subplots_adjust() in Python - GeeksforGeeks
|
03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The subplots_adjust() method figure module of matplotlib library is used to Update the SubplotParams with kwargs.
Syntax: subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
Parameters: This method accept the following parameters that are discussed below:
left : This parameter is the left side of the subplots of the figure.
right : This parameter is the right side of the subplots of the figure.
bottom : This parameter is the bottom of the subplots of the figure.
top : This parameter is the top of the subplots of the figure.
wspace : This parameter is the amount of width reserved for space between subplots expressed as a fraction of the average axis width.
hspace : This parameter is the amount of height reserved for space between subplots expressed as a fraction of the average axis height.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.subplots_adjust() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = [1, 2, 3, 4]y = [1, 4, 9, 16] fig = plt.figure()axs = fig.subplots() axs.plot(x, y) fig.subplots_adjust(bottom = 0.15) fig.suptitle("""matplotlib.figure.Figure.subplots_adjust()function Example\n\n""", fontweight ="bold") fig.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox fig, ax = plt.subplots()fig.subplots_adjust(bottom = 0.2) t = np.arange(-2.0, 2.0, 0.001)s = np.sin(t)+np.cos(2 * t) initial_text = "sin(t) + cos(2t)"l, = ax.plot(t, s, lw = 2) def submit(text): ydata = eval(text) l.set_ydata(ydata) ax.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() axbox = plt.axes([0.4, 0.05, 0.3, 0.075]) text_box = TextBox(axbox, 'Formula Used : ', initial = initial_text)text_box.on_submit(submit) fig.suptitle("""matplotlib.figure.Figure.subplots_adjust()function Example\n\n""", fontweight ="bold") fig.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 24580,
"s": 24552,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 24891,
"s": 24580,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 25005,
"s": 24891,
"text": "The subplots_adjust() method figure module of matplotlib library is used to Update the SubplotParams with kwargs."
},
{
"code": null,
"e": 25107,
"s": 25005,
"text": "Syntax: subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)"
},
{
"code": null,
"e": 25189,
"s": 25107,
"text": "Parameters: This method accept the following parameters that are discussed below:"
},
{
"code": null,
"e": 25259,
"s": 25189,
"text": "left : This parameter is the left side of the subplots of the figure."
},
{
"code": null,
"e": 25331,
"s": 25259,
"text": "right : This parameter is the right side of the subplots of the figure."
},
{
"code": null,
"e": 25400,
"s": 25331,
"text": "bottom : This parameter is the bottom of the subplots of the figure."
},
{
"code": null,
"e": 25463,
"s": 25400,
"text": "top : This parameter is the top of the subplots of the figure."
},
{
"code": null,
"e": 25597,
"s": 25463,
"text": "wspace : This parameter is the amount of width reserved for space between subplots expressed as a fraction of the average axis width."
},
{
"code": null,
"e": 25733,
"s": 25597,
"text": "hspace : This parameter is the amount of height reserved for space between subplots expressed as a fraction of the average axis height."
},
{
"code": null,
"e": 25782,
"s": 25733,
"text": "Returns: This method does not returns any value."
},
{
"code": null,
"e": 25886,
"s": 25782,
"text": "Below examples illustrate the matplotlib.figure.Figure.subplots_adjust() function in matplotlib.figure:"
},
{
"code": null,
"e": 25897,
"s": 25886,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = [1, 2, 3, 4]y = [1, 4, 9, 16] fig = plt.figure()axs = fig.subplots() axs.plot(x, y) fig.subplots_adjust(bottom = 0.15) fig.suptitle(\"\"\"matplotlib.figure.Figure.subplots_adjust()function Example\\n\\n\"\"\", fontweight =\"bold\") fig.show() ",
"e": 26235,
"s": 25897,
"text": null
},
{
"code": null,
"e": 26243,
"s": 26235,
"text": "Output:"
},
{
"code": null,
"e": 26254,
"s": 26243,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox fig, ax = plt.subplots()fig.subplots_adjust(bottom = 0.2) t = np.arange(-2.0, 2.0, 0.001)s = np.sin(t)+np.cos(2 * t) initial_text = \"sin(t) + cos(2t)\"l, = ax.plot(t, s, lw = 2) def submit(text): ydata = eval(text) l.set_ydata(ydata) ax.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() axbox = plt.axes([0.4, 0.05, 0.3, 0.075]) text_box = TextBox(axbox, 'Formula Used : ', initial = initial_text)text_box.on_submit(submit) fig.suptitle(\"\"\"matplotlib.figure.Figure.subplots_adjust()function Example\\n\\n\"\"\", fontweight =\"bold\") fig.show() ",
"e": 26965,
"s": 26254,
"text": null
},
{
"code": null,
"e": 26973,
"s": 26965,
"text": "Output:"
},
{
"code": null,
"e": 26997,
"s": 26973,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 27015,
"s": 26997,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27022,
"s": 27015,
"text": "Python"
},
{
"code": null,
"e": 27120,
"s": 27022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27138,
"s": 27120,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27170,
"s": 27138,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27212,
"s": 27170,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27238,
"s": 27212,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27275,
"s": 27238,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27319,
"s": 27275,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27348,
"s": 27319,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27373,
"s": 27348,
"text": "sum() function in Python"
},
{
"code": null,
"e": 27429,
"s": 27373,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Bootstrap dropdown closing when clicked in HTML
|
As you may have seen, whenever you open a dropdown, and click anywhere else, the dropdown close.
By using the below given code, the dropdown menu can be kept open after click−
$('#myDropdown').on('hide.bs.dropdown', function () {
return false;
});
Another option is to handle the clickevent −
The click event can also be handled byusing the following code. The event.stopPropagation() method stopsthe bubbling of an event to parent elements. It prevents any parentevent handlers from being executed −
$('#myDropdown .dropdown-menu').on({
"click":function(e) {
e.stopPropagation();
}
});
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "As you may have seen, whenever you open a dropdown, and click anywhere else, the dropdown close. "
},
{
"code": null,
"e": 1239,
"s": 1160,
"text": "By using the below given code, the dropdown menu can be kept open after click−"
},
{
"code": null,
"e": 1314,
"s": 1239,
"text": "$('#myDropdown').on('hide.bs.dropdown', function () {\n return false;\n});"
},
{
"code": null,
"e": 1359,
"s": 1314,
"text": "Another option is to handle the clickevent −"
},
{
"code": null,
"e": 1567,
"s": 1359,
"text": "The click event can also be handled byusing the following code. The event.stopPropagation() method stopsthe bubbling of an event to parent elements. It prevents any parentevent handlers from being executed −"
},
{
"code": null,
"e": 1667,
"s": 1567,
"text": "$('#myDropdown .dropdown-menu').on({\n \"click\":function(e) {\n e.stopPropagation();\n }\n});"
}
] |
Combine keys in a list of dictionaries in Python - GeeksforGeeks
|
22 Jun, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let’s discuss a way in which this task can be performed.
Input : test_list = [{‘a’: 6}, {‘b’: 2}, {‘a’: 9}, {‘b’: 7}]Output : [{‘b’: 2, ‘a’: 6}, {‘b’: 7, ‘a’: 9}]
Input : test_list = [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]Output : [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]
Method : loop + ** operatorThe combination of above functions can be used to solve this problem. In this, we use brute force to construct a new dictionary and add keys only if that is not added in current. The task of merging dictionaries is by unpacking the initial dictionaries using “**” operator, and then packing again with dictionary with no repeated key and new one, using the usual dictionary initialization construct {}.
# Python3 code to demonstrate working of # Merge Similar Dictionaries in List# Using loop + "**" operator # initializing listtest_list = [{'gfg' : 1}, {'is' : 2}, {'best' : 3}, {'gfg' : 5}, {'is' : 17}, {'best' : 14}, {'gfg' : 7}, {'is' : 8}, {'best' : 10},] # printing original listprint("The original list is : " + str(test_list)) # Merge Similar Dictionaries in List# Using loop + "**" operatorres = [{}]for sub in test_list: if list(sub)[0] not in res[-1]: res[-1] = {**res[-1], **sub} else: res.append(sub) # printing result print("The merged dictionaries : " + str(res))
The original list is : [{‘gfg’: 1}, {‘is’: 2}, {‘best’: 3}, {‘gfg’: 5}, {‘is’: 17}, {‘best’: 14}, {‘gfg’: 7}, {‘is’: 8}, {‘best’: 10}]The merged dictionaries : [{‘best’: 3, ‘is’: 2, ‘gfg’: 1}, {‘best’: 14, ‘is’: 17, ‘gfg’: 5}, {‘best’: 10, ‘is’: 8, ‘gfg’: 7}]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 24561,
"s": 24292,
"text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let’s discuss a way in which this task can be performed."
},
{
"code": null,
"e": 24667,
"s": 24561,
"text": "Input : test_list = [{‘a’: 6}, {‘b’: 2}, {‘a’: 9}, {‘b’: 7}]Output : [{‘b’: 2, ‘a’: 6}, {‘b’: 7, ‘a’: 9}]"
},
{
"code": null,
"e": 24757,
"s": 24667,
"text": "Input : test_list = [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]Output : [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]"
},
{
"code": null,
"e": 25187,
"s": 24757,
"text": "Method : loop + ** operatorThe combination of above functions can be used to solve this problem. In this, we use brute force to construct a new dictionary and add keys only if that is not added in current. The task of merging dictionaries is by unpacking the initial dictionaries using “**” operator, and then packing again with dictionary with no repeated key and new one, using the usual dictionary initialization construct {}."
},
{
"code": "# Python3 code to demonstrate working of # Merge Similar Dictionaries in List# Using loop + \"**\" operator # initializing listtest_list = [{'gfg' : 1}, {'is' : 2}, {'best' : 3}, {'gfg' : 5}, {'is' : 17}, {'best' : 14}, {'gfg' : 7}, {'is' : 8}, {'best' : 10},] # printing original listprint(\"The original list is : \" + str(test_list)) # Merge Similar Dictionaries in List# Using loop + \"**\" operatorres = [{}]for sub in test_list: if list(sub)[0] not in res[-1]: res[-1] = {**res[-1], **sub} else: res.append(sub) # printing result print(\"The merged dictionaries : \" + str(res)) ",
"e": 25815,
"s": 25187,
"text": null
},
{
"code": null,
"e": 26075,
"s": 25815,
"text": "The original list is : [{‘gfg’: 1}, {‘is’: 2}, {‘best’: 3}, {‘gfg’: 5}, {‘is’: 17}, {‘best’: 14}, {‘gfg’: 7}, {‘is’: 8}, {‘best’: 10}]The merged dictionaries : [{‘best’: 3, ‘is’: 2, ‘gfg’: 1}, {‘best’: 14, ‘is’: 17, ‘gfg’: 5}, {‘best’: 10, ‘is’: 8, ‘gfg’: 7}]"
},
{
"code": null,
"e": 26104,
"s": 26077,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 26111,
"s": 26104,
"text": "Python"
},
{
"code": null,
"e": 26127,
"s": 26111,
"text": "Python Programs"
},
{
"code": null,
"e": 26225,
"s": 26127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26257,
"s": 26225,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26313,
"s": 26257,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26355,
"s": 26313,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26397,
"s": 26355,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26419,
"s": 26397,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26441,
"s": 26419,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26487,
"s": 26441,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26526,
"s": 26487,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26564,
"s": 26526,
"text": "Python | Convert a list to dictionary"
}
] |
Express.js – app.listen() Method
|
The app.listen() method binds itself with the specified host and port to bind and listen for any connections. If the port is not defined or 0, an arbitrary unused port will be assigned by the operating system that is mainly used for automated tasks like testing, etc.
The app object returned by express() is a JavaScript function, that is passed to Node’s HTTP servers as a callback which handles the requests. This makes the application to provide both HTTP and HTTPS versions of the same app with the same code base, as the app does not inherit from these.
app.listen([port], [host], [backlog], [callback])
Create a file with the name "appListen.js" and copy the following code snippet.
After creating the file, use the command "node appListen.js" to run this code.
// app.listen() Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
C:\home\node>> node appListen.js
Server listening on PORT 3000
Let’s take a look at one more example.
// app.listen() Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
// Assigning a port that is already in use
var PORT = 80;
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
C:\home\node>> node appListen.js
Server listening on PORT 80
|
[
{
"code": null,
"e": 1330,
"s": 1062,
"text": "The app.listen() method binds itself with the specified host and port to bind and listen for any connections. If the port is not defined or 0, an arbitrary unused port will be assigned by the operating system that is mainly used for automated tasks like testing, etc."
},
{
"code": null,
"e": 1621,
"s": 1330,
"text": "The app object returned by express() is a JavaScript function, that is passed to Node’s HTTP servers as a callback which handles the requests. This makes the application to provide both HTTP and HTTPS versions of the same app with the same code base, as the app does not inherit from these."
},
{
"code": null,
"e": 1671,
"s": 1621,
"text": "app.listen([port], [host], [backlog], [callback])"
},
{
"code": null,
"e": 1830,
"s": 1671,
"text": "Create a file with the name \"appListen.js\" and copy the following code snippet.\nAfter creating the file, use the command \"node appListen.js\" to run this code."
},
{
"code": null,
"e": 2240,
"s": 1830,
"text": "// app.listen() Method Demo Example\n\n// Importing the express module\nvar express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n\n// Initializing the router from express\nvar router = express.Router();\nvar PORT = 3000;\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": 2303,
"s": 2240,
"text": "C:\\home\\node>> node appListen.js\nServer listening on PORT 3000"
},
{
"code": null,
"e": 2342,
"s": 2303,
"text": "Let’s take a look at one more example."
},
{
"code": null,
"e": 2794,
"s": 2342,
"text": "// app.listen() Method Demo Example\n\n// Importing the express module\nvar express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n\n// Initializing the router from express\nvar router = express.Router();\n\n// Assigning a port that is already in use\nvar PORT = 80;\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": 2855,
"s": 2794,
"text": "C:\\home\\node>> node appListen.js\nServer listening on PORT 80"
}
] |
What is Decentralized Voting Application (DApps)? - GeeksforGeeks
|
08 Sep, 2021
The Project Name is Decentralized Voting Application (DApps) which is built on Solidity Language. This Project showcases a lot of Solidity’s features. It implements a voting contract. Of course, the main problem of electronic voting is how to prevent to assign the duplicate Vote.
1. Contract: A contract is just like a class in Solidity which consists (its functions) and data (its state) that resides at a specific address on the Ethereum Blockchain. In each Contract, we can define State Variables, Methods, and Events, etc. A smart contract runs exactly as programmed without any possibility of downtime, censorship, fraud, and third-party interference.
2. Structure: The Structure is Collection of different type of Data Types same like C and C++, which is shown in the following example:
struct Voter{
bool authorized;
bool voted;
}
3. Mapping: Mapping is just like Hash tables It stores the value based on key. They cannot be used as parameters or return parameters of contract functions that are publicly visible. You cannot iterate over mappings, i.e. you cannot enumerate their keys. It possible to implement a data structure on top of them and iterate over that.
Example:
mapping(address=>Voter) info;
4. Modifier: Modifiers are used to easily change the behavior of a function. They can automatically check conditions before executing the functions.
modifier ownerOn() {
require(msg.sender==owner);
_;
}
function temaAF(address _address) public {
require(!info[_address].voted, "already voted person"); //If already not vote
require(info[_address].authorized, "You Have No Right for Vote");
info[_address].voted = true;
teamA++;
totalVotes++;
}
Explanation:
require(!info[_address].voted, "already voted person");
Firstly we need to verify that person is Voted Or Not. If Person is voted then stop to proceed in the code otherwise proceed rest of code.
Solidity
// Solidity program to demonstrate// DApps pragma solidity 0.5.11; // Smart Contract for the Voting applicationcontract VotingForTopper { // Refer to the owner address owner; // Declaring the public variable 'purpose' // to demonstrate the purpose of voting string public purpose; // Defining a structure with boolean // variables authorized and voted struct Voter{ bool authorized; bool voted; } // Declaring the unsigned integer // variables totalVotes, and for the //3 teams- A,B, and C uint totalVotes; uint teamA; uint teamB; uint teamC; // Creating a mapping for the total Votes mapping(address=>Voter) info; // Defining a constructor indicating // the purpose of voting constructor( string memory _name) public{ purpose = _name; owner = msg.sender; } // Defining a modifier to // verify the ownership modifier ownerOn() { require(msg.sender==owner); _; } // Defining a function to verify // the person is voted or not function authorize( address _person) ownerOn public { info[_person].authorized= true; } // Defining a function to check and // skip the code if the person is already // voted else allow to vote and // calculate totalvotes for team A function temaAF(address _address) public { require( !info[_address].voted, "already voted person"); require( info[_address].authorized, "You Have No Right for Vote"); info[_address].voted = true; teamA++; totalVotes++; } // Defining a function to check // and skip the code if the person // is already voted else allow to vote // and calculate totalvotes for team B function temaBF(address _address) public { require( !info[_address].voted, "already voted person"); require( info[_address].authorized, "You Have No Right for Vote"); teamB++; info[_address].voted = true; totalVotes++; } // Defining a function to check // and skip the code if the person // is already voted else allow to vote // and calculate totalvotes for team C function temaCF(address _address) public returns( string memory){ require( !info[_address].voted, "already voted person"); require( info[_address].authorized, "You Have No Right for Vote"); info[_address].voted = true; teamC++; totalVotes++; return("Thanks for Voting"); } function totalVotesF() public view returns(uint){ return totalVotes; } // Defining a function to announce // the result of voting and // the name of the winning team function resultOfVoting() public view returns( string memory){ if(teamA>teamB){ if(teamA>teamC){ return"A is Winning"; } else if(teamC>teamA){ return "C is Winning"; } } else if(teamB>teamC) { return "B is Winning"; } else if( teamA==teamB && teamA==teamC || teamB==teamC ){ return "No One is Winning"; } } }
rs1686740
BlockChain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Solidity - Constructors
Solidity - Operators
Mathematical Operations in Solidity
Solidity - Fall Back Function
Solidity - Inheritance
Dynamic Arrays and its Operations in Solidity
Introduction to Solidity
Solidity - Basics of Interface
Creating a Smart Contract that Returns Address and Balance of Owner using Solidity
Solidity - While, Do-While, and For Loop
|
[
{
"code": null,
"e": 24500,
"s": 24472,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 24781,
"s": 24500,
"text": "The Project Name is Decentralized Voting Application (DApps) which is built on Solidity Language. This Project showcases a lot of Solidity’s features. It implements a voting contract. Of course, the main problem of electronic voting is how to prevent to assign the duplicate Vote."
},
{
"code": null,
"e": 25158,
"s": 24781,
"text": "1. Contract: A contract is just like a class in Solidity which consists (its functions) and data (its state) that resides at a specific address on the Ethereum Blockchain. In each Contract, we can define State Variables, Methods, and Events, etc. A smart contract runs exactly as programmed without any possibility of downtime, censorship, fraud, and third-party interference."
},
{
"code": null,
"e": 25296,
"s": 25158,
"text": "2. Structure: The Structure is Collection of different type of Data Types same like C and C++, which is shown in the following example: "
},
{
"code": null,
"e": 25367,
"s": 25296,
"text": "struct Voter{\n bool authorized;\n bool voted;\n }"
},
{
"code": null,
"e": 25704,
"s": 25367,
"text": "3. Mapping: Mapping is just like Hash tables It stores the value based on key. They cannot be used as parameters or return parameters of contract functions that are publicly visible. You cannot iterate over mappings, i.e. you cannot enumerate their keys. It possible to implement a data structure on top of them and iterate over that. "
},
{
"code": null,
"e": 25714,
"s": 25704,
"text": "Example: "
},
{
"code": null,
"e": 25745,
"s": 25714,
"text": "mapping(address=>Voter) info; "
},
{
"code": null,
"e": 25896,
"s": 25745,
"text": "4. Modifier: Modifiers are used to easily change the behavior of a function. They can automatically check conditions before executing the functions. "
},
{
"code": null,
"e": 26257,
"s": 25896,
"text": "modifier ownerOn() {\n require(msg.sender==owner);\n _;\n }\nfunction temaAF(address _address) public {\n require(!info[_address].voted, \"already voted person\"); //If already not vote\n require(info[_address].authorized, \"You Have No Right for Vote\");\n info[_address].voted = true;\n teamA++;\n totalVotes++;\n }"
},
{
"code": null,
"e": 26270,
"s": 26257,
"text": "Explanation:"
},
{
"code": null,
"e": 26327,
"s": 26270,
"text": "require(!info[_address].voted, \"already voted person\"); "
},
{
"code": null,
"e": 26466,
"s": 26327,
"text": "Firstly we need to verify that person is Voted Or Not. If Person is voted then stop to proceed in the code otherwise proceed rest of code."
},
{
"code": null,
"e": 26475,
"s": 26466,
"text": "Solidity"
},
{
"code": "// Solidity program to demonstrate// DApps pragma solidity 0.5.11; // Smart Contract for the Voting applicationcontract VotingForTopper { // Refer to the owner address owner; // Declaring the public variable 'purpose' // to demonstrate the purpose of voting string public purpose; // Defining a structure with boolean // variables authorized and voted struct Voter{ bool authorized; bool voted; } // Declaring the unsigned integer // variables totalVotes, and for the //3 teams- A,B, and C uint totalVotes; uint teamA; uint teamB; uint teamC; // Creating a mapping for the total Votes mapping(address=>Voter) info; // Defining a constructor indicating // the purpose of voting constructor( string memory _name) public{ purpose = _name; owner = msg.sender; } // Defining a modifier to // verify the ownership modifier ownerOn() { require(msg.sender==owner); _; } // Defining a function to verify // the person is voted or not function authorize( address _person) ownerOn public { info[_person].authorized= true; } // Defining a function to check and // skip the code if the person is already // voted else allow to vote and // calculate totalvotes for team A function temaAF(address _address) public { require( !info[_address].voted, \"already voted person\"); require( info[_address].authorized, \"You Have No Right for Vote\"); info[_address].voted = true; teamA++; totalVotes++; } // Defining a function to check // and skip the code if the person // is already voted else allow to vote // and calculate totalvotes for team B function temaBF(address _address) public { require( !info[_address].voted, \"already voted person\"); require( info[_address].authorized, \"You Have No Right for Vote\"); teamB++; info[_address].voted = true; totalVotes++; } // Defining a function to check // and skip the code if the person // is already voted else allow to vote // and calculate totalvotes for team C function temaCF(address _address) public returns( string memory){ require( !info[_address].voted, \"already voted person\"); require( info[_address].authorized, \"You Have No Right for Vote\"); info[_address].voted = true; teamC++; totalVotes++; return(\"Thanks for Voting\"); } function totalVotesF() public view returns(uint){ return totalVotes; } // Defining a function to announce // the result of voting and // the name of the winning team function resultOfVoting() public view returns( string memory){ if(teamA>teamB){ if(teamA>teamC){ return\"A is Winning\"; } else if(teamC>teamA){ return \"C is Winning\"; } } else if(teamB>teamC) { return \"B is Winning\"; } else if( teamA==teamB && teamA==teamC || teamB==teamC ){ return \"No One is Winning\"; } } }",
"e": 29872,
"s": 26475,
"text": null
},
{
"code": null,
"e": 29882,
"s": 29872,
"text": "rs1686740"
},
{
"code": null,
"e": 29893,
"s": 29882,
"text": "BlockChain"
},
{
"code": null,
"e": 29902,
"s": 29893,
"text": "Solidity"
},
{
"code": null,
"e": 30000,
"s": 29902,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30024,
"s": 30000,
"text": "Solidity - Constructors"
},
{
"code": null,
"e": 30045,
"s": 30024,
"text": "Solidity - Operators"
},
{
"code": null,
"e": 30081,
"s": 30045,
"text": "Mathematical Operations in Solidity"
},
{
"code": null,
"e": 30111,
"s": 30081,
"text": "Solidity - Fall Back Function"
},
{
"code": null,
"e": 30134,
"s": 30111,
"text": "Solidity - Inheritance"
},
{
"code": null,
"e": 30180,
"s": 30134,
"text": "Dynamic Arrays and its Operations in Solidity"
},
{
"code": null,
"e": 30205,
"s": 30180,
"text": "Introduction to Solidity"
},
{
"code": null,
"e": 30236,
"s": 30205,
"text": "Solidity - Basics of Interface"
},
{
"code": null,
"e": 30319,
"s": 30236,
"text": "Creating a Smart Contract that Returns Address and Balance of Owner using Solidity"
}
] |
Perl | Hashes - GeeksforGeeks
|
13 Apr, 2021
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value associated with the key. Each key is associated with a single value.Example:
my%rateof{mango} = 45;
Question arises when to use Array and when to use Hashes?
If the things are in order, then go for the array. For Example:
1. A list of people in a bank queue.
2. A list of people in railway reservation line.
3. A list of files to read.
If the things we have are not in order then go for Hashes. For example:
1. An index of surname looked up by the first name.
2. An index showing the size of files looked up by name.
Empty Hash: A hash variable without any key is called empty hash.
Example:
my %rateof;
Here rateof is the hash variable.
Inserting a key/value pair into a Hash: Keys are always of string type and values always of scalar type.
Example:
$rateof{'mango'} = 45;
Here the key is mango and value is 45.
Initialization of Hash & Fetching an element of a Hash: A hash variable can be initialized with key/value pairs during its declaration time. There are two ways to initialize a hash variable. One is using => which is called the fat arrow or fat comma. The second one is to put the key/value pairs in double quotes(“”) separated by a comma(,). Using fat commas provide an alternative as you can leave double quotes around the key. To access the individual elements from a hash you can use a dollar sign($) followed by a hash variable followed by the key under curly braces. While accessing the key/value pair if you passed the key that doesn’t present in it then it will return an undefined value or if you switched on the warning it will show the warning.
Example:
Perl
# Perl program to demonstrate the# Fetching an element of a Hash # creating hash%rateof = ('Mango' => 45, 'Orange' => 30, 'Grapes' => 40); # Fetching an element of Hashprint "$rateof{'Mango'}\n";print "$rateof{'Orange'}\n";print "$rateof{'Grapes'}\n";
Output:
45
30
40
Explanation: To access three keys Mango, Orange, Grapes and to print the values associated with it just use the dollar sign followed by Key. The print statement will print the value associated with that key.
Empty values in a Hash: Generally, you can’t assign empty values to the key of the hash. But in Perl, there is an alternative to provide empty values to Hashes. By using undef function. “undef” can be assigned to new or existing key based on the user’s need. Putting undef in double quotes will make it a string not an empty value.
Perl
# Perl program to demonstrate the# empty values of a Hash #use warnings; # creating hash%rateof = ('Mango' => 45, 'Orange' => undef, 'Grapes' => 40); # Fetching an element of Hashprint "$rateof{'Mango'}\n";print "$rateof{'Orange'}\n";print "$rateof{'Grapes'}\n";
Output:
45
40
Iterating over hashes: To access the value in a hash user must the know the key associate to that value. If the keys of a hash are not known prior then with the help of keys function, user can get the list of keys and can iterate over those keys.Example:
my @fruits = keys %rateof;
for my $fruit (@fruits) {
print "The color of '$fruit' is $rateofof{$fruit}\n";
}
Size of a hash: The number of key/value pairs is known as the size of hash. To get the size, the first user has to create an array of keys or values and then he can get the size of the array.
Syntax:
print scalar keys % hash_variable_name;
Example:
Perl
# Perl program to find the size of a Hash #use warnings; # creating hash%rateof = ('Mango' => 64, 'Apple' => 54, 'Grapes' => 44, 'Strawberry'=>23); # creating array of keys@keys = keys %rateof;$size = @keys;print "Hash size using Keys is: $size\n"; # creating hash of values@values = values %rateof;$size = @values;print "Hash size using Values is: $size\n";
Output:
Hash size using Keys is: 4
Hash size using Values is: 4
Adding and Removing Elements in Hashes:User can easily add a new pair of key/values into a hash using simple assignment operator.
Example 1: Addition of element in hash
Perl
# Perl program to add an element in a hash #use warnings; # creating hash%rateof = ('Mango' => 64, 'Apple' => 54, 'Grapes' => 44, 'Strawberry'=>23); # array of keys@keys = keys %rateof; $size = @keys;print "SIZE OF HASH BEFORE ADDING: is $size\n"; # Adding new key/value pair into hash$rateof{'Potato'} = 20; # array of keys@keys= keys %rateof; $size = @keys;print "SIZE OF HASH AFTER ADDING: is $size\n";
Output:
SIZE OF HASH BEFORE ADDING: is 4
SIZE OF HASH AFTER ADDING: is 5
Example 2: Deleting an element from hash using delete function
Perl
# Perl program to element from hash #use warnings; # creating hash%rateof = ('Mango' => 64, 'Apple' => 54, 'Grapes' => 44, 'Strawberry'=>23); # creating array of keys@keys= keys %rateof; # finding size of hash$size = @keys;print "SIZE OF HASH BEFORE DELETING: $size\n"; # using delete functiondelete $rateof{'Mango'}; # creating array of keys@keys= keys %rateof; # finding size of hash$size = @keys;print "SIZE OF HASH AFTER DELETING: $size\n";
Output:
SIZE OF HASH BEFORE DELETING: 4
SIZE OF HASH AFTER DELETING: 3
Akanksha_Rai
shubham_singh
simranarora5sos
Perl-hashes
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Polymorphism in OOPs
Perl | Arrays
Perl | Arrays (push, pop, shift, unshift)
Perl | length() Function
Perl | sleep() Function
Perl | Data Types
Perl Tutorial - Learn Perl With Examples
Perl | Boolean Values
Introduction to Perl
Perl | Automatic String to Number Conversion or Casting
|
[
{
"code": null,
"e": 24146,
"s": 24118,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 24572,
"s": 24146,
"text": "Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value associated with the key. Each key is associated with a single value.Example: "
},
{
"code": null,
"e": 24595,
"s": 24572,
"text": "my%rateof{mango} = 45;"
},
{
"code": null,
"e": 24654,
"s": 24595,
"text": "Question arises when to use Array and when to use Hashes? "
},
{
"code": null,
"e": 24720,
"s": 24654,
"text": "If the things are in order, then go for the array. For Example: "
},
{
"code": null,
"e": 24834,
"s": 24720,
"text": "1. A list of people in a bank queue.\n2. A list of people in railway reservation line.\n3. A list of files to read."
},
{
"code": null,
"e": 24907,
"s": 24834,
"text": "If the things we have are not in order then go for Hashes. For example: "
},
{
"code": null,
"e": 25016,
"s": 24907,
"text": "1. An index of surname looked up by the first name.\n2. An index showing the size of files looked up by name."
},
{
"code": null,
"e": 25083,
"s": 25016,
"text": "Empty Hash: A hash variable without any key is called empty hash. "
},
{
"code": null,
"e": 25093,
"s": 25083,
"text": "Example: "
},
{
"code": null,
"e": 25105,
"s": 25093,
"text": "my %rateof;"
},
{
"code": null,
"e": 25139,
"s": 25105,
"text": "Here rateof is the hash variable."
},
{
"code": null,
"e": 25245,
"s": 25139,
"text": "Inserting a key/value pair into a Hash: Keys are always of string type and values always of scalar type. "
},
{
"code": null,
"e": 25255,
"s": 25245,
"text": "Example: "
},
{
"code": null,
"e": 25279,
"s": 25255,
"text": "$rateof{'mango'} = 45; "
},
{
"code": null,
"e": 25318,
"s": 25279,
"text": "Here the key is mango and value is 45."
},
{
"code": null,
"e": 26074,
"s": 25318,
"text": "Initialization of Hash & Fetching an element of a Hash: A hash variable can be initialized with key/value pairs during its declaration time. There are two ways to initialize a hash variable. One is using => which is called the fat arrow or fat comma. The second one is to put the key/value pairs in double quotes(“”) separated by a comma(,). Using fat commas provide an alternative as you can leave double quotes around the key. To access the individual elements from a hash you can use a dollar sign($) followed by a hash variable followed by the key under curly braces. While accessing the key/value pair if you passed the key that doesn’t present in it then it will return an undefined value or if you switched on the warning it will show the warning. "
},
{
"code": null,
"e": 26085,
"s": 26074,
"text": "Example: "
},
{
"code": null,
"e": 26090,
"s": 26085,
"text": "Perl"
},
{
"code": "# Perl program to demonstrate the# Fetching an element of a Hash # creating hash%rateof = ('Mango' => 45, 'Orange' => 30, 'Grapes' => 40); # Fetching an element of Hashprint \"$rateof{'Mango'}\\n\";print \"$rateof{'Orange'}\\n\";print \"$rateof{'Grapes'}\\n\";",
"e": 26342,
"s": 26090,
"text": null
},
{
"code": null,
"e": 26352,
"s": 26342,
"text": "Output: "
},
{
"code": null,
"e": 26361,
"s": 26352,
"text": "45\n30\n40"
},
{
"code": null,
"e": 26569,
"s": 26361,
"text": "Explanation: To access three keys Mango, Orange, Grapes and to print the values associated with it just use the dollar sign followed by Key. The print statement will print the value associated with that key."
},
{
"code": null,
"e": 26902,
"s": 26569,
"text": "Empty values in a Hash: Generally, you can’t assign empty values to the key of the hash. But in Perl, there is an alternative to provide empty values to Hashes. By using undef function. “undef” can be assigned to new or existing key based on the user’s need. Putting undef in double quotes will make it a string not an empty value. "
},
{
"code": null,
"e": 26907,
"s": 26902,
"text": "Perl"
},
{
"code": "# Perl program to demonstrate the# empty values of a Hash #use warnings; # creating hash%rateof = ('Mango' => 45, 'Orange' => undef, 'Grapes' => 40); # Fetching an element of Hashprint \"$rateof{'Mango'}\\n\";print \"$rateof{'Orange'}\\n\";print \"$rateof{'Grapes'}\\n\";",
"e": 27170,
"s": 26907,
"text": null
},
{
"code": null,
"e": 27180,
"s": 27170,
"text": "Output: "
},
{
"code": null,
"e": 27187,
"s": 27180,
"text": "45\n\n40"
},
{
"code": null,
"e": 27444,
"s": 27187,
"text": "Iterating over hashes: To access the value in a hash user must the know the key associate to that value. If the keys of a hash are not known prior then with the help of keys function, user can get the list of keys and can iterate over those keys.Example: "
},
{
"code": null,
"e": 27557,
"s": 27444,
"text": "my @fruits = keys %rateof;\nfor my $fruit (@fruits) {\n print \"The color of '$fruit' is $rateofof{$fruit}\\n\";\n}"
},
{
"code": null,
"e": 27750,
"s": 27557,
"text": "Size of a hash: The number of key/value pairs is known as the size of hash. To get the size, the first user has to create an array of keys or values and then he can get the size of the array. "
},
{
"code": null,
"e": 27760,
"s": 27750,
"text": "Syntax: "
},
{
"code": null,
"e": 27800,
"s": 27760,
"text": "print scalar keys % hash_variable_name;"
},
{
"code": null,
"e": 27811,
"s": 27800,
"text": "Example: "
},
{
"code": null,
"e": 27816,
"s": 27811,
"text": "Perl"
},
{
"code": "# Perl program to find the size of a Hash #use warnings; # creating hash%rateof = ('Mango' => 64, 'Apple' => 54, 'Grapes' => 44, 'Strawberry'=>23); # creating array of keys@keys = keys %rateof;$size = @keys;print \"Hash size using Keys is: $size\\n\"; # creating hash of values@values = values %rateof;$size = @values;print \"Hash size using Values is: $size\\n\";",
"e": 28175,
"s": 27816,
"text": null
},
{
"code": null,
"e": 28184,
"s": 28175,
"text": "Output: "
},
{
"code": null,
"e": 28240,
"s": 28184,
"text": "Hash size using Keys is: 4\nHash size using Values is: 4"
},
{
"code": null,
"e": 28372,
"s": 28240,
"text": "Adding and Removing Elements in Hashes:User can easily add a new pair of key/values into a hash using simple assignment operator. "
},
{
"code": null,
"e": 28413,
"s": 28372,
"text": "Example 1: Addition of element in hash "
},
{
"code": null,
"e": 28418,
"s": 28413,
"text": "Perl"
},
{
"code": "# Perl program to add an element in a hash #use warnings; # creating hash%rateof = ('Mango' => 64, 'Apple' => 54, 'Grapes' => 44, 'Strawberry'=>23); # array of keys@keys = keys %rateof; $size = @keys;print \"SIZE OF HASH BEFORE ADDING: is $size\\n\"; # Adding new key/value pair into hash$rateof{'Potato'} = 20; # array of keys@keys= keys %rateof; $size = @keys;print \"SIZE OF HASH AFTER ADDING: is $size\\n\";",
"e": 28826,
"s": 28418,
"text": null
},
{
"code": null,
"e": 28836,
"s": 28826,
"text": "Output: "
},
{
"code": null,
"e": 28903,
"s": 28836,
"text": "SIZE OF HASH BEFORE ADDING: is 4\nSIZE OF HASH AFTER ADDING: is 5"
},
{
"code": null,
"e": 28968,
"s": 28903,
"text": "Example 2: Deleting an element from hash using delete function "
},
{
"code": null,
"e": 28973,
"s": 28968,
"text": "Perl"
},
{
"code": "# Perl program to element from hash #use warnings; # creating hash%rateof = ('Mango' => 64, 'Apple' => 54, 'Grapes' => 44, 'Strawberry'=>23); # creating array of keys@keys= keys %rateof; # finding size of hash$size = @keys;print \"SIZE OF HASH BEFORE DELETING: $size\\n\"; # using delete functiondelete $rateof{'Mango'}; # creating array of keys@keys= keys %rateof; # finding size of hash$size = @keys;print \"SIZE OF HASH AFTER DELETING: $size\\n\";",
"e": 29418,
"s": 28973,
"text": null
},
{
"code": null,
"e": 29428,
"s": 29418,
"text": "Output: "
},
{
"code": null,
"e": 29491,
"s": 29428,
"text": "SIZE OF HASH BEFORE DELETING: 4\nSIZE OF HASH AFTER DELETING: 3"
},
{
"code": null,
"e": 29506,
"s": 29493,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29520,
"s": 29506,
"text": "shubham_singh"
},
{
"code": null,
"e": 29536,
"s": 29520,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29548,
"s": 29536,
"text": "Perl-hashes"
},
{
"code": null,
"e": 29553,
"s": 29548,
"text": "Perl"
},
{
"code": null,
"e": 29558,
"s": 29553,
"text": "Perl"
},
{
"code": null,
"e": 29656,
"s": 29558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29665,
"s": 29656,
"text": "Comments"
},
{
"code": null,
"e": 29678,
"s": 29665,
"text": "Old Comments"
},
{
"code": null,
"e": 29706,
"s": 29678,
"text": "Perl | Polymorphism in OOPs"
},
{
"code": null,
"e": 29720,
"s": 29706,
"text": "Perl | Arrays"
},
{
"code": null,
"e": 29762,
"s": 29720,
"text": "Perl | Arrays (push, pop, shift, unshift)"
},
{
"code": null,
"e": 29787,
"s": 29762,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 29811,
"s": 29787,
"text": "Perl | sleep() Function"
},
{
"code": null,
"e": 29829,
"s": 29811,
"text": "Perl | Data Types"
},
{
"code": null,
"e": 29870,
"s": 29829,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 29892,
"s": 29870,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 29913,
"s": 29892,
"text": "Introduction to Perl"
}
] |
How Arrays are Passed to Functions in C/C++? - GeeksforGeeks
|
09 Jan, 2022
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array’s name.
In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). The below example demonstrates the same.
C++
C
// CPP Program to demonstrate passing// an array to a function is always treated// as a pointer#include <iostream>using namespace std; // Note that arr[] for fun is// just a pointer even if square// brackets are usedvoid fun(int arr[]) // SAME AS void fun(int *arr){ unsigned int n = sizeof(arr) / sizeof(arr[0]); cout << "\nArray size inside fun() is " << n;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; unsigned int n = sizeof(arr) / sizeof(arr[0]); cout << "Array size inside main() is " << n; fun(arr); return 0;}
#include <stdio.h>#include <stdlib.h>// Note that arr[] for fun is just a pointer even if square// brackets are usedvoid fun(int arr[]) // SAME AS void fun(int *arr){ unsigned int n = sizeof(arr)/sizeof(arr[0]); printf("\nArray size inside fun() is %d", n);} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; unsigned int n = sizeof(arr)/sizeof(arr[0]); printf("Array size inside main() is %d", n); fun(arr); return 0;}
Output
Array size inside main() is 8
Array size inside fun() is 1
Therefore in C, we must pass the size of the array as a parameter. Size may not be needed only in the case of ‘\0’ terminated character arrays, size can be determined by checking the end of string character.
Following is a simple example to show how arrays are typically passed in C:
C++
C
#include <iostream>using namespace std; void fun(int *arr, unsigned int n){ int i; for (i = 0; i < n; i++) cout <<" "<< arr[i];} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; unsigned int n = sizeof(arr)/sizeof(arr[0]); fun(arr, n); return 0;}
#include <stdio.h> void fun(int *arr, unsigned int n){ int i; for (i=0; i<n; i++) printf("%d ", arr[i]);} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; unsigned int n = sizeof(arr)/sizeof(arr[0]); fun(arr, n); return 0;}
Output
1 2 3 4 5 6 7 8
Exercise: Predict the output of the below C programs:
Program 1:
C++
C
// Program 1#include <iostream>using namespace std;void fun(int arr[], unsigned int n){ int i; for (i = 0; i < n; i++) cout << arr[i] << " ";} // Driver programint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; unsigned int n = sizeof(arr) / sizeof(arr[0]); fun(arr, n); return 0;}
#include <stdio.h>void fun(int arr[], unsigned int n){int i;for (i=0; i<n; i++) printf("%d ", arr[i]);} // Driver programint main(){int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};unsigned int n = sizeof(arr)/sizeof(arr[0]);fun(arr, n);return 0;}
Output
1 2 3 4 5 6 7 8
Program 2:
C++
C
// Program 2#include <iostream>using namespace std;void fun(int* arr){ int i; unsigned int n = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < n; i++) cout << " " << arr[i];} // Driver programint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; fun(arr); return 0;}
#include <stdio.h>void fun(int *arr){ int i; unsigned int n = sizeof(arr)/sizeof(arr[0]); for (i=0; i<n; i++) printf("%d ", arr[i]);} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; fun(arr); return 0;}
Output
1 2
Program 3:
C++
C
// Program 3#include <iostream>#include <string.h>using namespace std;void fun(char* arr){ int i; unsigned int n = strlen(arr); cout << "n = " << n << endl; for (i = 0; i < n; i++) cout << arr[i] << " ";} // Driver programint main(){ char arr[] = "geeksquiz"; fun(arr); return 0;}
#include <stdio.h>#include <string.h> void fun(char *arr){ int i; unsigned int n = strlen(arr); printf("n = %d\n", n); for (i=0; i<n; i++) printf("%c ", arr[i]);} // Driver programint main(){ char arr[] = "geeksquiz"; fun(arr); return 0;}
Output
n = 9
g e e k s q u i z
Program 4:
C++
C
// Program 4#include <bits/stdc++.h>#include <iostream>using namespace std; void fun(char* arr){ int i; unsigned int n = strlen(arr); cout << "n = " << n << "\n"; for (i = 0; i < n; i++) cout << " " << arr[i];} // Driver programint main(){ char arr[] = { 'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z' }; fun(arr); return 0;}
#include <stdio.h>#include <string.h> void fun(char *arr){ int i; unsigned int n = strlen(arr); printf("n = %d\n", n); for (i=0; i<n; i++) printf("%c ", arr[i]);} // Driver programint main(){ char arr[] = {'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z'}; fun(arr); return 0;}
Output
n = 11
g e e k s q u i z
NOTE: The character array in the above program is not ‘\0’ terminated. (See this for details)
Now These were some of the common approaches that we use but do you know that there is a better way to do the same. For this, we first need to look at the drawbacks of all the above-suggested methods:
Drawbacks:
A major drawback of the above method is compiler has no idea about what you are passing. What I mean here is for compiler we are just passing an int* and we know that this is pointing to the array but the compiler doesn’t know this.
To verify my statement you can call for-each loop on your array. You will surely get an error saying no callable begin, end function found.This is because the passing array is like actually passing an integer pointer and it itself has no information about the underlying array hence no iterator is provided.
This method retains all information about the underlying array. This method is majorly based on reference to an array but using this with templates optimizes our method. Template dependency actually calculates the length of the array automatically at the time of function call so that it can be used to create a reference because a reference to an array must know the size of the array.
Here Template is used for template argument deduction.
C++
// CPP Program to demonstrate template approach#include <iostream>using namespace std; template <size_t N> void print(int (&a)[N]){ for (int e : a) { cout << e << endl; }} // Driver Codeint main(){ int a[]{ 1, 2, 3, 4, 5 }; print(a);}
1
2
3
4
5
Here you can see why we need template argument deduction. For a base to create a reference to an array so that we can take an array as a parameter.
Related Articles:
Do not use sizeof for array parameters.
Difference between pointer and array in C?
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed here.
RishabhPrabhu
prasadguru15698
mohdatishanx
uppala0863
shivanisinghss2110
anshikajain26
CBSE - Class 11
cpp-array
CPP-Functions
cpp-pointer
school-programming
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 24234,
"s": 24206,
"text": "\n09 Jan, 2022"
},
{
"code": null,
"e": 24396,
"s": 24234,
"text": "A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array’s name."
},
{
"code": null,
"e": 24535,
"s": 24396,
"text": "In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). The below example demonstrates the same. "
},
{
"code": null,
"e": 24539,
"s": 24535,
"text": "C++"
},
{
"code": null,
"e": 24541,
"s": 24539,
"text": "C"
},
{
"code": "// CPP Program to demonstrate passing// an array to a function is always treated// as a pointer#include <iostream>using namespace std; // Note that arr[] for fun is// just a pointer even if square// brackets are usedvoid fun(int arr[]) // SAME AS void fun(int *arr){ unsigned int n = sizeof(arr) / sizeof(arr[0]); cout << \"\\nArray size inside fun() is \" << n;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; unsigned int n = sizeof(arr) / sizeof(arr[0]); cout << \"Array size inside main() is \" << n; fun(arr); return 0;}",
"e": 25102,
"s": 24541,
"text": null
},
{
"code": "#include <stdio.h>#include <stdlib.h>// Note that arr[] for fun is just a pointer even if square// brackets are usedvoid fun(int arr[]) // SAME AS void fun(int *arr){ unsigned int n = sizeof(arr)/sizeof(arr[0]); printf(\"\\nArray size inside fun() is %d\", n);} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; unsigned int n = sizeof(arr)/sizeof(arr[0]); printf(\"Array size inside main() is %d\", n); fun(arr); return 0;}",
"e": 25554,
"s": 25102,
"text": null
},
{
"code": null,
"e": 25561,
"s": 25554,
"text": "Output"
},
{
"code": null,
"e": 25620,
"s": 25561,
"text": "Array size inside main() is 8\nArray size inside fun() is 1"
},
{
"code": null,
"e": 25828,
"s": 25620,
"text": "Therefore in C, we must pass the size of the array as a parameter. Size may not be needed only in the case of ‘\\0’ terminated character arrays, size can be determined by checking the end of string character."
},
{
"code": null,
"e": 25905,
"s": 25828,
"text": "Following is a simple example to show how arrays are typically passed in C: "
},
{
"code": null,
"e": 25909,
"s": 25905,
"text": "C++"
},
{
"code": null,
"e": 25911,
"s": 25909,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; void fun(int *arr, unsigned int n){ int i; for (i = 0; i < n; i++) cout <<\" \"<< arr[i];} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; unsigned int n = sizeof(arr)/sizeof(arr[0]); fun(arr, n); return 0;}",
"e": 26192,
"s": 25911,
"text": null
},
{
"code": "#include <stdio.h> void fun(int *arr, unsigned int n){ int i; for (i=0; i<n; i++) printf(\"%d \", arr[i]);} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; unsigned int n = sizeof(arr)/sizeof(arr[0]); fun(arr, n); return 0;}",
"e": 26451,
"s": 26192,
"text": null
},
{
"code": null,
"e": 26458,
"s": 26451,
"text": "Output"
},
{
"code": null,
"e": 26481,
"s": 26458,
"text": "1 2 3 4 5 6 7 8"
},
{
"code": null,
"e": 26535,
"s": 26481,
"text": "Exercise: Predict the output of the below C programs:"
},
{
"code": null,
"e": 26546,
"s": 26535,
"text": "Program 1:"
},
{
"code": null,
"e": 26550,
"s": 26546,
"text": "C++"
},
{
"code": null,
"e": 26552,
"s": 26550,
"text": "C"
},
{
"code": "// Program 1#include <iostream>using namespace std;void fun(int arr[], unsigned int n){ int i; for (i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver programint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; unsigned int n = sizeof(arr) / sizeof(arr[0]); fun(arr, n); return 0;}",
"e": 26860,
"s": 26552,
"text": null
},
{
"code": "#include <stdio.h>void fun(int arr[], unsigned int n){int i;for (i=0; i<n; i++) printf(\"%d \", arr[i]);} // Driver programint main(){int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};unsigned int n = sizeof(arr)/sizeof(arr[0]);fun(arr, n);return 0;}",
"e": 27099,
"s": 26860,
"text": null
},
{
"code": null,
"e": 27106,
"s": 27099,
"text": "Output"
},
{
"code": null,
"e": 27122,
"s": 27106,
"text": "1 2 3 4 5 6 7 8"
},
{
"code": null,
"e": 27134,
"s": 27122,
"text": " Program 2:"
},
{
"code": null,
"e": 27138,
"s": 27134,
"text": "C++"
},
{
"code": null,
"e": 27140,
"s": 27138,
"text": "C"
},
{
"code": "// Program 2#include <iostream>using namespace std;void fun(int* arr){ int i; unsigned int n = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < n; i++) cout << \" \" << arr[i];} // Driver programint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; fun(arr); return 0;}",
"e": 27428,
"s": 27140,
"text": null
},
{
"code": "#include <stdio.h>void fun(int *arr){ int i; unsigned int n = sizeof(arr)/sizeof(arr[0]); for (i=0; i<n; i++) printf(\"%d \", arr[i]);} // Driver programint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; fun(arr); return 0;}",
"e": 27667,
"s": 27428,
"text": null
},
{
"code": null,
"e": 27674,
"s": 27667,
"text": "Output"
},
{
"code": null,
"e": 27679,
"s": 27674,
"text": " 1 2"
},
{
"code": null,
"e": 27690,
"s": 27679,
"text": "Program 3:"
},
{
"code": null,
"e": 27694,
"s": 27690,
"text": "C++"
},
{
"code": null,
"e": 27696,
"s": 27694,
"text": "C"
},
{
"code": "// Program 3#include <iostream>#include <string.h>using namespace std;void fun(char* arr){ int i; unsigned int n = strlen(arr); cout << \"n = \" << n << endl; for (i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver programint main(){ char arr[] = \"geeksquiz\"; fun(arr); return 0;}",
"e": 28005,
"s": 27696,
"text": null
},
{
"code": "#include <stdio.h>#include <string.h> void fun(char *arr){ int i; unsigned int n = strlen(arr); printf(\"n = %d\\n\", n); for (i=0; i<n; i++) printf(\"%c \", arr[i]);} // Driver programint main(){ char arr[] = \"geeksquiz\"; fun(arr); return 0;}",
"e": 28263,
"s": 28005,
"text": null
},
{
"code": null,
"e": 28270,
"s": 28263,
"text": "Output"
},
{
"code": null,
"e": 28295,
"s": 28270,
"text": "n = 9\ng e e k s q u i z "
},
{
"code": null,
"e": 28307,
"s": 28295,
"text": "Program 4: "
},
{
"code": null,
"e": 28311,
"s": 28307,
"text": "C++"
},
{
"code": null,
"e": 28313,
"s": 28311,
"text": "C"
},
{
"code": "// Program 4#include <bits/stdc++.h>#include <iostream>using namespace std; void fun(char* arr){ int i; unsigned int n = strlen(arr); cout << \"n = \" << n << \"\\n\"; for (i = 0; i < n; i++) cout << \" \" << arr[i];} // Driver programint main(){ char arr[] = { 'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z' }; fun(arr); return 0;}",
"e": 28671,
"s": 28313,
"text": null
},
{
"code": "#include <stdio.h>#include <string.h> void fun(char *arr){ int i; unsigned int n = strlen(arr); printf(\"n = %d\\n\", n); for (i=0; i<n; i++) printf(\"%c \", arr[i]);} // Driver programint main(){ char arr[] = {'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z'}; fun(arr); return 0;}",
"e": 28963,
"s": 28671,
"text": null
},
{
"code": null,
"e": 28970,
"s": 28963,
"text": "Output"
},
{
"code": null,
"e": 28995,
"s": 28970,
"text": "n = 11\ng e e k s q u i z"
},
{
"code": null,
"e": 29089,
"s": 28995,
"text": "NOTE: The character array in the above program is not ‘\\0’ terminated. (See this for details)"
},
{
"code": null,
"e": 29290,
"s": 29089,
"text": "Now These were some of the common approaches that we use but do you know that there is a better way to do the same. For this, we first need to look at the drawbacks of all the above-suggested methods:"
},
{
"code": null,
"e": 29301,
"s": 29290,
"text": "Drawbacks:"
},
{
"code": null,
"e": 29535,
"s": 29301,
"text": "A major drawback of the above method is compiler has no idea about what you are passing. What I mean here is for compiler we are just passing an int* and we know that this is pointing to the array but the compiler doesn’t know this. "
},
{
"code": null,
"e": 29843,
"s": 29535,
"text": "To verify my statement you can call for-each loop on your array. You will surely get an error saying no callable begin, end function found.This is because the passing array is like actually passing an integer pointer and it itself has no information about the underlying array hence no iterator is provided."
},
{
"code": null,
"e": 30230,
"s": 29843,
"text": "This method retains all information about the underlying array. This method is majorly based on reference to an array but using this with templates optimizes our method. Template dependency actually calculates the length of the array automatically at the time of function call so that it can be used to create a reference because a reference to an array must know the size of the array."
},
{
"code": null,
"e": 30285,
"s": 30230,
"text": "Here Template is used for template argument deduction."
},
{
"code": null,
"e": 30289,
"s": 30285,
"text": "C++"
},
{
"code": "// CPP Program to demonstrate template approach#include <iostream>using namespace std; template <size_t N> void print(int (&a)[N]){ for (int e : a) { cout << e << endl; }} // Driver Codeint main(){ int a[]{ 1, 2, 3, 4, 5 }; print(a);}",
"e": 30543,
"s": 30289,
"text": null
},
{
"code": null,
"e": 30553,
"s": 30543,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 30702,
"s": 30553,
"text": "Here you can see why we need template argument deduction. For a base to create a reference to an array so that we can take an array as a parameter. "
},
{
"code": null,
"e": 30720,
"s": 30702,
"text": "Related Articles:"
},
{
"code": null,
"e": 30760,
"s": 30720,
"text": "Do not use sizeof for array parameters."
},
{
"code": null,
"e": 30803,
"s": 30760,
"text": "Difference between pointer and array in C?"
},
{
"code": null,
"e": 30927,
"s": 30803,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed here."
},
{
"code": null,
"e": 30941,
"s": 30927,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 30957,
"s": 30941,
"text": "prasadguru15698"
},
{
"code": null,
"e": 30970,
"s": 30957,
"text": "mohdatishanx"
},
{
"code": null,
"e": 30981,
"s": 30970,
"text": "uppala0863"
},
{
"code": null,
"e": 31000,
"s": 30981,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 31014,
"s": 31000,
"text": "anshikajain26"
},
{
"code": null,
"e": 31030,
"s": 31014,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 31040,
"s": 31030,
"text": "cpp-array"
},
{
"code": null,
"e": 31054,
"s": 31040,
"text": "CPP-Functions"
},
{
"code": null,
"e": 31066,
"s": 31054,
"text": "cpp-pointer"
},
{
"code": null,
"e": 31085,
"s": 31066,
"text": "school-programming"
},
{
"code": null,
"e": 31096,
"s": 31085,
"text": "C Language"
},
{
"code": null,
"e": 31100,
"s": 31096,
"text": "C++"
},
{
"code": null,
"e": 31104,
"s": 31100,
"text": "CPP"
},
{
"code": null,
"e": 31202,
"s": 31104,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31211,
"s": 31202,
"text": "Comments"
},
{
"code": null,
"e": 31224,
"s": 31211,
"text": "Old Comments"
},
{
"code": null,
"e": 31262,
"s": 31224,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 31288,
"s": 31262,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 31308,
"s": 31288,
"text": "Multithreading in C"
},
{
"code": null,
"e": 31330,
"s": 31308,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 31368,
"s": 31330,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 31386,
"s": 31368,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 31405,
"s": 31386,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31451,
"s": 31405,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 31494,
"s": 31451,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to Load External JS Scripts Dynamically in AngularJS ? - GeeksforGeeks
|
27 Feb, 2020
The task is to load a JS code either from a CDN or JS file stored in the system dynamically at runtime in AngularJS i.e. JavaScript code should be loaded dynamically. For example, on a button press or on some event.
Whenever we want to load the script file we would have to create an element of type “script” using document.createElement. We would then specify its src attribute to be the location of the script either CDN or a local js file. Once that’s done, we will have to append the tag to an HTML element that’s already existing in the DOM. For example, the head element.
Syntax:
const node = document.createElement('script');
node.src = 'SCRIPT_FILE_OR_URL_HERE'
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
Example 1: In this example, we are loading a load.js file from file system dynamically on component load.
app.component.html
app.component.ts
load.js
<div style="text-align:center;"> <h1 style="color: green;"> GeeksForGeeks </h1></div>
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Load script GFG'; constructor() { this.loadScripts(); } // Method to dynamically load JavaScript loadScripts() { // This array contains all the files/CDNs const dynamicScripts = [ 'assets/load.js' ]; for (let i = 0; i < dynamicScripts.length; i++) { const node = document.createElement('script'); node.src = dynamicScripts[i]; node.type = 'text/javascript'; node.async = false; document.getElementsByTagName('head')[0].appendChild(node); } }}
alert('load js has been loaded');
Output: As soon as the app.component loads, the script loads as well and displays the alert window.
Example 2: In this example, we will load the load.js script on button click.
app.component.html
app.component.ts
load.js
<div style="text-align:center;"> <h1 style="color: green;"> GeeksForGeeks </h1> <button (click)="loadScripts($event)"> Click me to load JS </button></div>
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Load script GFG'; constructor() { } loadScripts($event) { const dynamicScripts = [ 'assets/load.js' ]; for (let i = 0; i < dynamicScripts.length; i++) { const node = document.createElement('script'); node.src = dynamicScripts[i]; node.type = 'text/javascript'; node.async = false; document.getElementsByTagName('head')[0].appendChild(node); } }}
alert('load js has been loaded');
Output: As the button is pressed, the JS file loads.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
AngularJS-Misc
HTML-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 24656,
"s": 24628,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 24872,
"s": 24656,
"text": "The task is to load a JS code either from a CDN or JS file stored in the system dynamically at runtime in AngularJS i.e. JavaScript code should be loaded dynamically. For example, on a button press or on some event."
},
{
"code": null,
"e": 25234,
"s": 24872,
"text": "Whenever we want to load the script file we would have to create an element of type “script” using document.createElement. We would then specify its src attribute to be the location of the script either CDN or a local js file. Once that’s done, we will have to append the tag to an HTML element that’s already existing in the DOM. For example, the head element."
},
{
"code": null,
"e": 25242,
"s": 25234,
"text": "Syntax:"
},
{
"code": null,
"e": 25418,
"s": 25242,
"text": "const node = document.createElement('script');\nnode.src = 'SCRIPT_FILE_OR_URL_HERE'\nnode.type = 'text/javascript';\ndocument.getElementsByTagName('head')[0].appendChild(node);\n"
},
{
"code": null,
"e": 25524,
"s": 25418,
"text": "Example 1: In this example, we are loading a load.js file from file system dynamically on component load."
},
{
"code": null,
"e": 25543,
"s": 25524,
"text": "app.component.html"
},
{
"code": null,
"e": 25560,
"s": 25543,
"text": "app.component.ts"
},
{
"code": null,
"e": 25568,
"s": 25560,
"text": "load.js"
},
{
"code": "<div style=\"text-align:center;\"> <h1 style=\"color: green;\"> GeeksForGeeks </h1></div>",
"e": 25667,
"s": 25568,
"text": null
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Load script GFG'; constructor() { this.loadScripts(); } // Method to dynamically load JavaScript loadScripts() { // This array contains all the files/CDNs const dynamicScripts = [ 'assets/load.js' ]; for (let i = 0; i < dynamicScripts.length; i++) { const node = document.createElement('script'); node.src = dynamicScripts[i]; node.type = 'text/javascript'; node.async = false; document.getElementsByTagName('head')[0].appendChild(node); } }}",
"e": 26381,
"s": 25667,
"text": null
},
{
"code": "alert('load js has been loaded'); ",
"e": 26416,
"s": 26381,
"text": null
},
{
"code": null,
"e": 26516,
"s": 26416,
"text": "Output: As soon as the app.component loads, the script loads as well and displays the alert window."
},
{
"code": null,
"e": 26593,
"s": 26516,
"text": "Example 2: In this example, we will load the load.js script on button click."
},
{
"code": null,
"e": 26612,
"s": 26593,
"text": "app.component.html"
},
{
"code": null,
"e": 26629,
"s": 26612,
"text": "app.component.ts"
},
{
"code": null,
"e": 26637,
"s": 26629,
"text": "load.js"
},
{
"code": "<div style=\"text-align:center;\"> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <button (click)=\"loadScripts($event)\"> Click me to load JS </button></div>",
"e": 26818,
"s": 26637,
"text": null
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Load script GFG'; constructor() { } loadScripts($event) { const dynamicScripts = [ 'assets/load.js' ]; for (let i = 0; i < dynamicScripts.length; i++) { const node = document.createElement('script'); node.src = dynamicScripts[i]; node.type = 'text/javascript'; node.async = false; document.getElementsByTagName('head')[0].appendChild(node); } }}",
"e": 27403,
"s": 26818,
"text": null
},
{
"code": "alert('load js has been loaded'); ",
"e": 27438,
"s": 27403,
"text": null
},
{
"code": null,
"e": 27491,
"s": 27438,
"text": "Output: As the button is pressed, the JS file loads."
},
{
"code": null,
"e": 27628,
"s": 27491,
"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": 27643,
"s": 27628,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 27653,
"s": 27643,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27660,
"s": 27653,
"text": "Picked"
},
{
"code": null,
"e": 27665,
"s": 27660,
"text": "HTML"
},
{
"code": null,
"e": 27682,
"s": 27665,
"text": "Web Technologies"
},
{
"code": null,
"e": 27709,
"s": 27682,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27714,
"s": 27709,
"text": "HTML"
},
{
"code": null,
"e": 27812,
"s": 27714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27821,
"s": 27812,
"text": "Comments"
},
{
"code": null,
"e": 27834,
"s": 27821,
"text": "Old Comments"
},
{
"code": null,
"e": 27882,
"s": 27834,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27932,
"s": 27882,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27956,
"s": 27932,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28006,
"s": 27956,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 28048,
"s": 28006,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 28090,
"s": 28048,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28123,
"s": 28090,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28166,
"s": 28123,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28211,
"s": 28166,
"text": "Convert a string to an integer in JavaScript"
}
] |
tee() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#define _GNU_SOURCE
#include <fcntl.h>
long tee(int fd_in, int fd_out, size_t len
", unsigned int " flags );
long tee(int fd_in, int fd_out, size_t len
", unsigned int " flags );
flags is a series of modifier flags, which share the name space with
splice(2)
and
vmsplice(2):
On error,
tee() returns -1 and
errno is set to indicate the error.
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
int
main(int argc, char *argv[])
{
int fd;
int len, slen;
assert(argc == 2);
fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
do {
/*
* tee stdin to stdout.
*/
len = tee(STDIN_FILENO, STDOUT_FILENO,
INT_MAX, SPLICE_F_NONBLOCK);
if (len < 0) {
if (errno == EAGAIN)
continue;
perror("tee");
exit(EXIT_FAILURE);
} else
if (len == 0)
break;
/*
* Consume stdin by splicing it to a file.
*/
while (len > 0) {
slen = splice(STDIN_FILENO, NULL, fd, NULL,
len, SPLICE_F_MOVE);
if (slen < 0) {
perror("splice");
break;
}
len -= slen;
}
} while (1);
close(fd);
exit(EXIT_SUCCESS);
}
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
int
main(int argc, char *argv[])
{
int fd;
int len, slen;
assert(argc == 2);
fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
do {
/*
* tee stdin to stdout.
*/
len = tee(STDIN_FILENO, STDOUT_FILENO,
INT_MAX, SPLICE_F_NONBLOCK);
if (len < 0) {
if (errno == EAGAIN)
continue;
perror("tee");
exit(EXIT_FAILURE);
} else
if (len == 0)
break;
/*
* Consume stdin by splicing it to a file.
*/
while (len > 0) {
slen = splice(STDIN_FILENO, NULL, fd, NULL,
len, SPLICE_F_MOVE);
if (slen < 0) {
perror("splice");
break;
}
len -= slen;
}
} while (1);
close(fd);
exit(EXIT_SUCCESS);
}
splice (2)
splice (2)
vmsplice (2)
vmsplice (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2433,
"s": 2319,
"text": "#define _GNU_SOURCE \n#include <fcntl.h> \n\nlong tee(int fd_in, int fd_out, size_t len \n\", unsigned int \" flags );\n"
},
{
"code": null,
"e": 2506,
"s": 2433,
"text": "\nlong tee(int fd_in, int fd_out, size_t len \n\", unsigned int \" flags );\n"
},
{
"code": null,
"e": 2604,
"s": 2506,
"text": "\nflags is a series of modifier flags, which share the name space with\nsplice(2)\nand\nvmsplice(2):\n"
},
{
"code": null,
"e": 2673,
"s": 2604,
"text": "\nOn error,\ntee() returns -1 and\nerrno is set to indicate the error.\n"
},
{
"code": null,
"e": 3824,
"s": 2673,
"text": "\n#define _GNU_SOURCE\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <assert.h>\n#include <errno.h>\n#include <limits.h>\n\nint\nmain(int argc, char *argv[])\n{\n int fd;\n int len, slen;\n\n assert(argc == 2);\n\n fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);\n if (fd == -1) {\n perror(\"open\");\n exit(EXIT_FAILURE);\n }\n\n do {\n /*\n * tee stdin to stdout.\n */\n len = tee(STDIN_FILENO, STDOUT_FILENO,\n INT_MAX, SPLICE_F_NONBLOCK);\n\n if (len < 0) {\n if (errno == EAGAIN)\n continue;\n perror(\"tee\");\n exit(EXIT_FAILURE);\n } else\n if (len == 0)\n break;\n\n /*\n * Consume stdin by splicing it to a file.\n */\n while (len > 0) {\n slen = splice(STDIN_FILENO, NULL, fd, NULL,\n len, SPLICE_F_MOVE);\n if (slen < 0) {\n perror(\"splice\");\n break;\n }\n len -= slen;\n }\n } while (1);\n\n close(fd);\n exit(EXIT_SUCCESS);\n}\n"
},
{
"code": null,
"e": 3983,
"s": 3824,
"text": "\n#define _GNU_SOURCE\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <assert.h>\n#include <errno.h>\n#include <limits.h>\n"
},
{
"code": null,
"e": 4051,
"s": 3983,
"text": "\nint\nmain(int argc, char *argv[])\n{\n int fd;\n int len, slen;\n"
},
{
"code": null,
"e": 4076,
"s": 4051,
"text": "\n assert(argc == 2);\n"
},
{
"code": null,
"e": 4216,
"s": 4076,
"text": "\n fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);\n if (fd == -1) {\n perror(\"open\");\n exit(EXIT_FAILURE);\n }\n"
},
{
"code": null,
"e": 4376,
"s": 4216,
"text": "\n do {\n /*\n * tee stdin to stdout.\n */\n len = tee(STDIN_FILENO, STDOUT_FILENO,\n INT_MAX, SPLICE_F_NONBLOCK);\n"
},
{
"code": null,
"e": 4583,
"s": 4376,
"text": "\n if (len < 0) {\n if (errno == EAGAIN)\n continue;\n perror(\"tee\");\n exit(EXIT_FAILURE);\n } else\n if (len == 0)\n break;\n"
},
{
"code": null,
"e": 4939,
"s": 4583,
"text": "\n /*\n * Consume stdin by splicing it to a file.\n */\n while (len > 0) {\n slen = splice(STDIN_FILENO, NULL, fd, NULL,\n len, SPLICE_F_MOVE);\n if (slen < 0) {\n perror(\"splice\");\n break;\n }\n len -= slen;\n }\n } while (1);\n"
},
{
"code": null,
"e": 4982,
"s": 4939,
"text": "\n close(fd);\n exit(EXIT_SUCCESS);\n}\n"
},
{
"code": null,
"e": 4993,
"s": 4982,
"text": "splice (2)"
},
{
"code": null,
"e": 5004,
"s": 4993,
"text": "splice (2)"
},
{
"code": null,
"e": 5017,
"s": 5004,
"text": "vmsplice (2)"
},
{
"code": null,
"e": 5030,
"s": 5017,
"text": "vmsplice (2)"
},
{
"code": null,
"e": 5047,
"s": 5030,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 5082,
"s": 5047,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 5110,
"s": 5082,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5144,
"s": 5110,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5161,
"s": 5144,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5194,
"s": 5161,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5205,
"s": 5194,
"text": " Pradeep D"
},
{
"code": null,
"e": 5240,
"s": 5205,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5256,
"s": 5240,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5289,
"s": 5256,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5301,
"s": 5289,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 5333,
"s": 5301,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5341,
"s": 5333,
"text": " Uplatz"
},
{
"code": null,
"e": 5348,
"s": 5341,
"text": " Print"
},
{
"code": null,
"e": 5359,
"s": 5348,
"text": " Add Notes"
}
] |
Check if a number is Prime, Semi-Prime or Composite for very large numbers - GeeksforGeeks
|
21 Dec, 2021
Given a very large number N (> 150), the task is to check whether this number is Prime, Semi-Prime or Composite.Example:
Input: N = 90000000 Output: Not Prime Explanation: we have (N-1)%6 = 89999999%6 = 1 and (N+1)%6 = 90000001%6 = 5 Since n-1 and n+1 is not divisible by 6 Therefore N = 90000000 is Not PrimeInput: N = 7894561 Output: Semi-Prime Explanation: Here N = 7894561 = 71*111191 Since 71 & 111191 are prime, therefore 7894561 is Semi Prime
Approach:
It can be observed that if n is a Prime Number then n+1 or n-1 will be divisible by 6
If a number n exists such that neither n+1 nor n-1 is divisible by 6 then n is not a prime number
If a number n exists such that either n+1 or n-1 is divisible by 6 then n is either a prime or a semiprime number
To differentiate between prime and semi-prime, the following method is used: If N is semi prime then,
If N is semi prime then,
N = p*q ....................(1)
where p & q are primes.
Then from Goldbach Conjecture:
p + q must be even
i.e, p + q = 2*n for any positive integer n
Therefore solving for p & q will give
p = n - sqrt(n2 - N)
q = n + sqrt(n2 - N)
Let n2 – N be perfect square, Then
n2 - N = m2, .................(2)
for any positive integer m
Solving Equations (1) & (2) we get
m = (q-p)/2
n = (p+q)/2
Now if equation (1) & (2) meets at some point, then there exists a pair (p, q) such that the number N is semiprime otherwise N is prime.
Equation(2) forms Pythagorean Triplet
The solution expected varies on the graph
Pseudo code:
Input a number N and if N – 1 and N + 1 is not divisible by 6 then the number N is Not Prime. else it is prime or semi-prime
If n-1 or n+1 is divisible by 6 then iterate in the range(sqrt(N) + 1, N) and find a pair (p, q) such that p*q = N by below formula:
p = i - sqrt(i*i - N)
q = n/p
where i = index in range(sqrt(N) + 1, N)
If p*q = N then the number N is semi prime, else it is prime
Below is the implementation of the above approach:
Java
CPP
Python3
C#
Javascript
import static java.lang.Math.sqrt; public class Primmefunc { public static void prime(long n) { int flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { System.out.println("Not Prime"); } else { // breakout if number is perfect square double s = sqrt(n); if ((s * s) == n) { System.out.println("Semi-Prime"); } else { long f = (long)s; long l = (long)((f * f)); // Iterating over to get the // closest average value for (long i = f + 1; i < l; i++) { // 1st Factor long p = i - (long)(sqrt((i * i) - (n))); // 2nd Factor long q = n / p; // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { System.out.println("Semi-Prime"); } else if (flag == 2) { System.out.println("Prime"); } } } } public static void main(String[] args) { // Driver code // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); }//written by Rushil Jhaveri}
#include<bits/stdc++.h>using namespace std ; void prime(long n){ int flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { cout << ("Not Prime") << endl; } else { // breakout if number is perfect square double s = sqrt(n); if ((s * s) == n) { cout<<("Semi-Prime")<<endl; } else { long f = (long)s; long l = (long)((f * f)); // Iterating over to get the // closest average value for (long i = f + 1; i < l; i++) { // 1st Factor long p = i - (long)(sqrt((i * i) - (n))); // 2nd Factor long q = n / p; // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { cout<<("Semi-Prime")<<endl; } else if (flag == 2) { cout<<("Prime")<<endl; } } }} // Driver codeint main(){ // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187);} // This code is contributed by Rajput-Ji
def prime(n): flag = 0; # checking divisibility by 6 if ((n + 1) % 6 != 0 and (n - 1) % 6 != 0): print("Not Prime"); else: # breakout if number is perfect square s = pow(n, 1/2); if ((s * s) == n): print("Semi-Prime"); else: f = int(s); l = int(f * f); # Iterating over to get the # closest average value for i in range(f + 1, l): # 1st Factor p = i - (pow(((i * i) - (n)), 1/2)); # 2nd Factor q = n // p; # To avoid Convergence if (p < 2 or q < 2): break; # checking semi-prime condition if ((p * q) == n): flag = 1; break; # If convergence found # then number is semi-prime else: # convergence not found # then number is prime flag = 2; if (flag == 1): print("Semi-Prime"); elif(flag == 2): print("Prime"); # Driver codeif __name__ == '__main__': # Entered number should be greater # than 300 to avoid Convergence of # second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); # This code is contributed by 29AjayKumar
using System;public class Primmefunc{ public static void prime(long n) { int flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { Console.WriteLine("Not Prime"); } else { // breakout if number is perfect square double s = Math.Sqrt(n); if ((s * s) == n) { Console.WriteLine("Semi-Prime"); } else { long f = (long)s; long l = (long)((f * f)); // Iterating over to get the // closest average value for (long i = f + 1; i < l; i++) { // 1st Factor long p = i - (long)(Math.Sqrt((i * i) - (n))); // 2nd Factor long q = n / p; // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { Console.WriteLine("Semi-Prime"); } else if (flag == 2) { Console.WriteLine("Prime"); } } } } // Driver code public static void Main(String[] args) { // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); }} // This code is contributed by 29AjayKumar
<script> function prime(n) { var flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { document.write("Not Prime<br>"); } else { // breakout if number is perfect square var s = parseInt(Math.sqrt(n)); if ((s * s) == n) { document.write("Semi-Prime<br>"); } else { var f = s; var l = ((f * f)); // Iterating over to get the // closest average value for (var i = f + 1; i < l; i++) { // 1st Factor var p = i - parseInt(Math.sqrt((i * i) - (n))); // 2nd Factor var q = parseInt(n / p); // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { document.write("Semi-Prime<br>"); } else if (flag == 2) { document.write("Prime<br>"); } } } } // Driver code // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); // This code is contributed by 29AjayKumar</script>
Prime
Semi-Prime
Not Prime
Semi-Prime
Semi-Prime
Prime
Time Complexity: O(N)
29AjayKumar
Rajput-Ji
rushiljhaveri
kapoorsagar226
number-theory
Prime Number
Algorithms
Engineering Mathematics
number-theory
Prime Number
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Rail Fence Cipher - Encryption and Decryption
Quadratic Probing in Hashing
Relationship between number of nodes and height of binary tree
Inequalities in LaTeX
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
|
[
{
"code": null,
"e": 24700,
"s": 24672,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 24822,
"s": 24700,
"text": "Given a very large number N (> 150), the task is to check whether this number is Prime, Semi-Prime or Composite.Example: "
},
{
"code": null,
"e": 25153,
"s": 24822,
"text": "Input: N = 90000000 Output: Not Prime Explanation: we have (N-1)%6 = 89999999%6 = 1 and (N+1)%6 = 90000001%6 = 5 Since n-1 and n+1 is not divisible by 6 Therefore N = 90000000 is Not PrimeInput: N = 7894561 Output: Semi-Prime Explanation: Here N = 7894561 = 71*111191 Since 71 & 111191 are prime, therefore 7894561 is Semi Prime "
},
{
"code": null,
"e": 25164,
"s": 25153,
"text": "Approach: "
},
{
"code": null,
"e": 25250,
"s": 25164,
"text": "It can be observed that if n is a Prime Number then n+1 or n-1 will be divisible by 6"
},
{
"code": null,
"e": 25348,
"s": 25250,
"text": "If a number n exists such that neither n+1 nor n-1 is divisible by 6 then n is not a prime number"
},
{
"code": null,
"e": 25462,
"s": 25348,
"text": "If a number n exists such that either n+1 or n-1 is divisible by 6 then n is either a prime or a semiprime number"
},
{
"code": null,
"e": 25564,
"s": 25462,
"text": "To differentiate between prime and semi-prime, the following method is used: If N is semi prime then,"
},
{
"code": null,
"e": 25589,
"s": 25564,
"text": "If N is semi prime then,"
},
{
"code": null,
"e": 25646,
"s": 25589,
"text": "N = p*q ....................(1)\nwhere p & q are primes."
},
{
"code": null,
"e": 25677,
"s": 25646,
"text": "Then from Goldbach Conjecture:"
},
{
"code": null,
"e": 25740,
"s": 25677,
"text": "p + q must be even\ni.e, p + q = 2*n for any positive integer n"
},
{
"code": null,
"e": 25778,
"s": 25740,
"text": "Therefore solving for p & q will give"
},
{
"code": null,
"e": 25820,
"s": 25778,
"text": "p = n - sqrt(n2 - N)\nq = n + sqrt(n2 - N)"
},
{
"code": null,
"e": 25855,
"s": 25820,
"text": "Let n2 – N be perfect square, Then"
},
{
"code": null,
"e": 25917,
"s": 25855,
"text": "n2 - N = m2, .................(2)\nfor any positive integer m "
},
{
"code": null,
"e": 25952,
"s": 25917,
"text": "Solving Equations (1) & (2) we get"
},
{
"code": null,
"e": 25976,
"s": 25952,
"text": "m = (q-p)/2\nn = (p+q)/2"
},
{
"code": null,
"e": 26113,
"s": 25976,
"text": "Now if equation (1) & (2) meets at some point, then there exists a pair (p, q) such that the number N is semiprime otherwise N is prime."
},
{
"code": null,
"e": 26153,
"s": 26113,
"text": "Equation(2) forms Pythagorean Triplet "
},
{
"code": null,
"e": 26197,
"s": 26153,
"text": "The solution expected varies on the graph "
},
{
"code": null,
"e": 26211,
"s": 26197,
"text": "Pseudo code: "
},
{
"code": null,
"e": 26336,
"s": 26211,
"text": "Input a number N and if N – 1 and N + 1 is not divisible by 6 then the number N is Not Prime. else it is prime or semi-prime"
},
{
"code": null,
"e": 26469,
"s": 26336,
"text": "If n-1 or n+1 is divisible by 6 then iterate in the range(sqrt(N) + 1, N) and find a pair (p, q) such that p*q = N by below formula:"
},
{
"code": null,
"e": 26540,
"s": 26469,
"text": "p = i - sqrt(i*i - N)\nq = n/p\nwhere i = index in range(sqrt(N) + 1, N)"
},
{
"code": null,
"e": 26601,
"s": 26540,
"text": "If p*q = N then the number N is semi prime, else it is prime"
},
{
"code": null,
"e": 26654,
"s": 26601,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26659,
"s": 26654,
"text": "Java"
},
{
"code": null,
"e": 26663,
"s": 26659,
"text": "CPP"
},
{
"code": null,
"e": 26671,
"s": 26663,
"text": "Python3"
},
{
"code": null,
"e": 26674,
"s": 26671,
"text": "C#"
},
{
"code": null,
"e": 26685,
"s": 26674,
"text": "Javascript"
},
{
"code": "import static java.lang.Math.sqrt; public class Primmefunc { public static void prime(long n) { int flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { System.out.println(\"Not Prime\"); } else { // breakout if number is perfect square double s = sqrt(n); if ((s * s) == n) { System.out.println(\"Semi-Prime\"); } else { long f = (long)s; long l = (long)((f * f)); // Iterating over to get the // closest average value for (long i = f + 1; i < l; i++) { // 1st Factor long p = i - (long)(sqrt((i * i) - (n))); // 2nd Factor long q = n / p; // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { System.out.println(\"Semi-Prime\"); } else if (flag == 2) { System.out.println(\"Prime\"); } } } } public static void main(String[] args) { // Driver code // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); }//written by Rushil Jhaveri}",
"e": 28707,
"s": 26685,
"text": null
},
{
"code": "#include<bits/stdc++.h>using namespace std ; void prime(long n){ int flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { cout << (\"Not Prime\") << endl; } else { // breakout if number is perfect square double s = sqrt(n); if ((s * s) == n) { cout<<(\"Semi-Prime\")<<endl; } else { long f = (long)s; long l = (long)((f * f)); // Iterating over to get the // closest average value for (long i = f + 1; i < l; i++) { // 1st Factor long p = i - (long)(sqrt((i * i) - (n))); // 2nd Factor long q = n / p; // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { cout<<(\"Semi-Prime\")<<endl; } else if (flag == 2) { cout<<(\"Prime\")<<endl; } } }} // Driver codeint main(){ // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187);} // This code is contributed by Rajput-Ji",
"e": 30515,
"s": 28707,
"text": null
},
{
"code": "def prime(n): flag = 0; # checking divisibility by 6 if ((n + 1) % 6 != 0 and (n - 1) % 6 != 0): print(\"Not Prime\"); else: # breakout if number is perfect square s = pow(n, 1/2); if ((s * s) == n): print(\"Semi-Prime\"); else: f = int(s); l = int(f * f); # Iterating over to get the # closest average value for i in range(f + 1, l): # 1st Factor p = i - (pow(((i * i) - (n)), 1/2)); # 2nd Factor q = n // p; # To avoid Convergence if (p < 2 or q < 2): break; # checking semi-prime condition if ((p * q) == n): flag = 1; break; # If convergence found # then number is semi-prime else: # convergence not found # then number is prime flag = 2; if (flag == 1): print(\"Semi-Prime\"); elif(flag == 2): print(\"Prime\"); # Driver codeif __name__ == '__main__': # Entered number should be greater # than 300 to avoid Convergence of # second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); # This code is contributed by 29AjayKumar",
"e": 32025,
"s": 30515,
"text": null
},
{
"code": "using System;public class Primmefunc{ public static void prime(long n) { int flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { Console.WriteLine(\"Not Prime\"); } else { // breakout if number is perfect square double s = Math.Sqrt(n); if ((s * s) == n) { Console.WriteLine(\"Semi-Prime\"); } else { long f = (long)s; long l = (long)((f * f)); // Iterating over to get the // closest average value for (long i = f + 1; i < l; i++) { // 1st Factor long p = i - (long)(Math.Sqrt((i * i) - (n))); // 2nd Factor long q = n / p; // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { Console.WriteLine(\"Semi-Prime\"); } else if (flag == 2) { Console.WriteLine(\"Prime\"); } } } } // Driver code public static void Main(String[] args) { // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); }} // This code is contributed by 29AjayKumar",
"e": 34179,
"s": 32025,
"text": null
},
{
"code": "<script> function prime(n) { var flag = 0; // checking divisibility by 6 if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0) { document.write(\"Not Prime<br>\"); } else { // breakout if number is perfect square var s = parseInt(Math.sqrt(n)); if ((s * s) == n) { document.write(\"Semi-Prime<br>\"); } else { var f = s; var l = ((f * f)); // Iterating over to get the // closest average value for (var i = f + 1; i < l; i++) { // 1st Factor var p = i - parseInt(Math.sqrt((i * i) - (n))); // 2nd Factor var q = parseInt(n / p); // To avoid Convergence if (p < 2 || q < 2) { break; } // checking semi-prime condition if ((p * q) == n) { flag = 1; break; } // If convergence found // then number is semi-prime else { // convergence not found // then number is prime flag = 2; } } if (flag == 1) { document.write(\"Semi-Prime<br>\"); } else if (flag == 2) { document.write(\"Prime<br>\"); } } } } // Driver code // Entered number should be greater // than 300 to avoid Convergence of // second factor to 1 prime(8179); prime(7894561); prime(90000000); prime(841); prime(22553); prime(1187); // This code is contributed by 29AjayKumar</script>",
"e": 36110,
"s": 34179,
"text": null
},
{
"code": null,
"e": 36165,
"s": 36110,
"text": "Prime\nSemi-Prime\nNot Prime\nSemi-Prime\nSemi-Prime\nPrime"
},
{
"code": null,
"e": 36191,
"s": 36167,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 36203,
"s": 36191,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36213,
"s": 36203,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36227,
"s": 36213,
"text": "rushiljhaveri"
},
{
"code": null,
"e": 36242,
"s": 36227,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 36256,
"s": 36242,
"text": "number-theory"
},
{
"code": null,
"e": 36269,
"s": 36256,
"text": "Prime Number"
},
{
"code": null,
"e": 36280,
"s": 36269,
"text": "Algorithms"
},
{
"code": null,
"e": 36304,
"s": 36280,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 36318,
"s": 36304,
"text": "number-theory"
},
{
"code": null,
"e": 36331,
"s": 36318,
"text": "Prime Number"
},
{
"code": null,
"e": 36342,
"s": 36331,
"text": "Algorithms"
},
{
"code": null,
"e": 36440,
"s": 36342,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36465,
"s": 36440,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36508,
"s": 36465,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 36551,
"s": 36508,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 36597,
"s": 36551,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 36626,
"s": 36597,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 36689,
"s": 36626,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 36711,
"s": 36689,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 36776,
"s": 36711,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 36799,
"s": 36776,
"text": "Arrow Symbols in LaTeX"
}
] |
Write a C program to perform 3X3 matrix operations
|
Enter any 9 numbers at runtime and add the numbers in a row, column, and diagonal wise by using C Programming language
Step 1: Declare 9 variables
Step 2: enter 9 numbers at runtime
Step 3: store the numbers in 3 X 3 matrix form
//x y z
p q r
a b c
Step 4: Do row calculation: add all the numbers in a row and print
// (x+y+z),(p+q+r),(a+b+c)
Step 5: Do column calculation: add all the numbers in a Column and print
//(x+p+a)(y+q+b)(z+r+c)
Step 6: Do Diagonal Calculation: add the numbers in diagonal and print
//(x+q+c),(a+q+z)
Live Demo
#include<stdio.h>
int main(){
int x,y,z,p,q,r,a,b,c;
printf(“enter any 9 numbers :\n");
scanf(“%d%d%d%d%d%d%d%d%d",&x,&y,&z,&p,&q,&r,&a,&b,&c);//reading all 9 integers
printf(“%d %d %d\n",x,y,z);
printf(“%d %d %d\n",p,q,r);
printf(“%d %d %d\n",a,b,c);
printf(“Row total:%d %d %d\n",(x+y+z),(p+q+r),(a+b+c));//row calculation
printf(“column total: %d %d %d\n",(x+p+a),(y+q+b),(z+r+c));//column calculation
printf(“diagonal total :%d %d\n",(x+q+c),(a+q+z));//Diagonal calculation
return 0;
}
enter any 9 numbers :
2 4 6 3 5 7 8 9 2
2 4 6
3 5 7
8 9 2
Row total:12 15 19
column total: 13 18 15
diagonal total :9 19
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Enter any 9 numbers at runtime and add the numbers in a row, column, and diagonal wise by using C Programming language"
},
{
"code": null,
"e": 1639,
"s": 1181,
"text": "Step 1: Declare 9 variables\nStep 2: enter 9 numbers at runtime\nStep 3: store the numbers in 3 X 3 matrix form\n //x y z\n p q r\n a b c\nStep 4: Do row calculation: add all the numbers in a row and print\n // (x+y+z),(p+q+r),(a+b+c)\nStep 5: Do column calculation: add all the numbers in a Column and print\n //(x+p+a)(y+q+b)(z+r+c)\nStep 6: Do Diagonal Calculation: add the numbers in diagonal and print\n //(x+q+c),(a+q+z)"
},
{
"code": null,
"e": 1650,
"s": 1639,
"text": " Live Demo"
},
{
"code": null,
"e": 2170,
"s": 1650,
"text": "#include<stdio.h>\nint main(){\n int x,y,z,p,q,r,a,b,c;\n printf(“enter any 9 numbers :\\n\");\n scanf(“%d%d%d%d%d%d%d%d%d\",&x,&y,&z,&p,&q,&r,&a,&b,&c);//reading all 9 integers\n printf(“%d %d %d\\n\",x,y,z);\n printf(“%d %d %d\\n\",p,q,r);\n printf(“%d %d %d\\n\",a,b,c);\n printf(“Row total:%d %d %d\\n\",(x+y+z),(p+q+r),(a+b+c));//row calculation\n printf(“column total: %d %d %d\\n\",(x+p+a),(y+q+b),(z+r+c));//column calculation\n printf(“diagonal total :%d %d\\n\",(x+q+c),(a+q+z));//Diagonal calculation\n return 0;\n}"
},
{
"code": null,
"e": 2291,
"s": 2170,
"text": "enter any 9 numbers :\n2 4 6 3 5 7 8 9 2\n2 4 6\n3 5 7\n8 9 2\nRow total:12 15 19\ncolumn total: 13 18 15\ndiagonal total :9 19"
}
] |
GATE | GATE-CS-2016 (Set 2) | Question 2 - GeeksforGeeks
|
28 Jun, 2021
Nobody knows how the Indian cricket team is going to cope with the difficult and seamer-friendly wickets in Australia. Choose the option which is closest in meaning to the underlined phrase in the above sentence.
(A) put up with
(B) put in with(C) put down to(D) put up againstAnswer: (A)Explanation:
put up with - is a phrasal verb
Meaning : to accept somebody/something that is annoying, unpleasant without complaining
This explanation has been contributed by Mohit Gupta.Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
|
[
{
"code": null,
"e": 24556,
"s": 24528,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24769,
"s": 24556,
"text": "Nobody knows how the Indian cricket team is going to cope with the difficult and seamer-friendly wickets in Australia. Choose the option which is closest in meaning to the underlined phrase in the above sentence."
},
{
"code": null,
"e": 24785,
"s": 24769,
"text": "(A) put up with"
},
{
"code": null,
"e": 24857,
"s": 24785,
"text": "(B) put in with(C) put down to(D) put up againstAnswer: (A)Explanation:"
},
{
"code": null,
"e": 24978,
"s": 24857,
"text": "put up with - is a phrasal verb\nMeaning : to accept somebody/something that is annoying, unpleasant without complaining\n"
},
{
"code": null,
"e": 25053,
"s": 24978,
"text": "This explanation has been contributed by Mohit Gupta.Quiz of this Question"
},
{
"code": null,
"e": 25074,
"s": 25053,
"text": "GATE-CS-2016 (Set 2)"
},
{
"code": null,
"e": 25100,
"s": 25074,
"text": "GATE-GATE-CS-2016 (Set 2)"
},
{
"code": null,
"e": 25105,
"s": 25100,
"text": "GATE"
},
{
"code": null,
"e": 25203,
"s": 25105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25237,
"s": 25203,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25279,
"s": 25237,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25321,
"s": 25279,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25355,
"s": 25321,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 25388,
"s": 25355,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25422,
"s": 25388,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25456,
"s": 25422,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 25490,
"s": 25456,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 25532,
"s": 25490,
"text": "GATE | GATE CS 2021 | Set 1 | Question 47"
}
] |
For each lowercase English alphabet find the count of strings having these alphabets - GeeksforGeeks
|
21 Feb, 2022
Given an array of strings of lowercase English alphabets. The task is for each letter [a-z] to find the count of strings having these letters.Examples:
Input: str = { “geeks”, “for”, “code” } Output: { 0 0 1 1 2 1 1 0 0 0 0 0 0 0 2 0 0 1 1 0 0 0 0 0 0 0 } Explanation: For a letter, say ‘e’, it is present in { “geeks”, “code” }, hence its count is 2. Similarly for another letter result can be found.Input: str = { “i”, “will”, “practice”, “everyday” } Output: 2 0 1 1 2 0 0 0 3 0 0 0 0 0 0 1 0 2 0 1 0 1 1 0 1 0 Explanation: For a letter, say ‘i’, it is present in { “i”, “will”, “practice” }, hence its count is 3. Similarly for another letter result can be found.
Naive Approach:
Create a global counter for each letter of size 26, initialize it with 0.Run a loop for each of the small letters’ English alphabet. Increment the counter of, say letter ‘x’, if the current letter is found in the current string.Repeat this for all lowercase English alphabet.
Create a global counter for each letter of size 26, initialize it with 0.
Run a loop for each of the small letters’ English alphabet. Increment the counter of, say letter ‘x’, if the current letter is found in the current string.
Repeat this for all lowercase English alphabet.
Time Complexity: O(26*N), where N is the sum of the length of all strings.Efficient Approach:
Instead of running a loop for each small letter English alphabet and checking whether it is present in the current string or not. We can instead run a loop on each string individually and increment the global counter for any letter present in that string.
Also, to avoid duplicate count we create a visited boolean array to mark the characters encounter so far. This approach reduces the complexity to O(N).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find count of strings// for each letter [a-z] in english alphabet#include <bits/stdc++.h>using namespace std; // Function to find the countStrings// for each letter [a-z]void CountStrings(vector<string>& str){ int size = str.size(); // Initialize result as zero vector<int> count(26, 0); // Mark all letter as not visited vector<bool> visited(26, false); // Loop through each strings for (int i = 0; i < size; ++i) { for (int j = 0; j < str[i].length(); ++j) { // Increment the global counter // for current character of string if (visited[str[i][j]] == false) count[str[i][j] - 'a']++; visited[str[i][j]] = true; } // Instead of re-initialising boolean // vector every time we just reset // all visited letter to false for (int j = 0; j < str[i].length(); ++j) { visited[str[i][j]] = false; } } // Print count for each letter for (int i = 0; i < 26; ++i) { cout << count[i] << " "; }} // Driver programint main(){ // Given array of strings vector<string> str = {"i", "will", "practice", "everyday"}; // Call the countStrings function CountStrings(str); return 0;}
// Java program to find count of Strings// for each letter [a-z] in english alphabetclass GFG{ // Function to find the countStrings// for each letter [a-z]static void CountStrings(String []str){ int size = str.length; // Initialize result as zero int []count = new int[26]; // Mark all letter as not visited boolean []visited = new boolean[26]; // Loop through each Strings for (int i = 0; i < size; ++i) { for (int j = 0; j < str[i].length(); ++j) { // Increment the global counter // for current character of String if (visited[str[i].charAt(j) - 'a'] == false) count[str[i].charAt(j) - 'a']++; visited[str[i].charAt(j) - 'a'] = true; } // Instead of re-initialising boolean // vector every time we just reset // all visited letter to false for (int j = 0; j < str[i].length(); ++j) { visited[str[i].charAt(j) - 'a'] = false; } } // Print count for each letter for (int i = 0; i < 26; ++i) { System.out.print(count[i] + " "); }} // Driver programpublic static void main(String[] args){ // Given array of Strings String []str = {"i", "will", "practice", "everyday"}; // Call the countStrings function CountStrings(str);}} // This code is contributed by shikhasingrajput
# Python3 program to find count of# strings for each letter [a-z] in# english alphabet # Function to find the countStrings# for each letter [a-z]def CountStrings(s): size = len(s) # Initialize result as zero count = [0] * 26 # Mark all letter as not visited visited = [False] * 26 # Loop through each strings for i in range(size): for j in range(len(s[i])): # Increment the global counter # for current character of string if visited[ord(s[i][j]) - ord('a')] == False: count[ord(s[i][j]) - ord('a')] += 1 visited[ord(s[i][j]) - ord('a')] = True # Instead of re-initialising boolean # vector every time we just reset # all visited letter to false for j in range(len(s[i])): visited[ord(s[i][j]) - ord('a')] = False # Print count for each letter for i in range(26): print(count[i], end = ' ') # Driver codeif __name__=='__main__': # Given array of strings s = [ "i", "will", "practice", "everyday" ] # Call the countStrings function CountStrings(s) # This code is contributed by rutvik_56
// C# program to find count of Strings// for each letter [a-z] in english alphabetusing System; class GFG{ // Function to find the countStrings// for each letter [a-z]static void CountStrings(String []str){ int size = str.Length; // Initialize result as zero int []count = new int[26]; // Mark all letter as not visited bool []visited = new bool[26]; // Loop through each Strings for(int i = 0; i < size; ++i) { for(int j = 0; j < str[i].Length; ++j) { // Increment the global counter // for current character of String if (visited[str[i][j] - 'a'] == false) count[str[i][j] - 'a']++; visited[str[i][j] - 'a'] = true; } // Instead of re-initialising bool // vector every time we just reset // all visited letter to false for(int j = 0; j < str[i].Length; ++j) { visited[str[i][j] - 'a'] = false; } } // Print count for each letter for(int i = 0; i < 26; ++i) { Console.Write(count[i] + " "); }} // Driver codepublic static void Main(String[] args){ // Given array of Strings String []str = { "i", "will", "practice", "everyday"}; // Call the countStrings function CountStrings(str);}} // This code is contributed by Amit Katiyar
<script>// JavaScript program to find count of strings// for each letter [a-z] in english alphabet // Function to find the countStrings// for each letter [a-z]function CountStrings(str){ let size = str.length; // Initialize result as zero let count = new Array(26).fill(0); // Mark all letter as not visited let visited = new Array(26).fill(false); // Loop through each strings for (let i = 0; i < size; ++i) { for (let j = 0; j < str[i].length; ++j) { // Increment the global counter // for current character of string if(visited[str[i].charCodeAt(j) - 97] == false) count[str[i].charCodeAt(j) - 97]++; visited[str[i].charCodeAt(j) - 97] = true; } // Instead of re-initialising boolean // vector every time we just reset // all visited letter to false for (let j = 0; j < str[i].length; ++j) { visited[str[i].charCodeAt(j) - 97] = false; } } // Print count for each letter for (let i = 0; i < 26; ++i) { document.write(count[i]," "); }} // Driver program // Given array of stringslet str = ["i", "will","practice", "everyday"]; // Call the countStrings functionCountStrings(str); // This code is contributed by shinjanpatra </script>
2 0 1 1 2 0 0 0 3 0 0 1 0 0 0 1 0 2 0 1 0 1 1 0 1 0
Time Complexity: O(N), where N is the sum of the length of all strings.
rutvik_56
shikhasingrajput
amit143katiyar
shinjanpatra
Arrays
Greedy
Pattern Searching
Searching
Strings
Arrays
Searching
Strings
Greedy
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 25438,
"s": 25410,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 25590,
"s": 25438,
"text": "Given an array of strings of lowercase English alphabets. The task is for each letter [a-z] to find the count of strings having these letters.Examples:"
},
{
"code": null,
"e": 26106,
"s": 25590,
"text": "Input: str = { “geeks”, “for”, “code” } Output: { 0 0 1 1 2 1 1 0 0 0 0 0 0 0 2 0 0 1 1 0 0 0 0 0 0 0 } Explanation: For a letter, say ‘e’, it is present in { “geeks”, “code” }, hence its count is 2. Similarly for another letter result can be found.Input: str = { “i”, “will”, “practice”, “everyday” } Output: 2 0 1 1 2 0 0 0 3 0 0 0 0 0 0 1 0 2 0 1 0 1 1 0 1 0 Explanation: For a letter, say ‘i’, it is present in { “i”, “will”, “practice” }, hence its count is 3. Similarly for another letter result can be found."
},
{
"code": null,
"e": 26123,
"s": 26106,
"text": "Naive Approach: "
},
{
"code": null,
"e": 26399,
"s": 26123,
"text": "Create a global counter for each letter of size 26, initialize it with 0.Run a loop for each of the small letters’ English alphabet. Increment the counter of, say letter ‘x’, if the current letter is found in the current string.Repeat this for all lowercase English alphabet."
},
{
"code": null,
"e": 26473,
"s": 26399,
"text": "Create a global counter for each letter of size 26, initialize it with 0."
},
{
"code": null,
"e": 26629,
"s": 26473,
"text": "Run a loop for each of the small letters’ English alphabet. Increment the counter of, say letter ‘x’, if the current letter is found in the current string."
},
{
"code": null,
"e": 26677,
"s": 26629,
"text": "Repeat this for all lowercase English alphabet."
},
{
"code": null,
"e": 26771,
"s": 26677,
"text": "Time Complexity: O(26*N), where N is the sum of the length of all strings.Efficient Approach:"
},
{
"code": null,
"e": 27027,
"s": 26771,
"text": "Instead of running a loop for each small letter English alphabet and checking whether it is present in the current string or not. We can instead run a loop on each string individually and increment the global counter for any letter present in that string."
},
{
"code": null,
"e": 27179,
"s": 27027,
"text": "Also, to avoid duplicate count we create a visited boolean array to mark the characters encounter so far. This approach reduces the complexity to O(N)."
},
{
"code": null,
"e": 27230,
"s": 27179,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27234,
"s": 27230,
"text": "C++"
},
{
"code": null,
"e": 27239,
"s": 27234,
"text": "Java"
},
{
"code": null,
"e": 27247,
"s": 27239,
"text": "Python3"
},
{
"code": null,
"e": 27250,
"s": 27247,
"text": "C#"
},
{
"code": null,
"e": 27261,
"s": 27250,
"text": "Javascript"
},
{
"code": "// C++ program to find count of strings// for each letter [a-z] in english alphabet#include <bits/stdc++.h>using namespace std; // Function to find the countStrings// for each letter [a-z]void CountStrings(vector<string>& str){ int size = str.size(); // Initialize result as zero vector<int> count(26, 0); // Mark all letter as not visited vector<bool> visited(26, false); // Loop through each strings for (int i = 0; i < size; ++i) { for (int j = 0; j < str[i].length(); ++j) { // Increment the global counter // for current character of string if (visited[str[i][j]] == false) count[str[i][j] - 'a']++; visited[str[i][j]] = true; } // Instead of re-initialising boolean // vector every time we just reset // all visited letter to false for (int j = 0; j < str[i].length(); ++j) { visited[str[i][j]] = false; } } // Print count for each letter for (int i = 0; i < 26; ++i) { cout << count[i] << \" \"; }} // Driver programint main(){ // Given array of strings vector<string> str = {\"i\", \"will\", \"practice\", \"everyday\"}; // Call the countStrings function CountStrings(str); return 0;}",
"e": 28573,
"s": 27261,
"text": null
},
{
"code": "// Java program to find count of Strings// for each letter [a-z] in english alphabetclass GFG{ // Function to find the countStrings// for each letter [a-z]static void CountStrings(String []str){ int size = str.length; // Initialize result as zero int []count = new int[26]; // Mark all letter as not visited boolean []visited = new boolean[26]; // Loop through each Strings for (int i = 0; i < size; ++i) { for (int j = 0; j < str[i].length(); ++j) { // Increment the global counter // for current character of String if (visited[str[i].charAt(j) - 'a'] == false) count[str[i].charAt(j) - 'a']++; visited[str[i].charAt(j) - 'a'] = true; } // Instead of re-initialising boolean // vector every time we just reset // all visited letter to false for (int j = 0; j < str[i].length(); ++j) { visited[str[i].charAt(j) - 'a'] = false; } } // Print count for each letter for (int i = 0; i < 26; ++i) { System.out.print(count[i] + \" \"); }} // Driver programpublic static void main(String[] args){ // Given array of Strings String []str = {\"i\", \"will\", \"practice\", \"everyday\"}; // Call the countStrings function CountStrings(str);}} // This code is contributed by shikhasingrajput",
"e": 29960,
"s": 28573,
"text": null
},
{
"code": "# Python3 program to find count of# strings for each letter [a-z] in# english alphabet # Function to find the countStrings# for each letter [a-z]def CountStrings(s): size = len(s) # Initialize result as zero count = [0] * 26 # Mark all letter as not visited visited = [False] * 26 # Loop through each strings for i in range(size): for j in range(len(s[i])): # Increment the global counter # for current character of string if visited[ord(s[i][j]) - ord('a')] == False: count[ord(s[i][j]) - ord('a')] += 1 visited[ord(s[i][j]) - ord('a')] = True # Instead of re-initialising boolean # vector every time we just reset # all visited letter to false for j in range(len(s[i])): visited[ord(s[i][j]) - ord('a')] = False # Print count for each letter for i in range(26): print(count[i], end = ' ') # Driver codeif __name__=='__main__': # Given array of strings s = [ \"i\", \"will\", \"practice\", \"everyday\" ] # Call the countStrings function CountStrings(s) # This code is contributed by rutvik_56",
"e": 31270,
"s": 29960,
"text": null
},
{
"code": "// C# program to find count of Strings// for each letter [a-z] in english alphabetusing System; class GFG{ // Function to find the countStrings// for each letter [a-z]static void CountStrings(String []str){ int size = str.Length; // Initialize result as zero int []count = new int[26]; // Mark all letter as not visited bool []visited = new bool[26]; // Loop through each Strings for(int i = 0; i < size; ++i) { for(int j = 0; j < str[i].Length; ++j) { // Increment the global counter // for current character of String if (visited[str[i][j] - 'a'] == false) count[str[i][j] - 'a']++; visited[str[i][j] - 'a'] = true; } // Instead of re-initialising bool // vector every time we just reset // all visited letter to false for(int j = 0; j < str[i].Length; ++j) { visited[str[i][j] - 'a'] = false; } } // Print count for each letter for(int i = 0; i < 26; ++i) { Console.Write(count[i] + \" \"); }} // Driver codepublic static void Main(String[] args){ // Given array of Strings String []str = { \"i\", \"will\", \"practice\", \"everyday\"}; // Call the countStrings function CountStrings(str);}} // This code is contributed by Amit Katiyar",
"e": 32639,
"s": 31270,
"text": null
},
{
"code": "<script>// JavaScript program to find count of strings// for each letter [a-z] in english alphabet // Function to find the countStrings// for each letter [a-z]function CountStrings(str){ let size = str.length; // Initialize result as zero let count = new Array(26).fill(0); // Mark all letter as not visited let visited = new Array(26).fill(false); // Loop through each strings for (let i = 0; i < size; ++i) { for (let j = 0; j < str[i].length; ++j) { // Increment the global counter // for current character of string if(visited[str[i].charCodeAt(j) - 97] == false) count[str[i].charCodeAt(j) - 97]++; visited[str[i].charCodeAt(j) - 97] = true; } // Instead of re-initialising boolean // vector every time we just reset // all visited letter to false for (let j = 0; j < str[i].length; ++j) { visited[str[i].charCodeAt(j) - 97] = false; } } // Print count for each letter for (let i = 0; i < 26; ++i) { document.write(count[i],\" \"); }} // Driver program // Given array of stringslet str = [\"i\", \"will\",\"practice\", \"everyday\"]; // Call the countStrings functionCountStrings(str); // This code is contributed by shinjanpatra </script>",
"e": 33961,
"s": 32639,
"text": null
},
{
"code": null,
"e": 34016,
"s": 33964,
"text": "2 0 1 1 2 0 0 0 3 0 0 1 0 0 0 1 0 2 0 1 0 1 1 0 1 0"
},
{
"code": null,
"e": 34091,
"s": 34018,
"text": "Time Complexity: O(N), where N is the sum of the length of all strings. "
},
{
"code": null,
"e": 34103,
"s": 34093,
"text": "rutvik_56"
},
{
"code": null,
"e": 34120,
"s": 34103,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 34135,
"s": 34120,
"text": "amit143katiyar"
},
{
"code": null,
"e": 34148,
"s": 34135,
"text": "shinjanpatra"
},
{
"code": null,
"e": 34155,
"s": 34148,
"text": "Arrays"
},
{
"code": null,
"e": 34162,
"s": 34155,
"text": "Greedy"
},
{
"code": null,
"e": 34180,
"s": 34162,
"text": "Pattern Searching"
},
{
"code": null,
"e": 34190,
"s": 34180,
"text": "Searching"
},
{
"code": null,
"e": 34198,
"s": 34190,
"text": "Strings"
},
{
"code": null,
"e": 34205,
"s": 34198,
"text": "Arrays"
},
{
"code": null,
"e": 34215,
"s": 34205,
"text": "Searching"
},
{
"code": null,
"e": 34223,
"s": 34215,
"text": "Strings"
},
{
"code": null,
"e": 34230,
"s": 34223,
"text": "Greedy"
},
{
"code": null,
"e": 34248,
"s": 34230,
"text": "Pattern Searching"
},
{
"code": null,
"e": 34346,
"s": 34248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34394,
"s": 34346,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34462,
"s": 34394,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34506,
"s": 34462,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34538,
"s": 34506,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34561,
"s": 34538,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34612,
"s": 34561,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 34670,
"s": 34612,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 34721,
"s": 34670,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 34752,
"s": 34721,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
Socket Programming in C#
|
The System.Net.Sockets namespace has a managed implementation of the Windows Sockets interface.
It has two basic modes − synchronous and asynchronous.
Let us see an example to work with System.Net.Sockets.TcpListener class −
TcpListener l = new TcpListener(1234);
l.Start();
// creating a socket
Socket s = l.AcceptSocket();
Stream network = new NetworkStream(s);
The following is the Socket useful in communicating on TCP/IP network −
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Above,
AddressFamily − It is the standard address families by the Socket class to resolve network addresses
AddressFamily − It is the standard address families by the Socket class to resolve network addresses
SocketType − The type of socket
SocketType − The type of socket
ProtocolType − This is the network protocol for communication on the Socket. It can be Tcp and Udp.
ProtocolType − This is the network protocol for communication on the Socket. It can be Tcp and Udp.
|
[
{
"code": null,
"e": 1158,
"s": 1062,
"text": "The System.Net.Sockets namespace has a managed implementation of the Windows Sockets interface."
},
{
"code": null,
"e": 1213,
"s": 1158,
"text": "It has two basic modes − synchronous and asynchronous."
},
{
"code": null,
"e": 1287,
"s": 1213,
"text": "Let us see an example to work with System.Net.Sockets.TcpListener class −"
},
{
"code": null,
"e": 1427,
"s": 1287,
"text": "TcpListener l = new TcpListener(1234);\nl.Start();\n\n// creating a socket\nSocket s = l.AcceptSocket();\nStream network = new NetworkStream(s);"
},
{
"code": null,
"e": 1499,
"s": 1427,
"text": "The following is the Socket useful in communicating on TCP/IP network −"
},
{
"code": null,
"e": 1588,
"s": 1499,
"text": "Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n"
},
{
"code": null,
"e": 1595,
"s": 1588,
"text": "Above,"
},
{
"code": null,
"e": 1696,
"s": 1595,
"text": "AddressFamily − It is the standard address families by the Socket class to resolve network addresses"
},
{
"code": null,
"e": 1797,
"s": 1696,
"text": "AddressFamily − It is the standard address families by the Socket class to resolve network addresses"
},
{
"code": null,
"e": 1829,
"s": 1797,
"text": "SocketType − The type of socket"
},
{
"code": null,
"e": 1861,
"s": 1829,
"text": "SocketType − The type of socket"
},
{
"code": null,
"e": 1961,
"s": 1861,
"text": "ProtocolType − This is the network protocol for communication on the Socket. It can be Tcp and Udp."
},
{
"code": null,
"e": 2061,
"s": 1961,
"text": "ProtocolType − This is the network protocol for communication on the Socket. It can be Tcp and Udp."
}
] |
Count words in a sentence in Python program
|
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a string we need to count the number of words in the string
Split function breaks the string into a list iterable with space as a delimiter. if the split() function is used without specifying the delimiter space is allocated as a default delimiter.
Live Demo
test_string = "Tutorials point is a learning platform"
#original string
print ("The original string is : " + test_string)
# using split() function
res = len(test_string.split())
# total no of words
print ("The number of words in string are : " + str(res))
The original string is : Tutorials point is a learning platform
The number of words in string are : 6
Here findall() function is used to count the number of words in the sentence available in a regex module.
Live Demo
import re
test_string = "Tutorials point is a learning platform"
# original string
print ("The original string is : " + test_string)
# using regex (findall()) function
res = len(re.findall(r'\w+', test_string))
# total no of words
print ("The number of words in string are : " + str(res))
The original string is: Tutorials point is a learning platform The number of words in string is: 6
Here we first check all the words in the given sentence and add them using the sum() function.
Live Demo
import string
test_string = "Tutorials point is a learning platform"
# printing original string
print ("The original string is: " + test_string)
# using sum() + strip() + split() function
res = sum([i.strip(string.punctuation).isalpha() for i in
test_string.split()])
# no of words
print ("The number of words in string are : " + str(res))
The original string is : Tutorials point is a learning platform
The number of words in string are : 6
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned how to count the number of words in the sentence.
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1243,
"s": 1150,
"text": "Problem statement − We are given a string we need to count the number of words in the string"
},
{
"code": null,
"e": 1432,
"s": 1243,
"text": "Split function breaks the string into a list iterable with space as a delimiter. if the split() function is used without specifying the delimiter space is allocated as a default delimiter."
},
{
"code": null,
"e": 1443,
"s": 1432,
"text": " Live Demo"
},
{
"code": null,
"e": 1699,
"s": 1443,
"text": "test_string = \"Tutorials point is a learning platform\"\n#original string\nprint (\"The original string is : \" + test_string)\n# using split() function\nres = len(test_string.split())\n# total no of words\nprint (\"The number of words in string are : \" + str(res))"
},
{
"code": null,
"e": 1801,
"s": 1699,
"text": "The original string is : Tutorials point is a learning platform\nThe number of words in string are : 6"
},
{
"code": null,
"e": 1907,
"s": 1801,
"text": "Here findall() function is used to count the number of words in the sentence available in a regex module."
},
{
"code": null,
"e": 1918,
"s": 1907,
"text": " Live Demo"
},
{
"code": null,
"e": 2207,
"s": 1918,
"text": "import re\ntest_string = \"Tutorials point is a learning platform\"\n# original string\nprint (\"The original string is : \" + test_string)\n# using regex (findall()) function\nres = len(re.findall(r'\\w+', test_string))\n# total no of words\nprint (\"The number of words in string are : \" + str(res))"
},
{
"code": null,
"e": 2306,
"s": 2207,
"text": "The original string is: Tutorials point is a learning platform The number of words in string is: 6"
},
{
"code": null,
"e": 2401,
"s": 2306,
"text": "Here we first check all the words in the given sentence and add them using the sum() function."
},
{
"code": null,
"e": 2412,
"s": 2401,
"text": " Live Demo"
},
{
"code": null,
"e": 2752,
"s": 2412,
"text": "import string\ntest_string = \"Tutorials point is a learning platform\"\n# printing original string\nprint (\"The original string is: \" + test_string)\n# using sum() + strip() + split() function\nres = sum([i.strip(string.punctuation).isalpha() for i in\ntest_string.split()])\n# no of words\nprint (\"The number of words in string are : \" + str(res))"
},
{
"code": null,
"e": 2854,
"s": 2752,
"text": "The original string is : Tutorials point is a learning platform\nThe number of words in string are : 6"
},
{
"code": null,
"e": 2955,
"s": 2854,
"text": "All the variables are declared in the local scope and their references are seen in the figure above."
},
{
"code": null,
"e": 3038,
"s": 2955,
"text": "In this article, we have learned how to count the number of words in the sentence."
}
] |
ByteArrayOutputStream size() method in Java with Examples - GeeksforGeeks
|
28 May, 2020
The size() method of ByteArrayOutputStream class in Java is used to obtain the current size of the buffer. This buffer is accumulated inside the ByteArrayOutputStream. This method returns the size of the current buffer as an integer type.
Syntax:
public int size()
Parameters: This method does not accept any parameter.
Return value: This method returns the size of the current buffer as an integer.
Exceptions: This method does not throw any exception.
Below programs illustrate size() method in ByteArrayOutputStream class in IO package:
Program 1:
// Java program to illustrate// ByteArrayOutputStream size() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83 }; for (byte b : buf) { // Write byte // to byteArrayOutputStream byteArrayOutStr.write(b); // Print the byteArrayOutputStream // as String and size as integer System.out.println( byteArrayOutStr.toString() + " " + byteArrayOutStr.size()); } }}
G 1
GE 2
GEE 3
GEEK 4
GEEKS 5
Program 2:
// Java program to illustrate// ByteArrayOutputStream size() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; for (byte b : buf) { // Write byte // to byteArrayOutputStream byteArrayOutStr.write(b); // Convert byteArrayOutputStream // into String String s = byteArrayOutStr.toString(); int buffsize = byteArrayOutStr.size(); // Print string and size System.out.println( s + " " + buffsize); } }}
G 1
GE 2
GEE 3
GEEK 4
GEEKS 5
GEEKSF 6
GEEKSFO 7
GEEKSFOR 8
GEEKSFORG 9
GEEKSFORGE 10
GEEKSFORGEE 11
GEEKSFORGEEK 12
GEEKSFORGEEKS 13
References:https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#size()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 25586,
"s": 25347,
"text": "The size() method of ByteArrayOutputStream class in Java is used to obtain the current size of the buffer. This buffer is accumulated inside the ByteArrayOutputStream. This method returns the size of the current buffer as an integer type."
},
{
"code": null,
"e": 25594,
"s": 25586,
"text": "Syntax:"
},
{
"code": null,
"e": 25613,
"s": 25594,
"text": "public int size()\n"
},
{
"code": null,
"e": 25668,
"s": 25613,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 25748,
"s": 25668,
"text": "Return value: This method returns the size of the current buffer as an integer."
},
{
"code": null,
"e": 25802,
"s": 25748,
"text": "Exceptions: This method does not throw any exception."
},
{
"code": null,
"e": 25888,
"s": 25802,
"text": "Below programs illustrate size() method in ByteArrayOutputStream class in IO package:"
},
{
"code": null,
"e": 25899,
"s": 25888,
"text": "Program 1:"
},
{
"code": "// Java program to illustrate// ByteArrayOutputStream size() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83 }; for (byte b : buf) { // Write byte // to byteArrayOutputStream byteArrayOutStr.write(b); // Print the byteArrayOutputStream // as String and size as integer System.out.println( byteArrayOutStr.toString() + \" \" + byteArrayOutStr.size()); } }}",
"e": 26638,
"s": 25899,
"text": null
},
{
"code": null,
"e": 26669,
"s": 26638,
"text": "G 1\nGE 2\nGEE 3\nGEEK 4\nGEEKS 5\n"
},
{
"code": null,
"e": 26680,
"s": 26669,
"text": "Program 2:"
},
{
"code": "// Java program to illustrate// ByteArrayOutputStream size() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; for (byte b : buf) { // Write byte // to byteArrayOutputStream byteArrayOutStr.write(b); // Convert byteArrayOutputStream // into String String s = byteArrayOutStr.toString(); int buffsize = byteArrayOutStr.size(); // Print string and size System.out.println( s + \" \" + buffsize); } }}",
"e": 27591,
"s": 26680,
"text": null
},
{
"code": null,
"e": 27726,
"s": 27591,
"text": "G 1\nGE 2\nGEE 3\nGEEK 4\nGEEKS 5\nGEEKSF 6\nGEEKSFO 7\nGEEKSFOR 8\nGEEKSFORG 9\nGEEKSFORGE 10\nGEEKSFORGEE 11\nGEEKSFORGEEK 12\nGEEKSFORGEEKS 13\n"
},
{
"code": null,
"e": 27822,
"s": 27726,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#size()"
},
{
"code": null,
"e": 27837,
"s": 27822,
"text": "Java-Functions"
},
{
"code": null,
"e": 27853,
"s": 27837,
"text": "Java-IO package"
},
{
"code": null,
"e": 27858,
"s": 27853,
"text": "Java"
},
{
"code": null,
"e": 27863,
"s": 27858,
"text": "Java"
},
{
"code": null,
"e": 27961,
"s": 27863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27976,
"s": 27961,
"text": "Stream In Java"
},
{
"code": null,
"e": 27995,
"s": 27976,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28016,
"s": 27995,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28046,
"s": 28016,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28092,
"s": 28046,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28109,
"s": 28092,
"text": "Generics in Java"
},
{
"code": null,
"e": 28130,
"s": 28109,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28173,
"s": 28130,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28195,
"s": 28173,
"text": "PriorityQueue in Java"
}
] |
Drag and Drop using DragLinearLayout in Android with Example - GeeksforGeeks
|
23 Dec, 2020
In most of the To-do list apps, we need to create a view such that the user can prioritize his daily tasks according to his priority. For this feature to work he should be able to drag and drop view items. For adding this type of functionality inside our app we have to use DragLinearLayout inside our app. In this article, we will take a look at How we can add Drag and Drop functionality for each view to change the view position. For this feature, we have to add a library for DragLinearLayout.
Using DragLinearLayout we can create a parent view inside which we can make our child item draggable. A sample GIF is given below from which we can get an idea of what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Make sure to select Java as the programming language.
Step 2: Add dependency to build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.jmedeisis:draglinearlayout:1.1.0’
Now sync the project.
Step 3: Modify the strings.xml file
Below is the code for the strings.xml file.
XML
<resources> <string name="app_name">GFG App</string> <string name="image_desc">image</string> <string name="dsa_course">DSA Course</string> <string name="geeks_for_geeks">Geeks for Geeks</string></resources>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><com.jmedeisis.draglinearlayout.DragLinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--Parent layout is a Draglinearlayout whose orientation is vertical and we have to provide id to it.--> <!--below is a simple image view --> <ImageView android:id="@+id/idIVlogo" android:layout_width="match_parent" android:layout_height="150dp" android:contentDescription="@string/image_desc" android:src="@drawable/gfgimage" /> <!--below is the simple text view--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/purple_500" android:padding="20dp" android:text="@string/geeks_for_geeks" android:textAlignment="center" android:textColor="@color/white" android:textSize="20sp" android:textStyle="bold" /> <!--below is the simple text view--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/purple_500" android:padding="10dp" android:text="@string/dsa_course" android:textAlignment="center" android:textColor="@color/white" android:textSize="20sp" android:textStyle="bold" /> </com.jmedeisis.draglinearlayout.DragLinearLayout>
Step 5: Working with the MainActivity.java file
Navigate to the app > java > your apps package name > MainActivity.java file and open MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import androidx.appcompat.app.AppCompatActivity;import com.jmedeisis.draglinearlayout.DragLinearLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // below lines is to initialize our Drag linear layout DragLinearLayout dragLayout = findViewById(R.id.container); // we are creating for loop for dragging // and dropping of child items. for (int i = 0; i < dragLayout.getChildCount(); i++) { // below is the child inside dragger layout View child = dragLayout.getChildAt(i); // below line will set all children draggable // except the header layout. // the child is its own drag handle. dragLayout.setViewDraggable(child, child); } }}
Check out the project: https://github.com/ChaitanyaMunje/GFGImageSlider/tree/DragLinearLayout
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
|
[
{
"code": null,
"e": 26516,
"s": 26488,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 27015,
"s": 26516,
"text": "In most of the To-do list apps, we need to create a view such that the user can prioritize his daily tasks according to his priority. For this feature to work he should be able to drag and drop view items. For adding this type of functionality inside our app we have to use DragLinearLayout inside our app. In this article, we will take a look at How we can add Drag and Drop functionality for each view to change the view position. For this feature, we have to add a library for DragLinearLayout. "
},
{
"code": null,
"e": 27294,
"s": 27015,
"text": "Using DragLinearLayout we can create a parent view inside which we can make our child item draggable. A sample GIF is given below from which we can get an idea of what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 27323,
"s": 27294,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27488,
"s": 27323,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Make sure to select Java as the programming language."
},
{
"code": null,
"e": 27539,
"s": 27488,
"text": "Step 2: Add dependency to build.gradle(Module:app)"
},
{
"code": null,
"e": 27656,
"s": 27539,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 27710,
"s": 27656,
"text": "implementation ‘com.jmedeisis:draglinearlayout:1.1.0’"
},
{
"code": null,
"e": 27732,
"s": 27710,
"text": "Now sync the project."
},
{
"code": null,
"e": 27768,
"s": 27732,
"text": "Step 3: Modify the strings.xml file"
},
{
"code": null,
"e": 27812,
"s": 27768,
"text": "Below is the code for the strings.xml file."
},
{
"code": null,
"e": 27816,
"s": 27812,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GFG App</string> <string name=\"image_desc\">image</string> <string name=\"dsa_course\">DSA Course</string> <string name=\"geeks_for_geeks\">Geeks for Geeks</string></resources>",
"e": 28036,
"s": 27816,
"text": null
},
{
"code": null,
"e": 28084,
"s": 28036,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 28228,
"s": 28084,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 28232,
"s": 28228,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><com.jmedeisis.draglinearlayout.DragLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/container\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Parent layout is a Draglinearlayout whose orientation is vertical and we have to provide id to it.--> <!--below is a simple image view --> <ImageView android:id=\"@+id/idIVlogo\" android:layout_width=\"match_parent\" android:layout_height=\"150dp\" android:contentDescription=\"@string/image_desc\" android:src=\"@drawable/gfgimage\" /> <!--below is the simple text view--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/purple_500\" android:padding=\"20dp\" android:text=\"@string/geeks_for_geeks\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!--below is the simple text view--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/purple_500\" android:padding=\"10dp\" android:text=\"@string/dsa_course\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </com.jmedeisis.draglinearlayout.DragLinearLayout>",
"e": 29869,
"s": 28232,
"text": null
},
{
"code": null,
"e": 29917,
"s": 29869,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30152,
"s": 29917,
"text": "Navigate to the app > java > your apps package name > MainActivity.java file and open MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 30157,
"s": 30152,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import androidx.appcompat.app.AppCompatActivity;import com.jmedeisis.draglinearlayout.DragLinearLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // below lines is to initialize our Drag linear layout DragLinearLayout dragLayout = findViewById(R.id.container); // we are creating for loop for dragging // and dropping of child items. for (int i = 0; i < dragLayout.getChildCount(); i++) { // below is the child inside dragger layout View child = dragLayout.getChildAt(i); // below line will set all children draggable // except the header layout. // the child is its own drag handle. dragLayout.setViewDraggable(child, child); } }}",
"e": 31163,
"s": 30157,
"text": null
},
{
"code": null,
"e": 31257,
"s": 31163,
"text": "Check out the project: https://github.com/ChaitanyaMunje/GFGImageSlider/tree/DragLinearLayout"
},
{
"code": null,
"e": 31265,
"s": 31257,
"text": "android"
},
{
"code": null,
"e": 31289,
"s": 31265,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31297,
"s": 31289,
"text": "Android"
},
{
"code": null,
"e": 31302,
"s": 31297,
"text": "Java"
},
{
"code": null,
"e": 31321,
"s": 31302,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31326,
"s": 31321,
"text": "Java"
},
{
"code": null,
"e": 31334,
"s": 31326,
"text": "Android"
},
{
"code": null,
"e": 31432,
"s": 31334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31470,
"s": 31432,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31509,
"s": 31470,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31559,
"s": 31509,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31585,
"s": 31559,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 31627,
"s": 31585,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31642,
"s": 31627,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31686,
"s": 31642,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31708,
"s": 31686,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31759,
"s": 31708,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Plotting different types of plots using Factor plot in seaborn - GeeksforGeeks
|
10 Feb, 2022
Prerequisites: Introduction to Seaborn
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas.
Factor Plot is used to draw a different types of categorical plot. The default plot that is shown is a point plot, but we can plot other seaborn categorical plots by using of kind parameter, like box plots, violin plots, bar plots, or strip plots.
Note: For viewing the Pokemon Dataset file, Click Here
Dataset Snippet :
Code 1: Point plot using factorplot() method of seaborn.
# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s Attack point plot sns.factorplot(x ='Stage', y ='Attack', data = df)sns.factorplot(x ='Stage', y ='Defense', data = df) # Show the plotsplt.show()
Output:
Code 2: Violin plot using factorplot() method of seaborn.
# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Type 1 v / s Attack violin plot sns.factorplot(x ='Type 1', y ='Attack', kind = 'violin', data = df) # show the plotsplt.show()
Output:
Code 3: Bar plot using factorplot() method of seaborn.
# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Type 1 v / s Defense bar plot # with Stage column is used for # colour encoding i.e # on the basis of Stages different# colours is decided, here in this# dataset, 3 Stage is mention so # 3 different colours is used.sns.factorplot(x ='Type 1', y ='Defense', kind = 'bar', hue = 'Stage', data = df) # show the plotsplt.show()
Output:
Code 4: Box plot using factorplot() method of seaborn.
# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s Defense box plot sns.factorplot(x ='Stage', y ='Defense', kind = 'box', data = df) # show the plotsplt.show()
Output:
Code 5: Strip plot using factorplot() method of seaborn.
# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s Defense strip plot sns.factorplot(x ='Stage', y ='Defense', kind = 'strip', data = df) # show the plotsplt.show()
Output:
Code 6: Count plot using factorplot() method of seaborn.
# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s count - count plot sns.factorplot(x ='Stage', kind = 'count', data = df) # show the plotsplt.show()
Output:
reenadevi98412200
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 28115,
"s": 28087,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 28154,
"s": 28115,
"text": "Prerequisites: Introduction to Seaborn"
},
{
"code": null,
"e": 28451,
"s": 28154,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas."
},
{
"code": null,
"e": 28699,
"s": 28451,
"text": "Factor Plot is used to draw a different types of categorical plot. The default plot that is shown is a point plot, but we can plot other seaborn categorical plots by using of kind parameter, like box plots, violin plots, bar plots, or strip plots."
},
{
"code": null,
"e": 28754,
"s": 28699,
"text": "Note: For viewing the Pokemon Dataset file, Click Here"
},
{
"code": null,
"e": 28772,
"s": 28754,
"text": "Dataset Snippet :"
},
{
"code": null,
"e": 28829,
"s": 28772,
"text": "Code 1: Point plot using factorplot() method of seaborn."
},
{
"code": "# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s Attack point plot sns.factorplot(x ='Stage', y ='Attack', data = df)sns.factorplot(x ='Stage', y ='Defense', data = df) # Show the plotsplt.show()",
"e": 29142,
"s": 28829,
"text": null
},
{
"code": null,
"e": 29150,
"s": 29142,
"text": "Output:"
},
{
"code": null,
"e": 29208,
"s": 29150,
"text": "Code 2: Violin plot using factorplot() method of seaborn."
},
{
"code": "# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Type 1 v / s Attack violin plot sns.factorplot(x ='Type 1', y ='Attack', kind = 'violin', data = df) # show the plotsplt.show()",
"e": 29504,
"s": 29208,
"text": null
},
{
"code": null,
"e": 29512,
"s": 29504,
"text": "Output:"
},
{
"code": null,
"e": 29567,
"s": 29512,
"text": "Code 3: Bar plot using factorplot() method of seaborn."
},
{
"code": "# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Type 1 v / s Defense bar plot # with Stage column is used for # colour encoding i.e # on the basis of Stages different# colours is decided, here in this# dataset, 3 Stage is mention so # 3 different colours is used.sns.factorplot(x ='Type 1', y ='Defense', kind = 'bar', hue = 'Stage', data = df) # show the plotsplt.show()",
"e": 30075,
"s": 29567,
"text": null
},
{
"code": null,
"e": 30083,
"s": 30075,
"text": "Output:"
},
{
"code": null,
"e": 30138,
"s": 30083,
"text": "Code 4: Box plot using factorplot() method of seaborn."
},
{
"code": "# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s Defense box plot sns.factorplot(x ='Stage', y ='Defense', kind = 'box', data = df) # show the plotsplt.show()",
"e": 30428,
"s": 30138,
"text": null
},
{
"code": null,
"e": 30436,
"s": 30428,
"text": "Output:"
},
{
"code": null,
"e": 30493,
"s": 30436,
"text": "Code 5: Strip plot using factorplot() method of seaborn."
},
{
"code": "# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s Defense strip plot sns.factorplot(x ='Stage', y ='Defense', kind = 'strip', data = df) # show the plotsplt.show()",
"e": 30788,
"s": 30493,
"text": null
},
{
"code": null,
"e": 30796,
"s": 30788,
"text": "Output:"
},
{
"code": null,
"e": 30853,
"s": 30796,
"text": "Code 6: Count plot using factorplot() method of seaborn."
},
{
"code": "# importing required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Pokemon.csv') # Stage v / s count - count plot sns.factorplot(x ='Stage', kind = 'count', data = df) # show the plotsplt.show()",
"e": 31119,
"s": 30853,
"text": null
},
{
"code": null,
"e": 31127,
"s": 31119,
"text": "Output:"
},
{
"code": null,
"e": 31145,
"s": 31127,
"text": "reenadevi98412200"
},
{
"code": null,
"e": 31160,
"s": 31145,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 31167,
"s": 31160,
"text": "Python"
},
{
"code": null,
"e": 31265,
"s": 31167,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31293,
"s": 31265,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 31343,
"s": 31293,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 31365,
"s": 31343,
"text": "Python map() function"
},
{
"code": null,
"e": 31409,
"s": 31365,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 31427,
"s": 31409,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31450,
"s": 31427,
"text": "Taking input in Python"
},
{
"code": null,
"e": 31485,
"s": 31450,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31517,
"s": 31485,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31539,
"s": 31517,
"text": "Enumerate() in Python"
}
] |
AngularJS | Tables - GeeksforGeeks
|
16 Oct, 2019
The data in tables are basically repeatable, so you can use ng-repeat directives to create tables easilyThe example will clear the approach.
Syntax:
<element ng-repeat="expression">Content..<element>
Displayed Data in table.
<!DOCTYPE html><html><head> <title>AngularJS ng-repeat Directive</title> </head><body> <center> <h1 style="color:green;">GeekforGeeks</h1> <table> <tr> <th>Course</th> <th>Duration</th> </tr> <tr ng-repeat = "subject in student.subjects"> <td>{{ Course.name }}</td> <td>{{ Duration.time }}</td> </tr> </table> </center></body></html>
Output:
Displayed with CSS style
<style> table, th , td { border: 1px solid black; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #82E0AA ; } table tr:nth-child(even) { background-color: #2ECC71 ; } h1{ color:green; }</style>
AnhularJS ng-repeat directives Example with the above codes: Here you will see the combination of above html and css with the AngularJS ng-repeat directives.
<!DOCTYPE html><html> <head> <title>Angular JS Table</title> <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <style> table, th , td { border: 1px solid black; border-collapse: collapse; padding: 5px; } table { background-color: grey; } h1{ color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <div ng-app = "mainApp" ng-controller = "studentController"> <table border = "0"> <tr> <td>Enter first name:</td> <td><input type = "text" ng-model = "student.firstName"></td> </tr> <tr> <td>Enter last name: </td> <td> <input type = "text" ng-model = "student.lastName"> </td> </tr> <tr> <td>Name: </td> <td>{{student.fullName()}}</td> </tr> <tr> <td>Subject:</td> <td> <table> <tr> <th>Name</th>. <th>Marks</th> </tr> <tr ng-repeat = "subject in student.subjects"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr> </table> </td> </tr> </table> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Pranab", lastName: "Mukherjee", subjects:[ {name:'Algorithm',marks:70}, {name:'Data Structure',marks:80}, {name:'Architecture',marks:65}, {name:'Digital Analog',marks:75} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </center> </body></html>
Output:
nidhi_biet
AngularJS-Directives
Picked
AngularJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Angular PrimeNG Calendar 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 ?
Angular PrimeNG Messages Component
What is AOT and JIT Compiler in Angular ?
How to set focus on input field automatically on page load in AngularJS ?
Angular 10 (blur) Event
|
[
{
"code": null,
"e": 29626,
"s": 29598,
"text": "\n16 Oct, 2019"
},
{
"code": null,
"e": 29767,
"s": 29626,
"text": "The data in tables are basically repeatable, so you can use ng-repeat directives to create tables easilyThe example will clear the approach."
},
{
"code": null,
"e": 29775,
"s": 29767,
"text": "Syntax:"
},
{
"code": null,
"e": 29827,
"s": 29775,
"text": "<element ng-repeat=\"expression\">Content..<element>\n"
},
{
"code": null,
"e": 29852,
"s": 29827,
"text": "Displayed Data in table."
},
{
"code": "<!DOCTYPE html><html><head> <title>AngularJS ng-repeat Directive</title> </head><body> <center> <h1 style=\"color:green;\">GeekforGeeks</h1> <table> <tr> <th>Course</th> <th>Duration</th> </tr> <tr ng-repeat = \"subject in student.subjects\"> <td>{{ Course.name }}</td> <td>{{ Duration.time }}</td> </tr> </table> </center></body></html> ",
"e": 30316,
"s": 29852,
"text": null
},
{
"code": null,
"e": 30324,
"s": 30316,
"text": "Output:"
},
{
"code": null,
"e": 30349,
"s": 30324,
"text": "Displayed with CSS style"
},
{
"code": "<style> table, th , td { border: 1px solid black; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #82E0AA ; } table tr:nth-child(even) { background-color: #2ECC71 ; } h1{ color:green; }</style>",
"e": 30633,
"s": 30349,
"text": null
},
{
"code": null,
"e": 30791,
"s": 30633,
"text": "AnhularJS ng-repeat directives Example with the above codes: Here you will see the combination of above html and css with the AngularJS ng-repeat directives."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Angular JS Table</title> <script src =\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script> <style> table, th , td { border: 1px solid black; border-collapse: collapse; padding: 5px; } table { background-color: grey; } h1{ color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <div ng-app = \"mainApp\" ng-controller = \"studentController\"> <table border = \"0\"> <tr> <td>Enter first name:</td> <td><input type = \"text\" ng-model = \"student.firstName\"></td> </tr> <tr> <td>Enter last name: </td> <td> <input type = \"text\" ng-model = \"student.lastName\"> </td> </tr> <tr> <td>Name: </td> <td>{{student.fullName()}}</td> </tr> <tr> <td>Subject:</td> <td> <table> <tr> <th>Name</th>. <th>Marks</th> </tr> <tr ng-repeat = \"subject in student.subjects\"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr> </table> </td> </tr> </table> </div> <script> var mainApp = angular.module(\"mainApp\", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: \"Pranab\", lastName: \"Mukherjee\", subjects:[ {name:'Algorithm',marks:70}, {name:'Data Structure',marks:80}, {name:'Architecture',marks:65}, {name:'Digital Analog',marks:75} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + \" \" + studentObject.lastName; } }; }); </script> </center> </body></html>",
"e": 33227,
"s": 30791,
"text": null
},
{
"code": null,
"e": 33235,
"s": 33227,
"text": "Output:"
},
{
"code": null,
"e": 33246,
"s": 33235,
"text": "nidhi_biet"
},
{
"code": null,
"e": 33267,
"s": 33246,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 33274,
"s": 33267,
"text": "Picked"
},
{
"code": null,
"e": 33284,
"s": 33274,
"text": "AngularJS"
},
{
"code": null,
"e": 33382,
"s": 33284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33402,
"s": 33382,
"text": "Angular File Upload"
},
{
"code": null,
"e": 33437,
"s": 33402,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 33459,
"s": 33437,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 33494,
"s": 33459,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 33525,
"s": 33494,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 33613,
"s": 33525,
"text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?"
},
{
"code": null,
"e": 33648,
"s": 33613,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 33690,
"s": 33648,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 33764,
"s": 33690,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
}
] |
C# | How to convert an ArrayList to Array - GeeksforGeeks
|
03 Jun, 2021
In C#, an array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float etc. and the elements are stored in a contiguous location.ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It allows dynamic memory allocation, adding, searching and sorting items in the list.
Below are the two methods for converting an ArrayList to an Array:Method 1: Convert an ArrayList to Array of object Syntax:
public virtual object[] ToArray ();
Explanation:
It copy the elements of the ArrayList to a new Object array.
It return an Object array containing copies of the elements of the ArrayList.
Example: In the below program, mylist is the ArrayList and we added 7 items to it which are the name of weekdays. Then we are creating an object array obj1 and using ToArray method with mylist we will assign the Arraylist elements to the object array. Finally, using foreach loop you can print the required converted array.
CSharp
// C# program to illustrate ToArray() Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initializing ArrayList ArrayList mylist = new ArrayList(7); mylist.Add("Monday"); mylist.Add("Tuesday"); mylist.Add("Wednesday"); mylist.Add("Thursday"); mylist.Add("Friday"); mylist.Add("Saturday"); mylist.Add("Sunday"); // Copy the data of Arraylist into // the object Array Using ToArray() // method object[] obj1 = mylist.ToArray(); foreach(string st in obj1) { Console.WriteLine(st); } }}
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Method 2: Convert An ArrayList to Array of specified type Syntax:
public virtual Array ToArray (Type t);
Here, t is the element Type of the destination array to create and copy elements.Explanation:
It copy the elements of the ArrayList to a new array of the specified element type.
It return an array of the specified element type containing copies of the elements of the ArrayList.
It throws ArgumentNullException if the value of t is null.
It throws InvalidCastException if the type of the source ArrayList cannot be cast automatically to the specified type.
Example 1:
CSharp
// C# program to illustrate the use// of ToArray(Type) Method in the// conversion of ArrayList to Arrayusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initialize new array ArrayList mylist = new ArrayList(5); mylist.Add("Ruby"); mylist.Add("C#"); mylist.Add("C++"); mylist.Add("Java"); mylist.Add("Perl"); // Copy the data of Arraylist into // the string Array Using // ToArray(Type) method string[] str = (string[])mylist.ToArray(typeof(string)); // Display the data of str string foreach(string j in str) { Console.WriteLine(j); } }}
Ruby
C#
C++
Java
Perl
Explanation of Code: Here, we are converting an ArrayList to Array of specified type i.e string type. For conversion, you have to use ToArray(Type) method along with typeof keyword. And then you have to explicitly cast it to the specified type. Here you can see the line of code, string[] str = (string[])mylist.ToArray(typeof(string));. (string[]) is used for mylist to convert it to string array type. There is another alternative for this line of code as shown in below example.Example 2:
CSharp
// C# program to illustrate the use// of ToArray(Type) Method in the// conversion of ArrayList to Arrayusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initialize new array ArrayList mylist = new ArrayList(5); mylist.Add("Ruby"); mylist.Add("C#"); mylist.Add("C++"); mylist.Add("Java"); mylist.Add("Perl"); // Copy the data of Arraylist into // the string Array Using // ToArray(Type) method // see this clearly as here we // are using as keyword string[] str = mylist.ToArray(typeof(string)) as string[]; // Display the data of str string foreach(string j in str) { Console.WriteLine(j); } }}
Ruby
C#
C++
Java
Perl
If the ArrayList doesn’t contain the elements of the same type then your conversion(ArrayList to Array) will throw InvalidCastException.Example:
CSharp
// C# program to illustrate the use// of ToArray(Type) Method in the// conversion of ArrayList to Arrayusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initialize new array ArrayList mylist = new ArrayList(5); mylist.Add("Ruby"); mylist.Add(5); mylist.Add("C++"); mylist.Add(7); mylist.Add("Perl"); // It will throw the InvalidCastException // Copy the data of Arraylist into // the string Array Using // ToArray(Type) method string[] str = mylist.ToArray(typeof(string)) as string[]; // Display the data of str string foreach(string j in str) { Console.WriteLine(j); } }}
Runtime Error:
Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
simmytarika5
CSharp-Arrays
CSharp-Collections-ArrayList
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | Class and Object
C# | Constructors
Introduction to .NET Framework
|
[
{
"code": null,
"e": 26201,
"s": 26173,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 26704,
"s": 26201,
"text": "In C#, an array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float etc. and the elements are stored in a contiguous location.ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It allows dynamic memory allocation, adding, searching and sorting items in the list. "
},
{
"code": null,
"e": 26829,
"s": 26704,
"text": "Below are the two methods for converting an ArrayList to an Array:Method 1: Convert an ArrayList to Array of object Syntax: "
},
{
"code": null,
"e": 26865,
"s": 26829,
"text": "public virtual object[] ToArray ();"
},
{
"code": null,
"e": 26879,
"s": 26865,
"text": "Explanation: "
},
{
"code": null,
"e": 26940,
"s": 26879,
"text": "It copy the elements of the ArrayList to a new Object array."
},
{
"code": null,
"e": 27018,
"s": 26940,
"text": "It return an Object array containing copies of the elements of the ArrayList."
},
{
"code": null,
"e": 27343,
"s": 27018,
"text": "Example: In the below program, mylist is the ArrayList and we added 7 items to it which are the name of weekdays. Then we are creating an object array obj1 and using ToArray method with mylist we will assign the Arraylist elements to the object array. Finally, using foreach loop you can print the required converted array. "
},
{
"code": null,
"e": 27350,
"s": 27343,
"text": "CSharp"
},
{
"code": "// C# program to illustrate ToArray() Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initializing ArrayList ArrayList mylist = new ArrayList(7); mylist.Add(\"Monday\"); mylist.Add(\"Tuesday\"); mylist.Add(\"Wednesday\"); mylist.Add(\"Thursday\"); mylist.Add(\"Friday\"); mylist.Add(\"Saturday\"); mylist.Add(\"Sunday\"); // Copy the data of Arraylist into // the object Array Using ToArray() // method object[] obj1 = mylist.ToArray(); foreach(string st in obj1) { Console.WriteLine(st); } }}",
"e": 28036,
"s": 27350,
"text": null
},
{
"code": null,
"e": 28093,
"s": 28036,
"text": "Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday"
},
{
"code": null,
"e": 28162,
"s": 28095,
"text": "Method 2: Convert An ArrayList to Array of specified type Syntax: "
},
{
"code": null,
"e": 28201,
"s": 28162,
"text": "public virtual Array ToArray (Type t);"
},
{
"code": null,
"e": 28296,
"s": 28201,
"text": "Here, t is the element Type of the destination array to create and copy elements.Explanation: "
},
{
"code": null,
"e": 28380,
"s": 28296,
"text": "It copy the elements of the ArrayList to a new array of the specified element type."
},
{
"code": null,
"e": 28481,
"s": 28380,
"text": "It return an array of the specified element type containing copies of the elements of the ArrayList."
},
{
"code": null,
"e": 28540,
"s": 28481,
"text": "It throws ArgumentNullException if the value of t is null."
},
{
"code": null,
"e": 28659,
"s": 28540,
"text": "It throws InvalidCastException if the type of the source ArrayList cannot be cast automatically to the specified type."
},
{
"code": null,
"e": 28671,
"s": 28659,
"text": "Example 1: "
},
{
"code": null,
"e": 28678,
"s": 28671,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the use// of ToArray(Type) Method in the// conversion of ArrayList to Arrayusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initialize new array ArrayList mylist = new ArrayList(5); mylist.Add(\"Ruby\"); mylist.Add(\"C#\"); mylist.Add(\"C++\"); mylist.Add(\"Java\"); mylist.Add(\"Perl\"); // Copy the data of Arraylist into // the string Array Using // ToArray(Type) method string[] str = (string[])mylist.ToArray(typeof(string)); // Display the data of str string foreach(string j in str) { Console.WriteLine(j); } }}",
"e": 29407,
"s": 28678,
"text": null
},
{
"code": null,
"e": 29429,
"s": 29407,
"text": "Ruby\nC#\nC++\nJava\nPerl"
},
{
"code": null,
"e": 29924,
"s": 29431,
"text": "Explanation of Code: Here, we are converting an ArrayList to Array of specified type i.e string type. For conversion, you have to use ToArray(Type) method along with typeof keyword. And then you have to explicitly cast it to the specified type. Here you can see the line of code, string[] str = (string[])mylist.ToArray(typeof(string));. (string[]) is used for mylist to convert it to string array type. There is another alternative for this line of code as shown in below example.Example 2: "
},
{
"code": null,
"e": 29931,
"s": 29924,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the use// of ToArray(Type) Method in the// conversion of ArrayList to Arrayusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initialize new array ArrayList mylist = new ArrayList(5); mylist.Add(\"Ruby\"); mylist.Add(\"C#\"); mylist.Add(\"C++\"); mylist.Add(\"Java\"); mylist.Add(\"Perl\"); // Copy the data of Arraylist into // the string Array Using // ToArray(Type) method // see this clearly as here we // are using as keyword string[] str = mylist.ToArray(typeof(string)) as string[]; // Display the data of str string foreach(string j in str) { Console.WriteLine(j); } }}",
"e": 30731,
"s": 29931,
"text": null
},
{
"code": null,
"e": 30753,
"s": 30731,
"text": "Ruby\nC#\nC++\nJava\nPerl"
},
{
"code": null,
"e": 30901,
"s": 30755,
"text": "If the ArrayList doesn’t contain the elements of the same type then your conversion(ArrayList to Array) will throw InvalidCastException.Example: "
},
{
"code": null,
"e": 30908,
"s": 30901,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the use// of ToArray(Type) Method in the// conversion of ArrayList to Arrayusing System;using System.Collections; class GFG { // Main Method public static void Main() { // Create and initialize new array ArrayList mylist = new ArrayList(5); mylist.Add(\"Ruby\"); mylist.Add(5); mylist.Add(\"C++\"); mylist.Add(7); mylist.Add(\"Perl\"); // It will throw the InvalidCastException // Copy the data of Arraylist into // the string Array Using // ToArray(Type) method string[] str = mylist.ToArray(typeof(string)) as string[]; // Display the data of str string foreach(string j in str) { Console.WriteLine(j); } }}",
"e": 31686,
"s": 30908,
"text": null
},
{
"code": null,
"e": 31702,
"s": 31686,
"text": "Runtime Error: "
},
{
"code": null,
"e": 31783,
"s": 31702,
"text": "Unhandled Exception: System.InvalidCastException: Specified cast is not valid. "
},
{
"code": null,
"e": 31798,
"s": 31785,
"text": "simmytarika5"
},
{
"code": null,
"e": 31812,
"s": 31798,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 31841,
"s": 31812,
"text": "CSharp-Collections-ArrayList"
},
{
"code": null,
"e": 31844,
"s": 31841,
"text": "C#"
},
{
"code": null,
"e": 31942,
"s": 31844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31970,
"s": 31942,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 31985,
"s": 31970,
"text": "C# | Delegates"
},
{
"code": null,
"e": 32008,
"s": 31985,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 32030,
"s": 32008,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 32076,
"s": 32030,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 32099,
"s": 32076,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 32121,
"s": 32099,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 32143,
"s": 32121,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 32161,
"s": 32143,
"text": "C# | Constructors"
}
] |
Smallest element greater than X not present in the array - GeeksforGeeks
|
09 Aug, 2021
Given an array arr[] of size N and an integer X. The task is to find the smallest element greater than X which is not present in the array.Examples:
Input: arr[] = {1, 5, 10, 4, 7}, X = 4 Output: 6 6 is the smallest number greater than 4 which is not present in the array.Input: arr[] = {1, 5, 10, 6, 11}, X = 10 Output: 12
Approach: An efficient solution is based on binary search. First sort the array. Take low as zero and high as N – 1. And search for the element X + 1. If the element at mid ( which is (low+high)/2 ) is less than or equals to searching element then make low as mid + 1. Otherwise, make high as mid – 1. If the element at mid gets equal to the searching element then increment the searching element by one and make high as N – 1.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the smallest element greater// than x which is not present in a[]int Next_greater(int a[], int n, int x){ // Sort the array sort(a, a + n); int low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid int mid = (low + high) / 2; // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codeint main(){ int a[] = { 1, 5, 10, 4, 7 }, x = 4; int n = sizeof(a) / sizeof(a[0]); cout << Next_greater(a, n, x); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the smallest element greater// than x which is not present in a[]static int Next_greater(int a[], int n, int x){ // Sort the array Arrays.sort(a); int low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid int mid = (low + high) / 2; // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codepublic static void main(String[] args){ int a[] = { 1, 5, 10, 4, 7 }, x = 4; int n = a.length; System.out.println(Next_greater(a, n, x));}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach # Function to return the smallest element# greater than x which is not present in a[]def Next_greater(a, n, x): # Sort the array a = sorted(a) low, high, ans = 0, n - 1, x + 1 # Continue until low is less # than or equals to high while (low <= high): # Find mid mid = (low + high) // 2 # If element at mid is less than # or equals to searching element if (a[mid] <= ans): # If mid is equals # to searching element if (a[mid] == ans): # Increment searching element ans += 1 # Make high as N - 1 high = n - 1 # Make low as mid + 1 low = mid + 1 # Make high as mid - 1 else: high = mid - 1 # Return the next greater element return ans # Driver codea = [1, 5, 10, 4, 7]x = 4n = len(a) print(Next_greater(a, n, x)) # This code is contributed# by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the smallest element greater// than x which is not present in a[]static int Next_greater(int []a, int n, int x){ // Sort the array Array.Sort(a); int low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid int mid = (low + high) / 2; // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codepublic static void Main(String[] args){ int []a = { 1, 5, 10, 4, 7 }; int x = 4; int n = a.Length; Console.WriteLine(Next_greater(a, n, x));}} // This code is contributed by Princi Singh
<?php// PHP implementation of the approach // Function to return the smallest element greater// than x which is not present in a[]function Next_greater($a, $n, $x){ // Sort the array sort($a); $low = 0; $high = $n - 1; $ans = $x + 1; // Continue until low is less // than or equals to high while ($low <= $high) { // Find mid $mid = ($low + $high) / 2; // If element at mid is less than // or equals to searching element if ($a[$mid] <= $ans) { // If mid is equals // to searching element if ($a[$mid] == $ans) { // Increment searching element $ans++; // Make high as N - 1 $high = $n - 1; } // Make low as mid + 1 $low = $mid + 1; } // Make high as mid - 1 else $high = $mid - 1; } // Return the next greater element return $ans;} // Driver code$a = array( 1, 5, 10, 4, 7 );$x = 4;$n = count($a); echo Next_greater($a, $n, $x); // This code is contributed by Naman_garg.?>
<script> // Js implementation of the approach // Function to return the smallest element greater// than x which is not present in a[]function Next_greater( a, n, x){ // Sort the array a.sort(function(aa, bb){return aa - bb}); let low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid let mid = Math.floor((low + high) / 2); // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codelet a = [ 1, 5, 10, 4, 7 ]let x = 4;let n = a.length; document.write( Next_greater(a, n, x));</script>
6
mohit kumar 29
princiraj1992
princi singh
Naman_Garg
rohitsingh07052
sumitgumber28
Binary Search
Arrays
Sorting
Arrays
Sorting
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
|
[
{
"code": null,
"e": 26177,
"s": 26149,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 26328,
"s": 26177,
"text": "Given an array arr[] of size N and an integer X. The task is to find the smallest element greater than X which is not present in the array.Examples: "
},
{
"code": null,
"e": 26505,
"s": 26328,
"text": "Input: arr[] = {1, 5, 10, 4, 7}, X = 4 Output: 6 6 is the smallest number greater than 4 which is not present in the array.Input: arr[] = {1, 5, 10, 6, 11}, X = 10 Output: 12 "
},
{
"code": null,
"e": 26985,
"s": 26505,
"text": "Approach: An efficient solution is based on binary search. First sort the array. Take low as zero and high as N – 1. And search for the element X + 1. If the element at mid ( which is (low+high)/2 ) is less than or equals to searching element then make low as mid + 1. Otherwise, make high as mid – 1. If the element at mid gets equal to the searching element then increment the searching element by one and make high as N – 1.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26989,
"s": 26985,
"text": "C++"
},
{
"code": null,
"e": 26994,
"s": 26989,
"text": "Java"
},
{
"code": null,
"e": 27002,
"s": 26994,
"text": "Python3"
},
{
"code": null,
"e": 27005,
"s": 27002,
"text": "C#"
},
{
"code": null,
"e": 27009,
"s": 27005,
"text": "PHP"
},
{
"code": null,
"e": 27020,
"s": 27009,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the smallest element greater// than x which is not present in a[]int Next_greater(int a[], int n, int x){ // Sort the array sort(a, a + n); int low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid int mid = (low + high) / 2; // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codeint main(){ int a[] = { 1, 5, 10, 4, 7 }, x = 4; int n = sizeof(a) / sizeof(a[0]); cout << Next_greater(a, n, x); return 0;}",
"e": 28171,
"s": 27020,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the smallest element greater// than x which is not present in a[]static int Next_greater(int a[], int n, int x){ // Sort the array Arrays.sort(a); int low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid int mid = (low + high) / 2; // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codepublic static void main(String[] args){ int a[] = { 1, 5, 10, 4, 7 }, x = 4; int n = a.length; System.out.println(Next_greater(a, n, x));}} // This code is contributed by PrinciRaj1992",
"e": 29393,
"s": 28171,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the smallest element# greater than x which is not present in a[]def Next_greater(a, n, x): # Sort the array a = sorted(a) low, high, ans = 0, n - 1, x + 1 # Continue until low is less # than or equals to high while (low <= high): # Find mid mid = (low + high) // 2 # If element at mid is less than # or equals to searching element if (a[mid] <= ans): # If mid is equals # to searching element if (a[mid] == ans): # Increment searching element ans += 1 # Make high as N - 1 high = n - 1 # Make low as mid + 1 low = mid + 1 # Make high as mid - 1 else: high = mid - 1 # Return the next greater element return ans # Driver codea = [1, 5, 10, 4, 7]x = 4n = len(a) print(Next_greater(a, n, x)) # This code is contributed# by Mohit Kumar",
"e": 30397,
"s": 29393,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the smallest element greater// than x which is not present in a[]static int Next_greater(int []a, int n, int x){ // Sort the array Array.Sort(a); int low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid int mid = (low + high) / 2; // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codepublic static void Main(String[] args){ int []a = { 1, 5, 10, 4, 7 }; int x = 4; int n = a.Length; Console.WriteLine(Next_greater(a, n, x));}} // This code is contributed by Princi Singh",
"e": 31619,
"s": 30397,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the smallest element greater// than x which is not present in a[]function Next_greater($a, $n, $x){ // Sort the array sort($a); $low = 0; $high = $n - 1; $ans = $x + 1; // Continue until low is less // than or equals to high while ($low <= $high) { // Find mid $mid = ($low + $high) / 2; // If element at mid is less than // or equals to searching element if ($a[$mid] <= $ans) { // If mid is equals // to searching element if ($a[$mid] == $ans) { // Increment searching element $ans++; // Make high as N - 1 $high = $n - 1; } // Make low as mid + 1 $low = $mid + 1; } // Make high as mid - 1 else $high = $mid - 1; } // Return the next greater element return $ans;} // Driver code$a = array( 1, 5, 10, 4, 7 );$x = 4;$n = count($a); echo Next_greater($a, $n, $x); // This code is contributed by Naman_garg.?>",
"e": 32751,
"s": 31619,
"text": null
},
{
"code": "<script> // Js implementation of the approach // Function to return the smallest element greater// than x which is not present in a[]function Next_greater( a, n, x){ // Sort the array a.sort(function(aa, bb){return aa - bb}); let low = 0, high = n - 1, ans = x + 1; // Continue until low is less // than or equals to high while (low <= high) { // Find mid let mid = Math.floor((low + high) / 2); // If element at mid is less than // or equals to searching element if (a[mid] <= ans) { // If mid is equals // to searching element if (a[mid] == ans) { // Increment searching element ans++; // Make high as N - 1 high = n - 1; } // Make low as mid + 1 low = mid + 1; } // Make high as mid - 1 else high = mid - 1; } // Return the next greater element return ans;} // Driver codelet a = [ 1, 5, 10, 4, 7 ]let x = 4;let n = a.length; document.write( Next_greater(a, n, x));</script>",
"e": 33859,
"s": 32751,
"text": null
},
{
"code": null,
"e": 33861,
"s": 33859,
"text": "6"
},
{
"code": null,
"e": 33878,
"s": 33863,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33892,
"s": 33878,
"text": "princiraj1992"
},
{
"code": null,
"e": 33905,
"s": 33892,
"text": "princi singh"
},
{
"code": null,
"e": 33916,
"s": 33905,
"text": "Naman_Garg"
},
{
"code": null,
"e": 33932,
"s": 33916,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 33946,
"s": 33932,
"text": "sumitgumber28"
},
{
"code": null,
"e": 33960,
"s": 33946,
"text": "Binary Search"
},
{
"code": null,
"e": 33967,
"s": 33960,
"text": "Arrays"
},
{
"code": null,
"e": 33975,
"s": 33967,
"text": "Sorting"
},
{
"code": null,
"e": 33982,
"s": 33975,
"text": "Arrays"
},
{
"code": null,
"e": 33990,
"s": 33982,
"text": "Sorting"
},
{
"code": null,
"e": 34004,
"s": 33990,
"text": "Binary Search"
},
{
"code": null,
"e": 34102,
"s": 34004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34133,
"s": 34102,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 34171,
"s": 34133,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34196,
"s": 34171,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34217,
"s": 34196,
"text": "Next Greater Element"
}
] |
Difference between Static variables and Register variables in C - GeeksforGeeks
|
04 Jan, 2021
static variables
Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Syntax:
static data_type var_name = var_value;
register variables
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword. The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers themselves do optimizations and put the variables in the register.
Syntax:
register data_type var_name = var_value;
Differences between static variables and register variables in C.
anandagrawal1
C-Variable Declaration and Scope
C Language
Difference Between
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
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 Process and Thread
|
[
{
"code": null,
"e": 24509,
"s": 24481,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 24526,
"s": 24509,
"text": "static variables"
},
{
"code": null,
"e": 24752,
"s": 24526,
"text": "Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. "
},
{
"code": null,
"e": 24761,
"s": 24752,
"text": "Syntax: "
},
{
"code": null,
"e": 24800,
"s": 24761,
"text": "static data_type var_name = var_value;"
},
{
"code": null,
"e": 24819,
"s": 24800,
"text": "register variables"
},
{
"code": null,
"e": 25205,
"s": 24819,
"text": "Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword. The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers themselves do optimizations and put the variables in the register. "
},
{
"code": null,
"e": 25215,
"s": 25205,
"text": "Syntax: "
},
{
"code": null,
"e": 25256,
"s": 25215,
"text": "register data_type var_name = var_value;"
},
{
"code": null,
"e": 25323,
"s": 25256,
"text": "Differences between static variables and register variables in C. "
},
{
"code": null,
"e": 25339,
"s": 25325,
"text": "anandagrawal1"
},
{
"code": null,
"e": 25372,
"s": 25339,
"text": "C-Variable Declaration and Scope"
},
{
"code": null,
"e": 25383,
"s": 25372,
"text": "C Language"
},
{
"code": null,
"e": 25402,
"s": 25383,
"text": "Difference Between"
},
{
"code": null,
"e": 25421,
"s": 25402,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25519,
"s": 25421,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25547,
"s": 25519,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25559,
"s": 25547,
"text": "fork() in C"
},
{
"code": null,
"e": 25591,
"s": 25559,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25613,
"s": 25591,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 25630,
"s": 25613,
"text": "Substring in C++"
},
{
"code": null,
"e": 25661,
"s": 25630,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 25701,
"s": 25661,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 25733,
"s": 25701,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 25794,
"s": 25733,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Implementation of BFS using adjacency matrix - GeeksforGeeks
|
03 Feb, 2022
Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph.
Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent the edges of the graph where mat[i][j] = 1 represents that there is an edge between the vertices i and j while mat[i][j] = 0 represents that there is no edge between the vertices i and j.
Below is the adjacency matrix representation of the graph shown in the above image:
0 1 2 3
0 0 1 1 0
1 1 0 0 1
2 1 0 0 0
3 0 1 0 0
Examples:
Input: source = 0
Output: 0 1 2 3
Input: source = 1
Output:1 0 2 3 4
Approach:
Create a matrix of size n*n where every element is 0 representing there is no edge in the graph.
Now, for every edge of the graph between the vertices i and j set mat[i][j] = 1.
After the adjacency matrix has been created and filled, find the BFS traversal of the graph as described in this post.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; vector<vector<int>> adj; // function to add edge to the graphvoid addEdge(int x,int y){ adj[x][y] = 1; adj[y][x] = 1;} // Function to perform BFS on the graphvoid bfs(int start){ // Visited vector to so that // a vertex is not visited more than once // Initializing the vector to false as no // vertex is visited at the beginning vector<bool> visited(adj.size(), false); vector<int> q; q.push_back(start); // Set source as visited visited[start] = true; int vis; while (!q.empty()) { vis = q[0]; // Print the current node cout << vis << " "; q.erase(q.begin()); // For every adjacent vertex to the current vertex for (int i = 0; i < adj[vis].size(); i++) { if (adj[vis][i] == 1 && (!visited[i])) { // Push the adjacent node to the queue q.push_back(i); // Set visited[i] = true; } } }} // Driver codeint main(){ // number of vertices int v = 5; // adjacency matrix adj= vector<vector<int>>(v,vector<int>(v,0)); addEdge(0,1); addEdge(0,2); addEdge(1,3); // perform bfs on the graph bfs(0);}
// Java implementation of the approachimport java.util.ArrayList;import java.util.Arrays;import java.util.List; class GFG{ static class Graph{ // Number of vertex int v; // Number of edges int e; // Adjacency matrix int[][] adj; // Function to fill the empty // adjacency matrix Graph(int v, int e) { this.v = v; this.e = e; adj = new int[v][v]; for(int row = 0; row < v; row++) Arrays.fill(adj[row], 0); } // Function to add an edge to the graph void addEdge(int start, int e) { // Considering a bidirectional edge adj[start][e] = 1; adj[e][start] = 1; } // Function to perform BFS on the graph void BFS(int start) { // Visited vector to so that // a vertex is not visited more than once // Initializing the vector to false as no // vertex is visited at the beginning boolean[] visited = new boolean[v]; Arrays.fill(visited, false); List<Integer> q = new ArrayList<>(); q.add(start); // Set source as visited visited[start] = true; int vis; while (!q.isEmpty()) { vis = q.get(0); // Print the current node System.out.print(vis + " "); q.remove(q.get(0)); // For every adjacent vertex to // the current vertex for(int i = 0; i < v; i++) { if (adj[vis][i] == 1 && (!visited[i])) { // Push the adjacent node to // the queue q.add(i); // Set visited[i] = true; } } } }} // Driver codepublic static void main(String[] args){ int v = 5, e = 4; // Create the graph Graph G = new Graph(v, e); G.addEdge(0, 1); G.addEdge(0, 2); G.addEdge(1, 3); G.BFS(0);}} // This code is contributed by sanjeev2552
# Python3 implementation of the approachclass Graph: adj = [] # Function to fill empty adjacency matrix def __init__(self, v, e): self.v = v self.e = e Graph.adj = [[0 for i in range(v)] for j in range(v)] # Function to add an edge to the graph def addEdge(self, start, e): # Considering a bidirectional edge Graph.adj[start][e] = 1 Graph.adj[e][start] = 1 # Function to perform DFS on the graph def BFS(self, start): # Visited vector to so that a # vertex is not visited more than # once Initializing the vector to # false as no vertex is visited at # the beginning visited = [False] * self.v q = [start] # Set source as visited visited[start] = True while q: vis = q[0] # Print current node print(vis, end = ' ') q.pop(0) # For every adjacent vertex to # the current vertex for i in range(self.v): if (Graph.adj[vis][i] == 1 and (not visited[i])): # Push the adjacent node # in the queue q.append(i) # set visited[i] = True # Driver codev, e = 5, 4 # Create the graphG = Graph(v, e)G.addEdge(0, 1)G.addEdge(0, 2)G.addEdge(1, 3) # Perform BFSG.BFS(0) # This code is contributed by ng24_7
// C# implementation of the approachusing System;using System.Collections.Generic; public class GFG{ class Graph { // Number of vertex public int v; // Number of edges public int e; // Adjacency matrix public int[,] adj; // Function to fill the empty // adjacency matrix public Graph(int v, int e) { this.v = v; this.e = e; adj = new int[v,v]; for(int row = 0; row < v; row++) for(int col = 0; col < v; col++) adj[row, col] = 0; } // Function to add an edge to the graph public void addEdge(int start, int e) { // Considering a bidirectional edge adj[start, e] = 1; adj[e, start] = 1; } // Function to perform BFS on the graph public void BFS(int start) { // Visited vector to so that // a vertex is not visited more than once // Initializing the vector to false as no // vertex is visited at the beginning bool[] visited = new bool[v]; List<int> q = new List<int>(); q.Add(start); // Set source as visited visited[start] = true; int vis; while (q.Count != 0) { vis = q[0]; // Print the current node Console.Write(vis + " "); q.Remove(q[0]); // For every adjacent vertex to // the current vertex for(int i = 0; i < v; i++) { if (adj[vis,i] == 1 && (!visited[i])) { // Push the adjacent node to // the queue q.Add(i); // Set visited[i] = true; } } } } } // Driver code public static void Main(String[] args) { int v = 5, e = 4; // Create the graph Graph G = new Graph(v, e); G.addEdge(0, 1); G.addEdge(0, 2); G.addEdge(1, 3); G.BFS(0); }} // This code is contributed by shikhasingrajput
0 1 2 3
Time Complexity: O(N*N)Auxiliary Space: O(N)
prat31
naina024
sanjeev2552
khushboogoyal499
pankajsharmagfg
Angad
ashutoshsinghgeeksforgeeks
shikhasingrajput
BFS
Algorithms
Graph
Matrix
Searching
Searching
Matrix
Graph
BFS
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Quick Sort vs Merge Sort
Converting Roman Numerals to Decimal lying between 1 to 3999
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations
|
[
{
"code": null,
"e": 25030,
"s": 25002,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 25219,
"s": 25030,
"text": "Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph."
},
{
"code": null,
"e": 25570,
"s": 25219,
"text": "Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent the edges of the graph where mat[i][j] = 1 represents that there is an edge between the vertices i and j while mat[i][j] = 0 represents that there is no edge between the vertices i and j. "
},
{
"code": null,
"e": 25655,
"s": 25570,
"text": "Below is the adjacency matrix representation of the graph shown in the above image: "
},
{
"code": null,
"e": 25708,
"s": 25655,
"text": " 0 1 2 3\n0 0 1 1 0 \n1 1 0 0 1 \n2 1 0 0 0 \n3 0 1 0 0"
},
{
"code": null,
"e": 25719,
"s": 25708,
"text": "Examples: "
},
{
"code": null,
"e": 25737,
"s": 25719,
"text": "Input: source = 0"
},
{
"code": null,
"e": 25772,
"s": 25737,
"text": "Output: 0 1 2 3\n\nInput: source = 1"
},
{
"code": null,
"e": 25789,
"s": 25772,
"text": "Output:1 0 2 3 4"
},
{
"code": null,
"e": 25800,
"s": 25789,
"text": "Approach: "
},
{
"code": null,
"e": 25897,
"s": 25800,
"text": "Create a matrix of size n*n where every element is 0 representing there is no edge in the graph."
},
{
"code": null,
"e": 25978,
"s": 25897,
"text": "Now, for every edge of the graph between the vertices i and j set mat[i][j] = 1."
},
{
"code": null,
"e": 26097,
"s": 25978,
"text": "After the adjacency matrix has been created and filled, find the BFS traversal of the graph as described in this post."
},
{
"code": null,
"e": 26149,
"s": 26097,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26153,
"s": 26149,
"text": "C++"
},
{
"code": null,
"e": 26158,
"s": 26153,
"text": "Java"
},
{
"code": null,
"e": 26166,
"s": 26158,
"text": "Python3"
},
{
"code": null,
"e": 26169,
"s": 26166,
"text": "C#"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; vector<vector<int>> adj; // function to add edge to the graphvoid addEdge(int x,int y){ adj[x][y] = 1; adj[y][x] = 1;} // Function to perform BFS on the graphvoid bfs(int start){ // Visited vector to so that // a vertex is not visited more than once // Initializing the vector to false as no // vertex is visited at the beginning vector<bool> visited(adj.size(), false); vector<int> q; q.push_back(start); // Set source as visited visited[start] = true; int vis; while (!q.empty()) { vis = q[0]; // Print the current node cout << vis << \" \"; q.erase(q.begin()); // For every adjacent vertex to the current vertex for (int i = 0; i < adj[vis].size(); i++) { if (adj[vis][i] == 1 && (!visited[i])) { // Push the adjacent node to the queue q.push_back(i); // Set visited[i] = true; } } }} // Driver codeint main(){ // number of vertices int v = 5; // adjacency matrix adj= vector<vector<int>>(v,vector<int>(v,0)); addEdge(0,1); addEdge(0,2); addEdge(1,3); // perform bfs on the graph bfs(0);}",
"e": 27442,
"s": 26169,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.ArrayList;import java.util.Arrays;import java.util.List; class GFG{ static class Graph{ // Number of vertex int v; // Number of edges int e; // Adjacency matrix int[][] adj; // Function to fill the empty // adjacency matrix Graph(int v, int e) { this.v = v; this.e = e; adj = new int[v][v]; for(int row = 0; row < v; row++) Arrays.fill(adj[row], 0); } // Function to add an edge to the graph void addEdge(int start, int e) { // Considering a bidirectional edge adj[start][e] = 1; adj[e][start] = 1; } // Function to perform BFS on the graph void BFS(int start) { // Visited vector to so that // a vertex is not visited more than once // Initializing the vector to false as no // vertex is visited at the beginning boolean[] visited = new boolean[v]; Arrays.fill(visited, false); List<Integer> q = new ArrayList<>(); q.add(start); // Set source as visited visited[start] = true; int vis; while (!q.isEmpty()) { vis = q.get(0); // Print the current node System.out.print(vis + \" \"); q.remove(q.get(0)); // For every adjacent vertex to // the current vertex for(int i = 0; i < v; i++) { if (adj[vis][i] == 1 && (!visited[i])) { // Push the adjacent node to // the queue q.add(i); // Set visited[i] = true; } } } }} // Driver codepublic static void main(String[] args){ int v = 5, e = 4; // Create the graph Graph G = new Graph(v, e); G.addEdge(0, 1); G.addEdge(0, 2); G.addEdge(1, 3); G.BFS(0);}} // This code is contributed by sanjeev2552",
"e": 29483,
"s": 27442,
"text": null
},
{
"code": "# Python3 implementation of the approachclass Graph: adj = [] # Function to fill empty adjacency matrix def __init__(self, v, e): self.v = v self.e = e Graph.adj = [[0 for i in range(v)] for j in range(v)] # Function to add an edge to the graph def addEdge(self, start, e): # Considering a bidirectional edge Graph.adj[start][e] = 1 Graph.adj[e][start] = 1 # Function to perform DFS on the graph def BFS(self, start): # Visited vector to so that a # vertex is not visited more than # once Initializing the vector to # false as no vertex is visited at # the beginning visited = [False] * self.v q = [start] # Set source as visited visited[start] = True while q: vis = q[0] # Print current node print(vis, end = ' ') q.pop(0) # For every adjacent vertex to # the current vertex for i in range(self.v): if (Graph.adj[vis][i] == 1 and (not visited[i])): # Push the adjacent node # in the queue q.append(i) # set visited[i] = True # Driver codev, e = 5, 4 # Create the graphG = Graph(v, e)G.addEdge(0, 1)G.addEdge(0, 2)G.addEdge(1, 3) # Perform BFSG.BFS(0) # This code is contributed by ng24_7",
"e": 31035,
"s": 29483,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; public class GFG{ class Graph { // Number of vertex public int v; // Number of edges public int e; // Adjacency matrix public int[,] adj; // Function to fill the empty // adjacency matrix public Graph(int v, int e) { this.v = v; this.e = e; adj = new int[v,v]; for(int row = 0; row < v; row++) for(int col = 0; col < v; col++) adj[row, col] = 0; } // Function to add an edge to the graph public void addEdge(int start, int e) { // Considering a bidirectional edge adj[start, e] = 1; adj[e, start] = 1; } // Function to perform BFS on the graph public void BFS(int start) { // Visited vector to so that // a vertex is not visited more than once // Initializing the vector to false as no // vertex is visited at the beginning bool[] visited = new bool[v]; List<int> q = new List<int>(); q.Add(start); // Set source as visited visited[start] = true; int vis; while (q.Count != 0) { vis = q[0]; // Print the current node Console.Write(vis + \" \"); q.Remove(q[0]); // For every adjacent vertex to // the current vertex for(int i = 0; i < v; i++) { if (adj[vis,i] == 1 && (!visited[i])) { // Push the adjacent node to // the queue q.Add(i); // Set visited[i] = true; } } } } } // Driver code public static void Main(String[] args) { int v = 5, e = 4; // Create the graph Graph G = new Graph(v, e); G.addEdge(0, 1); G.addEdge(0, 2); G.addEdge(1, 3); G.BFS(0); }} // This code is contributed by shikhasingrajput",
"e": 32887,
"s": 31035,
"text": null
},
{
"code": null,
"e": 32895,
"s": 32887,
"text": "0 1 2 3"
},
{
"code": null,
"e": 32942,
"s": 32897,
"text": "Time Complexity: O(N*N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32949,
"s": 32942,
"text": "prat31"
},
{
"code": null,
"e": 32958,
"s": 32949,
"text": "naina024"
},
{
"code": null,
"e": 32970,
"s": 32958,
"text": "sanjeev2552"
},
{
"code": null,
"e": 32987,
"s": 32970,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 33003,
"s": 32987,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 33009,
"s": 33003,
"text": "Angad"
},
{
"code": null,
"e": 33036,
"s": 33009,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 33053,
"s": 33036,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 33057,
"s": 33053,
"text": "BFS"
},
{
"code": null,
"e": 33068,
"s": 33057,
"text": "Algorithms"
},
{
"code": null,
"e": 33074,
"s": 33068,
"text": "Graph"
},
{
"code": null,
"e": 33081,
"s": 33074,
"text": "Matrix"
},
{
"code": null,
"e": 33091,
"s": 33081,
"text": "Searching"
},
{
"code": null,
"e": 33101,
"s": 33091,
"text": "Searching"
},
{
"code": null,
"e": 33108,
"s": 33101,
"text": "Matrix"
},
{
"code": null,
"e": 33114,
"s": 33108,
"text": "Graph"
},
{
"code": null,
"e": 33118,
"s": 33114,
"text": "BFS"
},
{
"code": null,
"e": 33129,
"s": 33118,
"text": "Algorithms"
},
{
"code": null,
"e": 33227,
"s": 33129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33276,
"s": 33227,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 33301,
"s": 33276,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33328,
"s": 33301,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 33353,
"s": 33328,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 33414,
"s": 33353,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 33465,
"s": 33414,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 33523,
"s": 33465,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 33574,
"s": 33523,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
] |
Julia end Keyword | Marking end of blocks in Julia - GeeksforGeeks
|
26 Mar, 2020
Keywords in Julia are reserved words that have a pre-defined meaning to the compiler. These keywords can’t be used as a variable name.
'end' keyword in Julia is used to mark the end of a block of statements. This block can be of any type like struct, loop, conditional statement, module, etc.
Syntax:
block_type block_name
Statement
Statement
end
Example:
# Julia program to illustrate# the use of 'end' keyword # Defining a functionfunction fn() # Defining for-loop for i in 1:5 # Using if-else block if i % 2 == 0 println(i, " is even"); else println(i, " is odd"); # Marking end of if-else end # Marking end of for-loop end # Marking end of function end # Function callfn()
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
Note: 'end' can also be used to mark the last index in a 1D array.
Example:
# Julia program to illustrate# the use of 'end' keyword # Defining ArrayArray1 = Array([1, 2, 3, 4, 5]) # Printing last element using 'end' keywordprintln("Last element of Array: ", Array1[end])
Output:
Last element of Array: 5
Julia-keywords
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get number of elements of array in Julia - length() Method
Find maximum element along with its index in Julia - findmax() Method
Getting the maximum value from a list in Julia - max() Method
Exception handling in Julia
Getting the absolute value of a number in Julia - abs() Method
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Working with Date and Time in Julia
|
[
{
"code": null,
"e": 24544,
"s": 24516,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24679,
"s": 24544,
"text": "Keywords in Julia are reserved words that have a pre-defined meaning to the compiler. These keywords can’t be used as a variable name."
},
{
"code": null,
"e": 24837,
"s": 24679,
"text": "'end' keyword in Julia is used to mark the end of a block of statements. This block can be of any type like struct, loop, conditional statement, module, etc."
},
{
"code": null,
"e": 24845,
"s": 24837,
"text": "Syntax:"
},
{
"code": null,
"e": 24900,
"s": 24845,
"text": "block_type block_name\n Statement\n Statement\nend\n"
},
{
"code": null,
"e": 24909,
"s": 24900,
"text": "Example:"
},
{
"code": "# Julia program to illustrate# the use of 'end' keyword # Defining a functionfunction fn() # Defining for-loop for i in 1:5 # Using if-else block if i % 2 == 0 println(i, \" is even\"); else println(i, \" is odd\"); # Marking end of if-else end # Marking end of for-loop end # Marking end of function end # Function callfn()",
"e": 25346,
"s": 24909,
"text": null
},
{
"code": null,
"e": 25354,
"s": 25346,
"text": "Output:"
},
{
"code": null,
"e": 25402,
"s": 25354,
"text": "1 is odd\n2 is even\n3 is odd\n4 is even\n5 is odd\n"
},
{
"code": null,
"e": 25469,
"s": 25402,
"text": "Note: 'end' can also be used to mark the last index in a 1D array."
},
{
"code": null,
"e": 25478,
"s": 25469,
"text": "Example:"
},
{
"code": "# Julia program to illustrate# the use of 'end' keyword # Defining ArrayArray1 = Array([1, 2, 3, 4, 5]) # Printing last element using 'end' keywordprintln(\"Last element of Array: \", Array1[end])",
"e": 25675,
"s": 25478,
"text": null
},
{
"code": null,
"e": 25683,
"s": 25675,
"text": "Output:"
},
{
"code": null,
"e": 25709,
"s": 25683,
"text": "Last element of Array: 5\n"
},
{
"code": null,
"e": 25724,
"s": 25709,
"text": "Julia-keywords"
},
{
"code": null,
"e": 25730,
"s": 25724,
"text": "Julia"
},
{
"code": null,
"e": 25828,
"s": 25730,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25876,
"s": 25828,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 25946,
"s": 25876,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 26019,
"s": 25946,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 26078,
"s": 26019,
"text": "Get number of elements of array in Julia - length() Method"
},
{
"code": null,
"e": 26148,
"s": 26078,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 26210,
"s": 26148,
"text": "Getting the maximum value from a list in Julia - max() Method"
},
{
"code": null,
"e": 26238,
"s": 26210,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 26301,
"s": 26238,
"text": "Getting the absolute value of a number in Julia - abs() Method"
},
{
"code": null,
"e": 26382,
"s": 26301,
"text": "Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods"
}
] |
Creating DenseNet 121 with TensorFlow | by Arjun Sarkar | Towards Data Science
|
DenseNet paper link: https://arxiv.org/pdf/1608.06993.pdf
DenseNet (Dense Convolutional Network) is an architecture that focuses on making the deep learning networks go even deeper, but at the same time making them more efficient to train, by using shorter connections between the layers. DenseNet is a convolutional neural network where each layer is connected to all other layers that are deeper in the network, that is, the first layer is connected to the 2nd, 3rd, 4th and so on, the second layer is connected to the 3rd, 4th, 5th and so on. This is done to enable maximum information flow between the layers of the network. To preserve the feed-forward nature, each layer obtains inputs from all the previous layers and passes on its own feature maps to all the layers which will come after it. Unlike Resnets it does not combine features through summation but combines the features by concatenating them. So the ‘ith’ layer has ‘i’ inputs and consists of feature maps of all its preceding convolutional blocks. Its own feature maps are passed on to all the next ‘I-i’ layers. This introduces ‘(I(I+1))/2’ connections in the network, rather than just ‘I’ connections as in traditional deep learning architectures. It hence requires fewer parameters than traditional convolutional neural networks, as there is no need to learn unimportant feature maps.
DenseNet consists of two important blocks other than the basic convolutional and pooling layers. they are the Dense Blocks and the Transition layers.
Next, we look at how all these blocks and layers look, and how to implement them in python.
DenseNet starts with a basic convolution and pooling layer. Then there is a dense block followed by a transition layer, another dense block followed by a transition layer, another dense block followed by a transition layer, and finally a dense block followed by a classification layer.
The first convolution block has 64 filters of size 7x7 and a stride of 2. It is followed by a MaxPooling layer with 3x3 max pooling and a stride of 2. These two lines can be represented with the following code in python.
input = Input (input_shape)x = Conv2D(64, 7, strides = 2, padding = 'same')(input)x = MaxPool2D(3, strides = 2, padding = 'same')(x)
Defining the convolutional block — Each convolutional block after the input has the following sequence: BatchNormalization, followed by ReLU activation and then the actual Conv2D layer. To implement that, we can write the following function.
#batch norm + relu + convdef bn_rl_conv(x,filters,kernel=1,strides=1): x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters, kernel, strides=strides,padding = 'same')(x) return x
Defining the Dense block — As seen in figure 3, Every dense block has two convolutions, with 1x1 and 3x3 sized kernels. In dense block 1, this is repeated 6 times, in dense block 2 it is repeated 12 times, in dense block 3, 24 times and finally in dense block 4, 16 times.
In dense block, each of the 1x1 convolutions has 4 times the number of filters. So we use 4*filters, but 3x3 filters are only present once. Also, we have to concatenate the input with the output tensor.
Each block is run for the 6,12,24,16 repetitions respectively, using the ‘for loop’.
def dense_block(x, repetition): for _ in range(repetition): y = bn_rl_conv(x, 4*filters) y = bn_rl_conv(y, filters, 3) x = concatenate([y,x]) return x
Defining the transition layer — In the transition layer, we are to reduce the number of channels to half of the existing channels. There are a 1x1 convolutional layer and a 2x2 average pooling layer with a stride of 2. kernel size of 1x1 is already set in the function, bn_rl_conv, so we do not explicitly need to define it again.
In the transition layers, we have to remove channels to half of the existing channels. We have the input tensor x, and we want to find how many channels there are, and we need to get half of them. So we can use Keras backend (K) to take the tensor x and return a tuple with the dimension of x. And, we only require the last number of that shape, that is, the number of the filters. So we add [-1]. Finally, we can just divide this number of filters by 2 to get the desired result.
def transition_layer(x): x = bn_rl_conv(x, K.int_shape(x)[-1] //2 ) x = AvgPool2D(2, strides = 2, padding = 'same')(x) return x
So we are done with defining the dense blocks and transition layers. Now we need to stack the dense blocks and transition layers together. So we write a for loop to run through the 6,12,24,16 repetitions. So the loop runs 4 times, each time using one of the values from 6,12,24 or 16. This completes the 4 dense blocks and transition layers.
for repetition in [6,12,24,16]: d = dense_block(x, repetition) x = transition_layer(d)
In the end, there is GlobalAveragePooling, followed by the final output layer. As we see in the above code block, the dense block is defined by ‘d’, and in the final layer, after Dense block 4, there is no transition layer 4, but it directly goes into the classification layer. So, ‘d’ is the connection on which GlobalAveragePooling is applied, and not on ‘x’. Another alternative is to remove the ‘for’ loop from the code above and stack the layers one after the other without the final transition layer.
x = GlobalAveragePooling2D()(d)output = Dense(n_classes, activation = 'softmax')(x)
Now that we have all the blocks together, let's merge them to see the entire DenseNet architecture.
Complete DenseNet 121 architecture:
import tensorflow as tffrom tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Densefrom tensorflow.keras.layers import AvgPool2D, GlobalAveragePooling2D, MaxPool2Dfrom tensorflow.keras.models import Modelfrom tensorflow.keras.layers import ReLU, concatenateimport tensorflow.keras.backend as K# Creating Densenet121def densenet(input_shape, n_classes, filters = 32): #batch norm + relu + conv def bn_rl_conv(x,filters,kernel=1,strides=1): x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters, kernel, strides=strides,padding = 'same')(x) return x def dense_block(x, repetition): for _ in range(repetition): y = bn_rl_conv(x, 4*filters) y = bn_rl_conv(y, filters, 3) x = concatenate([y,x]) return x def transition_layer(x): x = bn_rl_conv(x, K.int_shape(x)[-1] //2 ) x = AvgPool2D(2, strides = 2, padding = 'same')(x) return x input = Input (input_shape) x = Conv2D(64, 7, strides = 2, padding = 'same')(input) x = MaxPool2D(3, strides = 2, padding = 'same')(x) for repetition in [6,12,24,16]: d = dense_block(x, repetition) x = transition_layer(d) x = GlobalAveragePooling2D()(d) output = Dense(n_classes, activation = 'softmax')(x) model = Model(input, output) return modelinput_shape = 224, 224, 3n_classes = 3model = densenet(input_shape,n_classes)model.summary()
Output: (Assuming 3 final classes — last few lines of the model summary)
To view the architecture diagram, the following code can be used.
from tensorflow.python.keras.utils.vis_utils import model_to_dotfrom IPython.display import SVGimport pydotimport graphvizSVG(model_to_dot( model, show_shapes=True, show_layer_names=True, rankdir='TB', expand_nested=False, dpi=60, subgraph=False).create(prog='dot',format='svg'))
Output — first few blocks of the diagram
And that's how we can implement the DenseNet 121 architecture.
References:
1. Gao Huang and Zhuang Liu and Laurens van der Maaten and Kilian Q. Weinberger, Densely Connected Convolutional Networks, arXiv 1608.06993 (2016)
1. Gao Huang and Zhuang Liu and Laurens van der Maaten and Kilian Q. Weinberger, Densely Connected Convolutional Networks, arXiv 1608.06993 (2016)
|
[
{
"code": null,
"e": 230,
"s": 172,
"text": "DenseNet paper link: https://arxiv.org/pdf/1608.06993.pdf"
},
{
"code": null,
"e": 1529,
"s": 230,
"text": "DenseNet (Dense Convolutional Network) is an architecture that focuses on making the deep learning networks go even deeper, but at the same time making them more efficient to train, by using shorter connections between the layers. DenseNet is a convolutional neural network where each layer is connected to all other layers that are deeper in the network, that is, the first layer is connected to the 2nd, 3rd, 4th and so on, the second layer is connected to the 3rd, 4th, 5th and so on. This is done to enable maximum information flow between the layers of the network. To preserve the feed-forward nature, each layer obtains inputs from all the previous layers and passes on its own feature maps to all the layers which will come after it. Unlike Resnets it does not combine features through summation but combines the features by concatenating them. So the ‘ith’ layer has ‘i’ inputs and consists of feature maps of all its preceding convolutional blocks. Its own feature maps are passed on to all the next ‘I-i’ layers. This introduces ‘(I(I+1))/2’ connections in the network, rather than just ‘I’ connections as in traditional deep learning architectures. It hence requires fewer parameters than traditional convolutional neural networks, as there is no need to learn unimportant feature maps."
},
{
"code": null,
"e": 1679,
"s": 1529,
"text": "DenseNet consists of two important blocks other than the basic convolutional and pooling layers. they are the Dense Blocks and the Transition layers."
},
{
"code": null,
"e": 1771,
"s": 1679,
"text": "Next, we look at how all these blocks and layers look, and how to implement them in python."
},
{
"code": null,
"e": 2057,
"s": 1771,
"text": "DenseNet starts with a basic convolution and pooling layer. Then there is a dense block followed by a transition layer, another dense block followed by a transition layer, another dense block followed by a transition layer, and finally a dense block followed by a classification layer."
},
{
"code": null,
"e": 2278,
"s": 2057,
"text": "The first convolution block has 64 filters of size 7x7 and a stride of 2. It is followed by a MaxPooling layer with 3x3 max pooling and a stride of 2. These two lines can be represented with the following code in python."
},
{
"code": null,
"e": 2411,
"s": 2278,
"text": "input = Input (input_shape)x = Conv2D(64, 7, strides = 2, padding = 'same')(input)x = MaxPool2D(3, strides = 2, padding = 'same')(x)"
},
{
"code": null,
"e": 2653,
"s": 2411,
"text": "Defining the convolutional block — Each convolutional block after the input has the following sequence: BatchNormalization, followed by ReLU activation and then the actual Conv2D layer. To implement that, we can write the following function."
},
{
"code": null,
"e": 2860,
"s": 2653,
"text": "#batch norm + relu + convdef bn_rl_conv(x,filters,kernel=1,strides=1): x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters, kernel, strides=strides,padding = 'same')(x) return x"
},
{
"code": null,
"e": 3133,
"s": 2860,
"text": "Defining the Dense block — As seen in figure 3, Every dense block has two convolutions, with 1x1 and 3x3 sized kernels. In dense block 1, this is repeated 6 times, in dense block 2 it is repeated 12 times, in dense block 3, 24 times and finally in dense block 4, 16 times."
},
{
"code": null,
"e": 3336,
"s": 3133,
"text": "In dense block, each of the 1x1 convolutions has 4 times the number of filters. So we use 4*filters, but 3x3 filters are only present once. Also, we have to concatenate the input with the output tensor."
},
{
"code": null,
"e": 3421,
"s": 3336,
"text": "Each block is run for the 6,12,24,16 repetitions respectively, using the ‘for loop’."
},
{
"code": null,
"e": 3605,
"s": 3421,
"text": "def dense_block(x, repetition): for _ in range(repetition): y = bn_rl_conv(x, 4*filters) y = bn_rl_conv(y, filters, 3) x = concatenate([y,x]) return x"
},
{
"code": null,
"e": 3936,
"s": 3605,
"text": "Defining the transition layer — In the transition layer, we are to reduce the number of channels to half of the existing channels. There are a 1x1 convolutional layer and a 2x2 average pooling layer with a stride of 2. kernel size of 1x1 is already set in the function, bn_rl_conv, so we do not explicitly need to define it again."
},
{
"code": null,
"e": 4417,
"s": 3936,
"text": "In the transition layers, we have to remove channels to half of the existing channels. We have the input tensor x, and we want to find how many channels there are, and we need to get half of them. So we can use Keras backend (K) to take the tensor x and return a tuple with the dimension of x. And, we only require the last number of that shape, that is, the number of the filters. So we add [-1]. Finally, we can just divide this number of filters by 2 to get the desired result."
},
{
"code": null,
"e": 4562,
"s": 4417,
"text": "def transition_layer(x): x = bn_rl_conv(x, K.int_shape(x)[-1] //2 ) x = AvgPool2D(2, strides = 2, padding = 'same')(x) return x"
},
{
"code": null,
"e": 4904,
"s": 4562,
"text": "So we are done with defining the dense blocks and transition layers. Now we need to stack the dense blocks and transition layers together. So we write a for loop to run through the 6,12,24,16 repetitions. So the loop runs 4 times, each time using one of the values from 6,12,24 or 16. This completes the 4 dense blocks and transition layers."
},
{
"code": null,
"e": 5005,
"s": 4904,
"text": "for repetition in [6,12,24,16]: d = dense_block(x, repetition) x = transition_layer(d)"
},
{
"code": null,
"e": 5512,
"s": 5005,
"text": "In the end, there is GlobalAveragePooling, followed by the final output layer. As we see in the above code block, the dense block is defined by ‘d’, and in the final layer, after Dense block 4, there is no transition layer 4, but it directly goes into the classification layer. So, ‘d’ is the connection on which GlobalAveragePooling is applied, and not on ‘x’. Another alternative is to remove the ‘for’ loop from the code above and stack the layers one after the other without the final transition layer."
},
{
"code": null,
"e": 5596,
"s": 5512,
"text": "x = GlobalAveragePooling2D()(d)output = Dense(n_classes, activation = 'softmax')(x)"
},
{
"code": null,
"e": 5696,
"s": 5596,
"text": "Now that we have all the blocks together, let's merge them to see the entire DenseNet architecture."
},
{
"code": null,
"e": 5732,
"s": 5696,
"text": "Complete DenseNet 121 architecture:"
},
{
"code": null,
"e": 7229,
"s": 5732,
"text": "import tensorflow as tffrom tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Densefrom tensorflow.keras.layers import AvgPool2D, GlobalAveragePooling2D, MaxPool2Dfrom tensorflow.keras.models import Modelfrom tensorflow.keras.layers import ReLU, concatenateimport tensorflow.keras.backend as K# Creating Densenet121def densenet(input_shape, n_classes, filters = 32): #batch norm + relu + conv def bn_rl_conv(x,filters,kernel=1,strides=1): x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters, kernel, strides=strides,padding = 'same')(x) return x def dense_block(x, repetition): for _ in range(repetition): y = bn_rl_conv(x, 4*filters) y = bn_rl_conv(y, filters, 3) x = concatenate([y,x]) return x def transition_layer(x): x = bn_rl_conv(x, K.int_shape(x)[-1] //2 ) x = AvgPool2D(2, strides = 2, padding = 'same')(x) return x input = Input (input_shape) x = Conv2D(64, 7, strides = 2, padding = 'same')(input) x = MaxPool2D(3, strides = 2, padding = 'same')(x) for repetition in [6,12,24,16]: d = dense_block(x, repetition) x = transition_layer(d) x = GlobalAveragePooling2D()(d) output = Dense(n_classes, activation = 'softmax')(x) model = Model(input, output) return modelinput_shape = 224, 224, 3n_classes = 3model = densenet(input_shape,n_classes)model.summary()"
},
{
"code": null,
"e": 7302,
"s": 7229,
"text": "Output: (Assuming 3 final classes — last few lines of the model summary)"
},
{
"code": null,
"e": 7368,
"s": 7302,
"text": "To view the architecture diagram, the following code can be used."
},
{
"code": null,
"e": 7654,
"s": 7368,
"text": "from tensorflow.python.keras.utils.vis_utils import model_to_dotfrom IPython.display import SVGimport pydotimport graphvizSVG(model_to_dot( model, show_shapes=True, show_layer_names=True, rankdir='TB', expand_nested=False, dpi=60, subgraph=False).create(prog='dot',format='svg'))"
},
{
"code": null,
"e": 7695,
"s": 7654,
"text": "Output — first few blocks of the diagram"
},
{
"code": null,
"e": 7758,
"s": 7695,
"text": "And that's how we can implement the DenseNet 121 architecture."
},
{
"code": null,
"e": 7770,
"s": 7758,
"text": "References:"
},
{
"code": null,
"e": 7917,
"s": 7770,
"text": "1. Gao Huang and Zhuang Liu and Laurens van der Maaten and Kilian Q. Weinberger, Densely Connected Convolutional Networks, arXiv 1608.06993 (2016)"
}
] |
Private AI — Federated Learning with PySyft and PyTorch | by André Macedo Farias | Towards Data Science
|
During the last years, we all have witnessed an important and quick evolution in the fields of Artifical Intelligence and Machine Learning. This fast development is happening thanks to the improvement of computation power (made available by the last generations of GPUs and TPUs) and the enormous amount of data that has been accumulated over the years and is being created every second.
From conversational assistants to lung cancer detection, we can clearly see the several applications and various benefits of AI development for our society. However, for the past years, this progress came with a cost: loss of privacy at some degree. The Cambridge Analytica Scandal was the event that raised the alarms for concerns on confidentiality and data privacy. Furthermore, the increasing usage of data by tech companies, either small or big, led the authorities in several jurisdictions to work on regulation and laws regarding data protection and privacy. The GDPR in Europe is the most known example of such actions.
These concerns and regulations are not directly compatible with the development of AI and Machine Learning, as the models and algorithms always relied on the availability of data and the possibility to centralize it in big servers. In order to address this issue, a new field of research is getting the interest of ML researchers and practitioners: Private and Secure AI.
This new field consists of an ensemble of techniques that allow ML engineers to train models without having direct access to the data used for the training and avoid them to get any information about the data by the use of cryptography.
It seems like black magic doesn't it?
Don't worry... in a series of articles, I will show how it works and how we can apply it on our own Deep Learning models in Python with the open-source library PySyft.
This framework relies on three main techniques:
Federated Learning
Differential Privacy
Secured Multi-Party Computation
In this article, I will cover Federated Learning and its application for SMS spam detection.
Maybe the easiest to understand concept in Private AI, Federated Learning is a technique to train AI models without having to move data to a central server. The term was first used by Google in a paper published in 2016.
The main idea is that, instead of bringing the data to the model, we send the model to where the data is located.
As the data is located in several devices (which I will call workers from here) the model is sent to each worker and then sent back to the central server.
One simple example of Federated Learning in the real world happens with Apple devices. The application QuickType (Apple's text prediction tool) actually uses models that are sent time to time to iOS devices via WiFi, are trained locally with users' data and are sent back to Apple's central server with their weights updated.
PySyft is an open-source library built for Federate Learning and Privacy Preserving. It allows its users to perform private and secure Deep Learning. It is built as an extension of some DL libraries, such as PyTorch, Keras and Tensorflow.
github.com
If you are more interested you can also take a look at the paper published by OpenMined about the framework.
In this article, I will show a tutorial using the PySyft extension of PyTorch.
In order to install PySyft, it is recommended that you set up a conda environment first:
conda create -n pysyft python=3conda activate pysyft # or source activate pysyftconda install jupyter notebook
You then install the package:
pip install syft
Please be sure that you also have PyTorch 1.0.1 or higher installed in your environment.
If you have an installation error regarding zstd, try to uninstall zstd and reinstall it.
pip uninstall zstdpip install --upgrade zstd
If you are still getting errors with the setup, you can alternatively use a Colab notebook and run the following line of code:
!pip install syft
The jupyter notebook with the code below is available on my GitHub page.
github.com
In this tutorial, I will simulate two workers, Bob and Anne’s devices, where the SMS messages will be stored. With PySyft we can simulate these remote machines by using the abstraction of VirtualWorker object.
First, we hook PyTorch:
import torchimport syft as syhook = sy.TorchHook(torch)
Then, we create the VirtualWorkers:
bob = sy.VirtualWorker(hook, id="bob")anne = sy.VirtualWorker(hook, id="anne")
We can now send tensors to the workers with the method .send(worker). For example:
x = torch.Tensor([2,2,2]).send(bob)print(x)
You probably will get something like that as output:
(Wrapper)>[PointerTensor | me:79601866508 -> bob:62597613886]
You can also check where is located the tensor the pointer is pointing to:
print(x.location)
<VirtualWorker id:bob #tensors:1>
We can see that the tensor is located at a VirtualWorker called "bob" and this worker has one tensor.
Now you can do remote operations using these pointers:
y = torch.Tensor([1,2,3]).send(bob)sum = x + yprint(sum)
(Wrapper)>[PointerTensor | me:40216858934 -> bob:448194605]
You can see that after the operation we get a pointer as a return. To get the tensor back you need to use the method .get()
sum = sum.get()print(sum)
tensor([3., 4., 5.])
The most amazing thing is that we can effectuate all the operations provided by the PyTorch API on these pointers, such as compute losses, take gradients back to zero, perform backpropagation, etc.
Now that you understand the basics of VirtualWorkers and Pointers we can train our model using Federated Learning.
To simulate the remote data we will use SMS Spam Collection Data Set available on the UCI Machine Learning Repository. It consists of c. 5500 SMS messages, of which around 13% are spam messages. We will send about half of the messages to Bob's device and the other half to Anne's device.
For this project, I performed some text and data preprocessing that I will not show here, but if you are interested you can take a look at the script I used available on my GitHub page. Please also note that in a real-life case this preprocessing will be done in each user's device.
Let's load the processed data:
# Loading datainputs = np.load('./data/inputs.npy')inputs = torch.tensor(inputs)labels = np.load('./data/labels.npy')labels = torch.tensor(labels)# splitting training and test datapct_test = 0.2train_labels = labels[:-int(len(labels)*pct_test)]train_inputs = inputs[:-int(len(labels)*pct_test)]test_labels = labels[-int(len(labels)*pct_test):]test_inputs = inputs[-int(len(labels)*pct_test):]
We then split the datasets in two and send it to the workers with the class sy.BaseDataset:
When training in PyTorch, we use DataLoaders to iterate over the batches. With PySyft we can do a similar iteration with FederatedDataLoaders, where the batches come from several devices, in a federated manner.
For this task, I decided to use a classifier based on a 1-layer GRU network. Unfortunately, the current version of PySyft does not support the RNNs modules of PyTorch yet. However, I was able to handcraft a simple GRU network with linear layers, which are supported by PySyft.
As our focus here is the usage of the PySyft framework, I will skip the construction of the model. If you are interested in how I built it, you can check it out this script on my GitHub page.
Let's initiate the model!
from handcrafted_GRU import GRU# Training paramsEPOCHS = 15CLIP = 5 # gradient clipping - to avoid gradient explosion lr = 0.1BATCH_SIZE = 32# Model paramsEMBEDDING_DIM = 50HIDDEN_DIM = 10DROPOUT = 0.2# Initiating the modelmodel = GRU(vocab_size=VOCAB_SIZE, hidden_dim=HIDDEN_DIM, embedding_dim=EMBEDDING_DIM, dropout=DROPOUT)
And now train it!
Please note the lines 8, 12, 13 and 27. These are the steps that differentiate a centralised training in PyTorch from a federated training with PySyft.
After getting the model back at the end of the training loop, we can use it to evaluate its performance on local or remote test sets with a similar approach. In this case, I was able to achieve over 97.5% of AUC score, showing that training models in a federated manner does not hurt performance. However, we can notice an increase in overall time computation.
We can see that with the PySyft library and its PyTorch extension, we can perform operations with tensor pointers such as we can do with PyTorch API (but for some limitations that are still to be addressed).
Thanks to this, we were able to train a spam detector model without having any access to the remote and private data: for each batch, we sent the model to the current remote worker and got it back to the local machine before sending it to the worker of the next batch.
There is however one limitation of this method: by getting the model back we can still have access to some private information. Let’s say Bob had only one SMS on his machine. When we get the model back, we can just check which embeddings of the model changed and we will know which were the tokens (words) of the SMS.
In order to address this issue, there are two solutions: Differential Privacy and Secured Multi-Party Computation (SMPC). Differential Privacy would be used to make sure the model does not give access to some private information. SMPC, which is one kind of Encrypted Computation, in return allows you to send the model privately so that the remote workers which have the data cannot see the weights you are using.
I will show how we perform these techniques with PySyft in the next article.
Feel free to give me feedback and ask questions!
If you are interested in learning more about Secure and Private AI and how to use PySyft you can also check out this free course on Udacity. It's a great course for beginners taught by Andrew Trask, the founder of the OpenMined Initiative.
OpenMined's article about PySyft on arXiv: https://arxiv.org/pdf/1811.04017.pdf
Google's article about Federated Learning: https://arxiv.org/pdf/1602.05629.pdf
Tutorials for beginners in PySyft: https://github.com/OpenMined/PySyft/tree/dev/examples/tutorials
An Overview of Federated Learning: https://medium.com/@ODSC/an-open-framework-for-secure-and-private-ai-96c1891a4b
An Open Framework for Secure and Private AI: https://medium.com/@ODSC/an-open-framework-for-secure-and-private-ai-96c1891a4b
Federated Learning in 10 lines of PyTorch + PySyft: https://blog.openmined.org/upgrade-to-federated-learning-in-10-lines/
|
[
{
"code": null,
"e": 559,
"s": 171,
"text": "During the last years, we all have witnessed an important and quick evolution in the fields of Artifical Intelligence and Machine Learning. This fast development is happening thanks to the improvement of computation power (made available by the last generations of GPUs and TPUs) and the enormous amount of data that has been accumulated over the years and is being created every second."
},
{
"code": null,
"e": 1187,
"s": 559,
"text": "From conversational assistants to lung cancer detection, we can clearly see the several applications and various benefits of AI development for our society. However, for the past years, this progress came with a cost: loss of privacy at some degree. The Cambridge Analytica Scandal was the event that raised the alarms for concerns on confidentiality and data privacy. Furthermore, the increasing usage of data by tech companies, either small or big, led the authorities in several jurisdictions to work on regulation and laws regarding data protection and privacy. The GDPR in Europe is the most known example of such actions."
},
{
"code": null,
"e": 1559,
"s": 1187,
"text": "These concerns and regulations are not directly compatible with the development of AI and Machine Learning, as the models and algorithms always relied on the availability of data and the possibility to centralize it in big servers. In order to address this issue, a new field of research is getting the interest of ML researchers and practitioners: Private and Secure AI."
},
{
"code": null,
"e": 1796,
"s": 1559,
"text": "This new field consists of an ensemble of techniques that allow ML engineers to train models without having direct access to the data used for the training and avoid them to get any information about the data by the use of cryptography."
},
{
"code": null,
"e": 1834,
"s": 1796,
"text": "It seems like black magic doesn't it?"
},
{
"code": null,
"e": 2002,
"s": 1834,
"text": "Don't worry... in a series of articles, I will show how it works and how we can apply it on our own Deep Learning models in Python with the open-source library PySyft."
},
{
"code": null,
"e": 2050,
"s": 2002,
"text": "This framework relies on three main techniques:"
},
{
"code": null,
"e": 2069,
"s": 2050,
"text": "Federated Learning"
},
{
"code": null,
"e": 2090,
"s": 2069,
"text": "Differential Privacy"
},
{
"code": null,
"e": 2122,
"s": 2090,
"text": "Secured Multi-Party Computation"
},
{
"code": null,
"e": 2215,
"s": 2122,
"text": "In this article, I will cover Federated Learning and its application for SMS spam detection."
},
{
"code": null,
"e": 2436,
"s": 2215,
"text": "Maybe the easiest to understand concept in Private AI, Federated Learning is a technique to train AI models without having to move data to a central server. The term was first used by Google in a paper published in 2016."
},
{
"code": null,
"e": 2550,
"s": 2436,
"text": "The main idea is that, instead of bringing the data to the model, we send the model to where the data is located."
},
{
"code": null,
"e": 2705,
"s": 2550,
"text": "As the data is located in several devices (which I will call workers from here) the model is sent to each worker and then sent back to the central server."
},
{
"code": null,
"e": 3031,
"s": 2705,
"text": "One simple example of Federated Learning in the real world happens with Apple devices. The application QuickType (Apple's text prediction tool) actually uses models that are sent time to time to iOS devices via WiFi, are trained locally with users' data and are sent back to Apple's central server with their weights updated."
},
{
"code": null,
"e": 3270,
"s": 3031,
"text": "PySyft is an open-source library built for Federate Learning and Privacy Preserving. It allows its users to perform private and secure Deep Learning. It is built as an extension of some DL libraries, such as PyTorch, Keras and Tensorflow."
},
{
"code": null,
"e": 3281,
"s": 3270,
"text": "github.com"
},
{
"code": null,
"e": 3390,
"s": 3281,
"text": "If you are more interested you can also take a look at the paper published by OpenMined about the framework."
},
{
"code": null,
"e": 3469,
"s": 3390,
"text": "In this article, I will show a tutorial using the PySyft extension of PyTorch."
},
{
"code": null,
"e": 3558,
"s": 3469,
"text": "In order to install PySyft, it is recommended that you set up a conda environment first:"
},
{
"code": null,
"e": 3669,
"s": 3558,
"text": "conda create -n pysyft python=3conda activate pysyft # or source activate pysyftconda install jupyter notebook"
},
{
"code": null,
"e": 3699,
"s": 3669,
"text": "You then install the package:"
},
{
"code": null,
"e": 3716,
"s": 3699,
"text": "pip install syft"
},
{
"code": null,
"e": 3805,
"s": 3716,
"text": "Please be sure that you also have PyTorch 1.0.1 or higher installed in your environment."
},
{
"code": null,
"e": 3895,
"s": 3805,
"text": "If you have an installation error regarding zstd, try to uninstall zstd and reinstall it."
},
{
"code": null,
"e": 3940,
"s": 3895,
"text": "pip uninstall zstdpip install --upgrade zstd"
},
{
"code": null,
"e": 4067,
"s": 3940,
"text": "If you are still getting errors with the setup, you can alternatively use a Colab notebook and run the following line of code:"
},
{
"code": null,
"e": 4085,
"s": 4067,
"text": "!pip install syft"
},
{
"code": null,
"e": 4158,
"s": 4085,
"text": "The jupyter notebook with the code below is available on my GitHub page."
},
{
"code": null,
"e": 4169,
"s": 4158,
"text": "github.com"
},
{
"code": null,
"e": 4379,
"s": 4169,
"text": "In this tutorial, I will simulate two workers, Bob and Anne’s devices, where the SMS messages will be stored. With PySyft we can simulate these remote machines by using the abstraction of VirtualWorker object."
},
{
"code": null,
"e": 4403,
"s": 4379,
"text": "First, we hook PyTorch:"
},
{
"code": null,
"e": 4459,
"s": 4403,
"text": "import torchimport syft as syhook = sy.TorchHook(torch)"
},
{
"code": null,
"e": 4495,
"s": 4459,
"text": "Then, we create the VirtualWorkers:"
},
{
"code": null,
"e": 4574,
"s": 4495,
"text": "bob = sy.VirtualWorker(hook, id=\"bob\")anne = sy.VirtualWorker(hook, id=\"anne\")"
},
{
"code": null,
"e": 4657,
"s": 4574,
"text": "We can now send tensors to the workers with the method .send(worker). For example:"
},
{
"code": null,
"e": 4701,
"s": 4657,
"text": "x = torch.Tensor([2,2,2]).send(bob)print(x)"
},
{
"code": null,
"e": 4754,
"s": 4701,
"text": "You probably will get something like that as output:"
},
{
"code": null,
"e": 4816,
"s": 4754,
"text": "(Wrapper)>[PointerTensor | me:79601866508 -> bob:62597613886]"
},
{
"code": null,
"e": 4891,
"s": 4816,
"text": "You can also check where is located the tensor the pointer is pointing to:"
},
{
"code": null,
"e": 4909,
"s": 4891,
"text": "print(x.location)"
},
{
"code": null,
"e": 4943,
"s": 4909,
"text": "<VirtualWorker id:bob #tensors:1>"
},
{
"code": null,
"e": 5045,
"s": 4943,
"text": "We can see that the tensor is located at a VirtualWorker called \"bob\" and this worker has one tensor."
},
{
"code": null,
"e": 5100,
"s": 5045,
"text": "Now you can do remote operations using these pointers:"
},
{
"code": null,
"e": 5157,
"s": 5100,
"text": "y = torch.Tensor([1,2,3]).send(bob)sum = x + yprint(sum)"
},
{
"code": null,
"e": 5217,
"s": 5157,
"text": "(Wrapper)>[PointerTensor | me:40216858934 -> bob:448194605]"
},
{
"code": null,
"e": 5341,
"s": 5217,
"text": "You can see that after the operation we get a pointer as a return. To get the tensor back you need to use the method .get()"
},
{
"code": null,
"e": 5367,
"s": 5341,
"text": "sum = sum.get()print(sum)"
},
{
"code": null,
"e": 5388,
"s": 5367,
"text": "tensor([3., 4., 5.])"
},
{
"code": null,
"e": 5586,
"s": 5388,
"text": "The most amazing thing is that we can effectuate all the operations provided by the PyTorch API on these pointers, such as compute losses, take gradients back to zero, perform backpropagation, etc."
},
{
"code": null,
"e": 5701,
"s": 5586,
"text": "Now that you understand the basics of VirtualWorkers and Pointers we can train our model using Federated Learning."
},
{
"code": null,
"e": 5989,
"s": 5701,
"text": "To simulate the remote data we will use SMS Spam Collection Data Set available on the UCI Machine Learning Repository. It consists of c. 5500 SMS messages, of which around 13% are spam messages. We will send about half of the messages to Bob's device and the other half to Anne's device."
},
{
"code": null,
"e": 6272,
"s": 5989,
"text": "For this project, I performed some text and data preprocessing that I will not show here, but if you are interested you can take a look at the script I used available on my GitHub page. Please also note that in a real-life case this preprocessing will be done in each user's device."
},
{
"code": null,
"e": 6303,
"s": 6272,
"text": "Let's load the processed data:"
},
{
"code": null,
"e": 6696,
"s": 6303,
"text": "# Loading datainputs = np.load('./data/inputs.npy')inputs = torch.tensor(inputs)labels = np.load('./data/labels.npy')labels = torch.tensor(labels)# splitting training and test datapct_test = 0.2train_labels = labels[:-int(len(labels)*pct_test)]train_inputs = inputs[:-int(len(labels)*pct_test)]test_labels = labels[-int(len(labels)*pct_test):]test_inputs = inputs[-int(len(labels)*pct_test):]"
},
{
"code": null,
"e": 6788,
"s": 6696,
"text": "We then split the datasets in two and send it to the workers with the class sy.BaseDataset:"
},
{
"code": null,
"e": 6999,
"s": 6788,
"text": "When training in PyTorch, we use DataLoaders to iterate over the batches. With PySyft we can do a similar iteration with FederatedDataLoaders, where the batches come from several devices, in a federated manner."
},
{
"code": null,
"e": 7276,
"s": 6999,
"text": "For this task, I decided to use a classifier based on a 1-layer GRU network. Unfortunately, the current version of PySyft does not support the RNNs modules of PyTorch yet. However, I was able to handcraft a simple GRU network with linear layers, which are supported by PySyft."
},
{
"code": null,
"e": 7468,
"s": 7276,
"text": "As our focus here is the usage of the PySyft framework, I will skip the construction of the model. If you are interested in how I built it, you can check it out this script on my GitHub page."
},
{
"code": null,
"e": 7494,
"s": 7468,
"text": "Let's initiate the model!"
},
{
"code": null,
"e": 7821,
"s": 7494,
"text": "from handcrafted_GRU import GRU# Training paramsEPOCHS = 15CLIP = 5 # gradient clipping - to avoid gradient explosion lr = 0.1BATCH_SIZE = 32# Model paramsEMBEDDING_DIM = 50HIDDEN_DIM = 10DROPOUT = 0.2# Initiating the modelmodel = GRU(vocab_size=VOCAB_SIZE, hidden_dim=HIDDEN_DIM, embedding_dim=EMBEDDING_DIM, dropout=DROPOUT)"
},
{
"code": null,
"e": 7839,
"s": 7821,
"text": "And now train it!"
},
{
"code": null,
"e": 7991,
"s": 7839,
"text": "Please note the lines 8, 12, 13 and 27. These are the steps that differentiate a centralised training in PyTorch from a federated training with PySyft."
},
{
"code": null,
"e": 8352,
"s": 7991,
"text": "After getting the model back at the end of the training loop, we can use it to evaluate its performance on local or remote test sets with a similar approach. In this case, I was able to achieve over 97.5% of AUC score, showing that training models in a federated manner does not hurt performance. However, we can notice an increase in overall time computation."
},
{
"code": null,
"e": 8560,
"s": 8352,
"text": "We can see that with the PySyft library and its PyTorch extension, we can perform operations with tensor pointers such as we can do with PyTorch API (but for some limitations that are still to be addressed)."
},
{
"code": null,
"e": 8829,
"s": 8560,
"text": "Thanks to this, we were able to train a spam detector model without having any access to the remote and private data: for each batch, we sent the model to the current remote worker and got it back to the local machine before sending it to the worker of the next batch."
},
{
"code": null,
"e": 9147,
"s": 8829,
"text": "There is however one limitation of this method: by getting the model back we can still have access to some private information. Let’s say Bob had only one SMS on his machine. When we get the model back, we can just check which embeddings of the model changed and we will know which were the tokens (words) of the SMS."
},
{
"code": null,
"e": 9561,
"s": 9147,
"text": "In order to address this issue, there are two solutions: Differential Privacy and Secured Multi-Party Computation (SMPC). Differential Privacy would be used to make sure the model does not give access to some private information. SMPC, which is one kind of Encrypted Computation, in return allows you to send the model privately so that the remote workers which have the data cannot see the weights you are using."
},
{
"code": null,
"e": 9638,
"s": 9561,
"text": "I will show how we perform these techniques with PySyft in the next article."
},
{
"code": null,
"e": 9687,
"s": 9638,
"text": "Feel free to give me feedback and ask questions!"
},
{
"code": null,
"e": 9927,
"s": 9687,
"text": "If you are interested in learning more about Secure and Private AI and how to use PySyft you can also check out this free course on Udacity. It's a great course for beginners taught by Andrew Trask, the founder of the OpenMined Initiative."
},
{
"code": null,
"e": 10007,
"s": 9927,
"text": "OpenMined's article about PySyft on arXiv: https://arxiv.org/pdf/1811.04017.pdf"
},
{
"code": null,
"e": 10087,
"s": 10007,
"text": "Google's article about Federated Learning: https://arxiv.org/pdf/1602.05629.pdf"
},
{
"code": null,
"e": 10186,
"s": 10087,
"text": "Tutorials for beginners in PySyft: https://github.com/OpenMined/PySyft/tree/dev/examples/tutorials"
},
{
"code": null,
"e": 10301,
"s": 10186,
"text": "An Overview of Federated Learning: https://medium.com/@ODSC/an-open-framework-for-secure-and-private-ai-96c1891a4b"
},
{
"code": null,
"e": 10426,
"s": 10301,
"text": "An Open Framework for Secure and Private AI: https://medium.com/@ODSC/an-open-framework-for-secure-and-private-ai-96c1891a4b"
}
] |
Python Program for Counting Sort - GeeksforGeeks
|
22 Jan, 2022
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.
Python3
# Python program for counting sort # The main function that sort the given string arr[] in# alphabetical orderdef countSort(arr): # The output character array that will have sorted arr output = [0 for i in range(256)] # Create a count array to store count of individual # characters and initialize count array as 0 count = [0 for i in range(256)] # For storing the resulting answer since the # string is immutable ans = ["" for _ in arr] # Store count of each character for i in arr: count[ord(i)] += 1 # Change count[i] so that count[i] now contains actual # position of this character in output array for i in range(256): count[i] += count[i-1] # Build the output character array for i in range(len(arr)): output[count[ord(arr[i])]-1] = arr[i] count[ord(arr[i])] -= 1 # Copy the output array to arr, so that arr now # contains sorted characters for i in range(len(arr)): ans[i] = output[i] return ans # Driver program to test above functionarr = "geeksforgeeks"ans = countSort(arr)print ("Sorted character array is %s" %("".join(ans))) # This code is contributed by Nikhil Kumar Singh
Output:
Sorted character array is eeeefggkkorss
Please refer complete article on Counting Sort for more details!
simmytarika5
amartyaghoshgfg
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python Program for Binary Search (Recursive and Iterative)
Iterate over characters of a string in Python
Python program to add two numbers
Python Program for factorial of a number
Python Program for Bubble Sort
Python | Convert set into a list
|
[
{
"code": null,
"e": 23605,
"s": 23577,
"text": "\n22 Jan, 2022"
},
{
"code": null,
"e": 23864,
"s": 23605,
"text": "Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. "
},
{
"code": null,
"e": 23872,
"s": 23864,
"text": "Python3"
},
{
"code": "# Python program for counting sort # The main function that sort the given string arr[] in# alphabetical orderdef countSort(arr): # The output character array that will have sorted arr output = [0 for i in range(256)] # Create a count array to store count of individual # characters and initialize count array as 0 count = [0 for i in range(256)] # For storing the resulting answer since the # string is immutable ans = [\"\" for _ in arr] # Store count of each character for i in arr: count[ord(i)] += 1 # Change count[i] so that count[i] now contains actual # position of this character in output array for i in range(256): count[i] += count[i-1] # Build the output character array for i in range(len(arr)): output[count[ord(arr[i])]-1] = arr[i] count[ord(arr[i])] -= 1 # Copy the output array to arr, so that arr now # contains sorted characters for i in range(len(arr)): ans[i] = output[i] return ans # Driver program to test above functionarr = \"geeksforgeeks\"ans = countSort(arr)print (\"Sorted character array is %s\" %(\"\".join(ans))) # This code is contributed by Nikhil Kumar Singh",
"e": 25059,
"s": 23872,
"text": null
},
{
"code": null,
"e": 25068,
"s": 25059,
"text": "Output: "
},
{
"code": null,
"e": 25108,
"s": 25068,
"text": "Sorted character array is eeeefggkkorss"
},
{
"code": null,
"e": 25174,
"s": 25108,
"text": "Please refer complete article on Counting Sort for more details! "
},
{
"code": null,
"e": 25187,
"s": 25174,
"text": "simmytarika5"
},
{
"code": null,
"e": 25203,
"s": 25187,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 25219,
"s": 25203,
"text": "Python Programs"
},
{
"code": null,
"e": 25317,
"s": 25219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25326,
"s": 25317,
"text": "Comments"
},
{
"code": null,
"e": 25339,
"s": 25326,
"text": "Old Comments"
},
{
"code": null,
"e": 25378,
"s": 25339,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25416,
"s": 25378,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 25453,
"s": 25416,
"text": "Python Program for Fibonacci numbers"
},
{
"code": null,
"e": 25502,
"s": 25453,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 25561,
"s": 25502,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 25607,
"s": 25561,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 25641,
"s": 25607,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 25682,
"s": 25641,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 25713,
"s": 25682,
"text": "Python Program for Bubble Sort"
}
] |
Loop through a HashMap using an Iterator in Java
|
An Iterator can be used to loop through a HashMap. The method hasNext( ) returns true if there are more elements in HashMap and false otherwise. The method next( ) returns the next key element in the HashMap and throws the exception NoSuchElementException if there is no next element.
A program that demonstrates this is given as follows.
Live Demo
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Demo {
public static void main(String[] args) {
Map student = new HashMap();
student.put("101", "Harry");
student.put("102", "Amy");
student.put("103", "John");
student.put("104", "Susan");
student.put("105", "James");
Iterator i = student.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
System.out.println("\nRoll Number: " + key);
System.out.println("Name: " + student.get(key));
}
}
}
The output of the above program is as follows −
Roll Number: 101
Name: Harry
Roll Number: 102
Name: Amy
Roll Number: 103
Name: John
Roll Number: 104
Name: Susan
Roll Number: 105
Name: James
Now let us understand the above program.
The HashMap is created and HashMap.put() is used to add the entries to the HashMap. Then the HashMap entries i.e. the keys and the values are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows
Map student = new HashMap();
student.put("101", "Harry");
student.put("102", "Amy");
student.put("103", "John");
student.put("104", "Susan");
student.put("105", "James");
Iterator i = student.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
System.out.println("\nRoll Number: " + key);
System.out.println("Name: " + student.get(key));
}
|
[
{
"code": null,
"e": 1347,
"s": 1062,
"text": "An Iterator can be used to loop through a HashMap. The method hasNext( ) returns true if there are more elements in HashMap and false otherwise. The method next( ) returns the next key element in the HashMap and throws the exception NoSuchElementException if there is no next element."
},
{
"code": null,
"e": 1401,
"s": 1347,
"text": "A program that demonstrates this is given as follows."
},
{
"code": null,
"e": 1412,
"s": 1401,
"text": " Live Demo"
},
{
"code": null,
"e": 2002,
"s": 1412,
"text": "import java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\npublic class Demo {\n public static void main(String[] args) {\n Map student = new HashMap();\n student.put(\"101\", \"Harry\");\n student.put(\"102\", \"Amy\");\n student.put(\"103\", \"John\");\n student.put(\"104\", \"Susan\");\n student.put(\"105\", \"James\");\n Iterator i = student.keySet().iterator();\n while (i.hasNext()) {\n String key = (String) i.next();\n System.out.println(\"\\nRoll Number: \" + key);\n System.out.println(\"Name: \" + student.get(key));\n }\n }\n}"
},
{
"code": null,
"e": 2050,
"s": 2002,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 2196,
"s": 2050,
"text": "Roll Number: 101\nName: Harry\n\nRoll Number: 102\nName: Amy\n\nRoll Number: 103\nName: John\n\nRoll Number: 104\nName: Susan\n\nRoll Number: 105\nName: James"
},
{
"code": null,
"e": 2237,
"s": 2196,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2503,
"s": 2237,
"text": "The HashMap is created and HashMap.put() is used to add the entries to the HashMap. Then the HashMap entries i.e. the keys and the values are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows"
},
{
"code": null,
"e": 2875,
"s": 2503,
"text": "Map student = new HashMap();\nstudent.put(\"101\", \"Harry\");\nstudent.put(\"102\", \"Amy\");\nstudent.put(\"103\", \"John\");\nstudent.put(\"104\", \"Susan\");\nstudent.put(\"105\", \"James\");\nIterator i = student.keySet().iterator();\nwhile (i.hasNext()) {\n String key = (String) i.next();\n System.out.println(\"\\nRoll Number: \" + key);\n System.out.println(\"Name: \" + student.get(key));\n}"
}
] |
Create An Infographic Using Matplotlib | by Jun | Towards Data Science
|
From my previous posts about the hierarchical structure of matplotlib plotting and the many ways to instantiate axes, we can see that these features render matplotlib a great potential for creating highly complex and customisable visualisations. To demonstrate this and also improve my own understanding of matplotlib, I set out to make an infographic using matplotlib this week.
An infographic generally combines visual imagery, data charts, and minimal text together. It aims to illustrate an easy-to-understand overview of a topic. Owing to this nature, its layout and content are more complicated and diverse compared to a regular static data plot, which normally exhibits one type of data in one type of plot (e.g. bar, scatter, line, and box plot or their variants). Furthermore, an infographic can be a stand-alone plot while a regular static data plot mainly serves as supplementary material and should be read within a certain context.
As you might already see the finished infographic from the heading figure, which shows the yearly patterns of daily maximum temperature and precipitation across eight Australian major cities in 2019 (I really hope you could get its topic before reading this paragraph. This makes me feel confident to proceed). My infographic was inspired by this infographic from South China Morning Post.
I personally really like to visualise large quantities of data in a grid-like structure. When the colours and shapes are set appropriately (e.g. brick red for high temperature and arctic ice blue for low temperature in my case), it starts to convey the patterns underlaid the intricacies (e.g. less arctic ice blue as latitude decreasing), while also delivers an artistic feeling (e.g. the appearance of a bunch of red bars looks like burning wood).
Alright, without further ado, let’s now dive into the code and show you how I created this infographic using matplotlib. As usual, you can access all the required data and the jupyter notebook from my Github.
Although this is not within the scope of this post, I list this section to highlight that it is the fundamental part of making an effective infographic. Only if you know what story to tell, you have a direction for gathering data and thinking about design, layout, charts, and aesthetics. As for our case, weather data was downloaded from the Australian Bureau of Meteorology website. We only need daily maximum temperature, city name and date values (i.e. max_tmp_day, City, and Date as shown in Figure 1).
As stated in my previous post, fig.add_axes([left, bottom, width, height]) is a good way to manually place axes on fig. However, it is tedious to accurately calculate coordinates for each axes on the fig when we have lots of axes (we have 18 axes in total) and alignment is required (Our eyes are very picky, even slight misalignments will throw things off balance). I hence adopted a mixture of common layout and arbitrary layout of axes on fig. using fig.add_gridspec() and fig.add_axes(). Here, fig.add_gridspec() is a function that enable us to specify the geometry of the grid that a axes will be placed. For example, imagine a 2 rows by 2 columns grid on a fig, normally if we use fig.subplots(nrows=2, ncols=2), this will generate four axes that distributed evenly on the 2 by 2 grid. What if, on the 2 by 2 grid, we only need 3 axes that the first axes occupies the whole first row and the remaining 2 axes occupy the second row evenly? The power of fig.add_gridspec() comes in here, which enable us to create axes spanned rows and columns as desired. We can achieve the aforementioned layout as follow:
fig = plt.figure()# Use GridSpec for customising layoutgs = fig.add_gridspec(nrows=2, ncols=2)# Add an empty axes that occupied the whole first rowax1 = fig.add_subplot(gs[0, 0:2])# Add two empty axes that occupied the remaining gridax2 = fig.add_subplot(gs[1, 0])ax3 = fig.add_subplot(gs[1, 1])
As you can see, once a grid space object (i.e. gs) is created, we can make use of its grid geometry, just like access values from a 2D numpy.ndarray, to place axes accordingly. For instance, fig.add_subplot(gs[0, 0:2]) denotes add an axes occupied the whole first row in the 2 by 2 grid.
Back to the infographic, as shown in the above code, except for ax2 (the axes for the colour bar), all other axes were added by fig.add_gridspec(nrows=10, ncols=10). Specifically, on a 10 rows by 10 columns grid (Figure 2), ax1, which is the axes for the title, text and notes, occupies the first 2 rows and 8 columns. Each axes from ax3 to ax10, which are the axes for plotting temperature bar, occupies 1 row and 8 columns. Finally, each axes from ax11 to ax18, which are axes for rainfall data, occupies only 1 row and 2 columns.
As you can see, fig.add_gridspec() is a powerful function when flexibility and alignment of multiple axes are both required.
After the layout is confirmed, we can then add data plots. Here, take the temperature bar as an example (Figure 3).
Considering both information and aesthetics, each bar represents the difference between daily maximum temperature and the yearly average temperature of these eight major cities (24.43oC) in Celsius degree. By doing so, the audience can clearly identify days with above-average temperature (bars upward) and below-average temperature (bars downward). Otherwise, since temperature values are positive, all bars will toward the same direction above zero, which makes the bar plot boring. In addition, unlike a regular bar plot, I removed all grids, x-axis and y-axis and only left essential parts.
Another additive is the text annotation with curved arrows to point out days with highest and lowest temperature individually. This add agility to the whole infographic in terms of aesthetics. This was delivered by ax.annotate(). The official document about ax.annotate() gives very detailed examples, so I will not repeat the introduction of this function in this post.
Since the style of temperature bar plots need to be consistent for all these eight cities, we just need to come up codes for one plot and add others by a for loop (see code below).
Although colour scheme is a very subjective decision, I can share the principles I followed here: creating contrast, grouping elements, and encoding quantity. In this infographic, I used a dark background to make the temperature bar plot and rainfall circles visually salient. The dark background also expressed a cheerless atmosphere to reflect the emergency of extreme weather. In addition, the use of consistent colours for bar plot and rainfall circles, respectively, helped to group information together. Finally, the application of a colour spectral (from arctic ice blue to brick red) for different temperature values highlighted the patterns.
The reason that an infographic can be a stand-alone plot is that necessary text helps to reinforce its topic. Here we can use ax.text() to put whatever text wherever we want on the fig. The only pitfall I found is that it is a bit troublesome to add a custom font family to matplotlib (one solution here). An alternative is to add text via Illustrator once the main body of infographic is finished and export as svg file.
As always, I welcome feedback, constructive criticism, and hearing about your data science projects. I can be reached on Linkedin, and also on my website.
|
[
{
"code": null,
"e": 427,
"s": 47,
"text": "From my previous posts about the hierarchical structure of matplotlib plotting and the many ways to instantiate axes, we can see that these features render matplotlib a great potential for creating highly complex and customisable visualisations. To demonstrate this and also improve my own understanding of matplotlib, I set out to make an infographic using matplotlib this week."
},
{
"code": null,
"e": 992,
"s": 427,
"text": "An infographic generally combines visual imagery, data charts, and minimal text together. It aims to illustrate an easy-to-understand overview of a topic. Owing to this nature, its layout and content are more complicated and diverse compared to a regular static data plot, which normally exhibits one type of data in one type of plot (e.g. bar, scatter, line, and box plot or their variants). Furthermore, an infographic can be a stand-alone plot while a regular static data plot mainly serves as supplementary material and should be read within a certain context."
},
{
"code": null,
"e": 1382,
"s": 992,
"text": "As you might already see the finished infographic from the heading figure, which shows the yearly patterns of daily maximum temperature and precipitation across eight Australian major cities in 2019 (I really hope you could get its topic before reading this paragraph. This makes me feel confident to proceed). My infographic was inspired by this infographic from South China Morning Post."
},
{
"code": null,
"e": 1832,
"s": 1382,
"text": "I personally really like to visualise large quantities of data in a grid-like structure. When the colours and shapes are set appropriately (e.g. brick red for high temperature and arctic ice blue for low temperature in my case), it starts to convey the patterns underlaid the intricacies (e.g. less arctic ice blue as latitude decreasing), while also delivers an artistic feeling (e.g. the appearance of a bunch of red bars looks like burning wood)."
},
{
"code": null,
"e": 2041,
"s": 1832,
"text": "Alright, without further ado, let’s now dive into the code and show you how I created this infographic using matplotlib. As usual, you can access all the required data and the jupyter notebook from my Github."
},
{
"code": null,
"e": 2549,
"s": 2041,
"text": "Although this is not within the scope of this post, I list this section to highlight that it is the fundamental part of making an effective infographic. Only if you know what story to tell, you have a direction for gathering data and thinking about design, layout, charts, and aesthetics. As for our case, weather data was downloaded from the Australian Bureau of Meteorology website. We only need daily maximum temperature, city name and date values (i.e. max_tmp_day, City, and Date as shown in Figure 1)."
},
{
"code": null,
"e": 3661,
"s": 2549,
"text": "As stated in my previous post, fig.add_axes([left, bottom, width, height]) is a good way to manually place axes on fig. However, it is tedious to accurately calculate coordinates for each axes on the fig when we have lots of axes (we have 18 axes in total) and alignment is required (Our eyes are very picky, even slight misalignments will throw things off balance). I hence adopted a mixture of common layout and arbitrary layout of axes on fig. using fig.add_gridspec() and fig.add_axes(). Here, fig.add_gridspec() is a function that enable us to specify the geometry of the grid that a axes will be placed. For example, imagine a 2 rows by 2 columns grid on a fig, normally if we use fig.subplots(nrows=2, ncols=2), this will generate four axes that distributed evenly on the 2 by 2 grid. What if, on the 2 by 2 grid, we only need 3 axes that the first axes occupies the whole first row and the remaining 2 axes occupy the second row evenly? The power of fig.add_gridspec() comes in here, which enable us to create axes spanned rows and columns as desired. We can achieve the aforementioned layout as follow:"
},
{
"code": null,
"e": 3957,
"s": 3661,
"text": "fig = plt.figure()# Use GridSpec for customising layoutgs = fig.add_gridspec(nrows=2, ncols=2)# Add an empty axes that occupied the whole first rowax1 = fig.add_subplot(gs[0, 0:2])# Add two empty axes that occupied the remaining gridax2 = fig.add_subplot(gs[1, 0])ax3 = fig.add_subplot(gs[1, 1])"
},
{
"code": null,
"e": 4245,
"s": 3957,
"text": "As you can see, once a grid space object (i.e. gs) is created, we can make use of its grid geometry, just like access values from a 2D numpy.ndarray, to place axes accordingly. For instance, fig.add_subplot(gs[0, 0:2]) denotes add an axes occupied the whole first row in the 2 by 2 grid."
},
{
"code": null,
"e": 4778,
"s": 4245,
"text": "Back to the infographic, as shown in the above code, except for ax2 (the axes for the colour bar), all other axes were added by fig.add_gridspec(nrows=10, ncols=10). Specifically, on a 10 rows by 10 columns grid (Figure 2), ax1, which is the axes for the title, text and notes, occupies the first 2 rows and 8 columns. Each axes from ax3 to ax10, which are the axes for plotting temperature bar, occupies 1 row and 8 columns. Finally, each axes from ax11 to ax18, which are axes for rainfall data, occupies only 1 row and 2 columns."
},
{
"code": null,
"e": 4903,
"s": 4778,
"text": "As you can see, fig.add_gridspec() is a powerful function when flexibility and alignment of multiple axes are both required."
},
{
"code": null,
"e": 5019,
"s": 4903,
"text": "After the layout is confirmed, we can then add data plots. Here, take the temperature bar as an example (Figure 3)."
},
{
"code": null,
"e": 5614,
"s": 5019,
"text": "Considering both information and aesthetics, each bar represents the difference between daily maximum temperature and the yearly average temperature of these eight major cities (24.43oC) in Celsius degree. By doing so, the audience can clearly identify days with above-average temperature (bars upward) and below-average temperature (bars downward). Otherwise, since temperature values are positive, all bars will toward the same direction above zero, which makes the bar plot boring. In addition, unlike a regular bar plot, I removed all grids, x-axis and y-axis and only left essential parts."
},
{
"code": null,
"e": 5985,
"s": 5614,
"text": "Another additive is the text annotation with curved arrows to point out days with highest and lowest temperature individually. This add agility to the whole infographic in terms of aesthetics. This was delivered by ax.annotate(). The official document about ax.annotate() gives very detailed examples, so I will not repeat the introduction of this function in this post."
},
{
"code": null,
"e": 6166,
"s": 5985,
"text": "Since the style of temperature bar plots need to be consistent for all these eight cities, we just need to come up codes for one plot and add others by a for loop (see code below)."
},
{
"code": null,
"e": 6817,
"s": 6166,
"text": "Although colour scheme is a very subjective decision, I can share the principles I followed here: creating contrast, grouping elements, and encoding quantity. In this infographic, I used a dark background to make the temperature bar plot and rainfall circles visually salient. The dark background also expressed a cheerless atmosphere to reflect the emergency of extreme weather. In addition, the use of consistent colours for bar plot and rainfall circles, respectively, helped to group information together. Finally, the application of a colour spectral (from arctic ice blue to brick red) for different temperature values highlighted the patterns."
},
{
"code": null,
"e": 7239,
"s": 6817,
"text": "The reason that an infographic can be a stand-alone plot is that necessary text helps to reinforce its topic. Here we can use ax.text() to put whatever text wherever we want on the fig. The only pitfall I found is that it is a bit troublesome to add a custom font family to matplotlib (one solution here). An alternative is to add text via Illustrator once the main body of infographic is finished and export as svg file."
}
] |
How to give Matplolib imshow plot colorbars a label?
|
To give matplotlib imshow() plot colorbars a label, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create 5×5 data points using Numpy.
Create 5×5 data points using Numpy.
Use imshow() method to display the data as an image, i.e., on a 2D regular raster.
Use imshow() method to display the data as an image, i.e., on a 2D regular raster.
Create a colorbar for a ScalarMappable instance, im.
Create a colorbar for a ScalarMappable instance, im.
Set colorbar label using set_label() method.
Set colorbar label using set_label() method.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(5, 5)
im = plt.imshow(data, cmap="copper")
cbar = plt.colorbar(im)
cbar.set_label("Colorbar")
plt.show()
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To give matplotlib imshow() plot colorbars a label, we can take the following steps −"
},
{
"code": null,
"e": 1224,
"s": 1148,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1300,
"s": 1224,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1336,
"s": 1300,
"text": "Create 5×5 data points using Numpy."
},
{
"code": null,
"e": 1372,
"s": 1336,
"text": "Create 5×5 data points using Numpy."
},
{
"code": null,
"e": 1455,
"s": 1372,
"text": "Use imshow() method to display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1538,
"s": 1455,
"text": "Use imshow() method to display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1591,
"s": 1538,
"text": "Create a colorbar for a ScalarMappable instance, im."
},
{
"code": null,
"e": 1644,
"s": 1591,
"text": "Create a colorbar for a ScalarMappable instance, im."
},
{
"code": null,
"e": 1689,
"s": 1644,
"text": "Set colorbar label using set_label() method."
},
{
"code": null,
"e": 1734,
"s": 1689,
"text": "Set colorbar label using set_label() method."
},
{
"code": null,
"e": 1776,
"s": 1734,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1818,
"s": 1776,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2093,
"s": 1818,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = np.random.rand(5, 5)\n\nim = plt.imshow(data, cmap=\"copper\")\n\ncbar = plt.colorbar(im)\ncbar.set_label(\"Colorbar\")\n\nplt.show()"
}
] |
Convert.ToChar Method in C#
|
The Convert.ToChar method is used to convert a specified value to a Unicode integer.
We have declared an sbyte variable.
sbyte byteVal = 200;
Now, use the Convert.ToChar() method to convert the sbyte value to a Unicode integer.
charVal = Convert.ToChar(b);
Let us see another example.
Live Demo
using System;
public class Demo {
public static void Main() {
sbyte[] byteVal = { 92, 111, 115 };
char charVal;
foreach (sbyte b in byteVal) {
charVal = Convert.ToChar(b);
Console.WriteLine("{0} converted to '{1}'", b, charVal);
}
}
}
92 converted to '\'
111 converted to 'o'
115 converted to 's'
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "The Convert.ToChar method is used to convert a specified value to a Unicode integer."
},
{
"code": null,
"e": 1183,
"s": 1147,
"text": "We have declared an sbyte variable."
},
{
"code": null,
"e": 1204,
"s": 1183,
"text": "sbyte byteVal = 200;"
},
{
"code": null,
"e": 1290,
"s": 1204,
"text": "Now, use the Convert.ToChar() method to convert the sbyte value to a Unicode integer."
},
{
"code": null,
"e": 1319,
"s": 1290,
"text": "charVal = Convert.ToChar(b);"
},
{
"code": null,
"e": 1347,
"s": 1319,
"text": "Let us see another example."
},
{
"code": null,
"e": 1358,
"s": 1347,
"text": " Live Demo"
},
{
"code": null,
"e": 1641,
"s": 1358,
"text": "using System;\npublic class Demo {\n public static void Main() {\n sbyte[] byteVal = { 92, 111, 115 };\n char charVal;\n foreach (sbyte b in byteVal) {\n charVal = Convert.ToChar(b);\n Console.WriteLine(\"{0} converted to '{1}'\", b, charVal);\n }\n }\n}"
},
{
"code": null,
"e": 1703,
"s": 1641,
"text": "92 converted to '\\'\n111 converted to 'o'\n115 converted to 's'"
}
] |
How to declare a 2D array dynamically in C++ using new operator - GeeksforGeeks
|
13 Apr, 2021
Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays:
Syntax of a Multidimensional Array:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array. Here data_type is valid C/C++ data typearray_name: Name of the arraysize1, size2, ..., sizeN: Sizes of the dimensions
2D arrays are arrays of single-dimensional arrays.
Syntax of a 2D array:
data_type array_name[x][y];data_type: Type of data to be stored. Valid C/C++ data type.
Below is the diagrammatic representation of 2D arrays:
For more details on multidimensional and 2D arrays, please refer to Multidimensional arrays in C++ article.
Problem: Given a 2D array, the task is to dynamically allocate memory for a 2D array using new in C++.
Solution: Following 2D array is declared with 3 rows and 4 columns with the following values:
1 2 3 4
5 6 7 8
9 10 11 12
Note: Here M is the number of rows and N is the number of columns.
Method 1: using a single pointer – In this method, a memory block of size M*N is allocated and then the memory blocks are accessed using pointer arithmetic. Below is the program for the same:
C++
// C++ program to dynamically allocate// the memory for 2D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the 2D array int m = 3, n = 4, c = 0; // Declare a memory block of // size m*n int* arr = new int[m * n]; // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Assign values to // the memory block *(arr + i * n + j) = ++c; } } // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Print values of the // memory block cout << *(arr + i * n + j) << " "; } cout << endl; } //Delete the array created delete[] arr; return 0;}
1 2 3 4
5 6 7 8
9 10 11 12
Method 2: using an array of pointer: Here an array of pointers is created and then to each memory block. Below is the diagram to illustrate the concept:
Below is the program for the same:
C++
// C++ program to dynamically allocate// the memory for 3D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the array int m = 3, n = 4, c = 0; // Declare memory block of size M int** a = new int*[m]; for (int i = 0; i < m; i++) { // Declare a memory block // of size n a[i] = new int[n]; } // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Assign values to the // memory blocks created a[i][j] = ++c; } } // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Print the values of // memory blocks created cout << a[i][j] << " "; } cout << endl; } //Delete the array created for(int i=0;i<m;i++) //To delete the inner arrays delete [] a[i]; delete [] a; //To delete the outer array //which contained the pointers //of all the inner arrays return 0;}
1 2 3 4
5 6 7 8
9 10 11 12
random604naseeb
C++-new and delete
cpp-pointer
Pointers
Technical Scripter 2020
Arrays
C++
Technical Scripter
Arrays
Pointers
CPP
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
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
Inheritance in C++
|
[
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 24672,
"s": 24431,
"text": "Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays:"
},
{
"code": null,
"e": 24708,
"s": 24672,
"text": "Syntax of a Multidimensional Array:"
},
{
"code": null,
"e": 24755,
"s": 24708,
"text": "data_type array_name[size1][size2]....[sizeN];"
},
{
"code": null,
"e": 24924,
"s": 24755,
"text": "data_type: Type of data to be stored in the array. Here data_type is valid C/C++ data typearray_name: Name of the arraysize1, size2, ..., sizeN: Sizes of the dimensions"
},
{
"code": null,
"e": 24975,
"s": 24924,
"text": "2D arrays are arrays of single-dimensional arrays."
},
{
"code": null,
"e": 24997,
"s": 24975,
"text": "Syntax of a 2D array:"
},
{
"code": null,
"e": 25085,
"s": 24997,
"text": "data_type array_name[x][y];data_type: Type of data to be stored. Valid C/C++ data type."
},
{
"code": null,
"e": 25140,
"s": 25085,
"text": "Below is the diagrammatic representation of 2D arrays:"
},
{
"code": null,
"e": 25248,
"s": 25140,
"text": "For more details on multidimensional and 2D arrays, please refer to Multidimensional arrays in C++ article."
},
{
"code": null,
"e": 25351,
"s": 25248,
"text": "Problem: Given a 2D array, the task is to dynamically allocate memory for a 2D array using new in C++."
},
{
"code": null,
"e": 25445,
"s": 25351,
"text": "Solution: Following 2D array is declared with 3 rows and 4 columns with the following values:"
},
{
"code": null,
"e": 25472,
"s": 25445,
"text": "1 2 3 4\n5 6 7 8\n9 10 11 12"
},
{
"code": null,
"e": 25539,
"s": 25472,
"text": "Note: Here M is the number of rows and N is the number of columns."
},
{
"code": null,
"e": 25731,
"s": 25539,
"text": "Method 1: using a single pointer – In this method, a memory block of size M*N is allocated and then the memory blocks are accessed using pointer arithmetic. Below is the program for the same:"
},
{
"code": null,
"e": 25735,
"s": 25731,
"text": "C++"
},
{
"code": "// C++ program to dynamically allocate// the memory for 2D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the 2D array int m = 3, n = 4, c = 0; // Declare a memory block of // size m*n int* arr = new int[m * n]; // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Assign values to // the memory block *(arr + i * n + j) = ++c; } } // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Print values of the // memory block cout << *(arr + i * n + j) << \" \"; } cout << endl; } //Delete the array created delete[] arr; return 0;}",
"e": 26572,
"s": 25735,
"text": null
},
{
"code": null,
"e": 26604,
"s": 26575,
"text": "1 2 3 4 \n5 6 7 8 \n9 10 11 12"
},
{
"code": null,
"e": 26761,
"s": 26608,
"text": "Method 2: using an array of pointer: Here an array of pointers is created and then to each memory block. Below is the diagram to illustrate the concept:"
},
{
"code": null,
"e": 26800,
"s": 26765,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 26806,
"s": 26802,
"text": "C++"
},
{
"code": "// C++ program to dynamically allocate// the memory for 3D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the array int m = 3, n = 4, c = 0; // Declare memory block of size M int** a = new int*[m]; for (int i = 0; i < m; i++) { // Declare a memory block // of size n a[i] = new int[n]; } // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Assign values to the // memory blocks created a[i][j] = ++c; } } // Traverse the 2D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Print the values of // memory blocks created cout << a[i][j] << \" \"; } cout << endl; } //Delete the array created for(int i=0;i<m;i++) //To delete the inner arrays delete [] a[i]; delete [] a; //To delete the outer array //which contained the pointers //of all the inner arrays return 0;}",
"e": 27968,
"s": 26806,
"text": null
},
{
"code": null,
"e": 28000,
"s": 27971,
"text": "1 2 3 4 \n5 6 7 8 \n9 10 11 12"
},
{
"code": null,
"e": 28020,
"s": 28004,
"text": "random604naseeb"
},
{
"code": null,
"e": 28039,
"s": 28020,
"text": "C++-new and delete"
},
{
"code": null,
"e": 28051,
"s": 28039,
"text": "cpp-pointer"
},
{
"code": null,
"e": 28060,
"s": 28051,
"text": "Pointers"
},
{
"code": null,
"e": 28084,
"s": 28060,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28091,
"s": 28084,
"text": "Arrays"
},
{
"code": null,
"e": 28095,
"s": 28091,
"text": "C++"
},
{
"code": null,
"e": 28114,
"s": 28095,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28121,
"s": 28114,
"text": "Arrays"
},
{
"code": null,
"e": 28130,
"s": 28121,
"text": "Pointers"
},
{
"code": null,
"e": 28134,
"s": 28130,
"text": "CPP"
},
{
"code": null,
"e": 28232,
"s": 28134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28241,
"s": 28232,
"text": "Comments"
},
{
"code": null,
"e": 28254,
"s": 28241,
"text": "Old Comments"
},
{
"code": null,
"e": 28275,
"s": 28254,
"text": "Next Greater Element"
},
{
"code": null,
"e": 28300,
"s": 28275,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28327,
"s": 28300,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 28376,
"s": 28327,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28414,
"s": 28376,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28432,
"s": 28414,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28478,
"s": 28432,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28521,
"s": 28478,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28544,
"s": 28521,
"text": "std::sort() in C++ STL"
}
] |
How to Install Pytorch on MacOS? - GeeksforGeeks
|
08 Sep, 2021
PyTorch is an open-source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing, primarily developed by Facebook’s AI Research lab. It is free and open-source software released under the Modified BSD license.
Python
Python-pip or Anaconda-conda should be installed.
Step 1: Check if python3 is already installed by entering the following command in the command prompt.
python3 --version
If this command runs successfully, and we are able to get a Python version 3.9+ then we are good to go or else install python3 by referring to this article here.
Step 2: Check if pip3 is already installed by entering the following command in the command prompt.
pip3 --version
If this command runs successfully, and we are able to get a pip version then we are good to go or else install pip by referring to this article here.
Step 3: Enter the following command to install the latest stable release of Pytorch.
1. Compute Platform: CPU
pip3 install torch torchvision torchaudio
Step 4: Check if Pytorch is successfully installed by entering the following command in the command prompt.
pip3 show torch
If this command runs successfully, and we are able to get a torch version then we are good to go or else reinstall it.
Step 1: Activate Anaconda prompt if it is deactivated.
conda activate
Step 2: Check if conda is installed by entering the following command in Anaconda Prompt.
conda --version
If this command runs successfully, and we are able to get a conda version then we are good to go or else install Anaconda on MacOS.
Step 3: Enter the following commands to install the latest stable release of Pytorch.
1. Compute Platform : CPU
conda install pytorch torchvision torchaudio -c pytorch
Step 4: Check if Pytorch is successfully installed by entering the following command in Anaconda prompt.
conda list -f pytorch
If this command runs successfully, and we are able to get a torch version then we are good to go or else reinstall it.
RajuKumar19
how-to-install
Picked
Python-PyTorch
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 24847,
"s": 24561,
"text": "PyTorch is an open-source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing, primarily developed by Facebook’s AI Research lab. It is free and open-source software released under the Modified BSD license."
},
{
"code": null,
"e": 24854,
"s": 24847,
"text": "Python"
},
{
"code": null,
"e": 24904,
"s": 24854,
"text": "Python-pip or Anaconda-conda should be installed."
},
{
"code": null,
"e": 25007,
"s": 24904,
"text": "Step 1: Check if python3 is already installed by entering the following command in the command prompt."
},
{
"code": null,
"e": 25025,
"s": 25007,
"text": "python3 --version"
},
{
"code": null,
"e": 25187,
"s": 25025,
"text": "If this command runs successfully, and we are able to get a Python version 3.9+ then we are good to go or else install python3 by referring to this article here."
},
{
"code": null,
"e": 25287,
"s": 25187,
"text": "Step 2: Check if pip3 is already installed by entering the following command in the command prompt."
},
{
"code": null,
"e": 25302,
"s": 25287,
"text": "pip3 --version"
},
{
"code": null,
"e": 25452,
"s": 25302,
"text": "If this command runs successfully, and we are able to get a pip version then we are good to go or else install pip by referring to this article here."
},
{
"code": null,
"e": 25537,
"s": 25452,
"text": "Step 3: Enter the following command to install the latest stable release of Pytorch."
},
{
"code": null,
"e": 25562,
"s": 25537,
"text": "1. Compute Platform: CPU"
},
{
"code": null,
"e": 25604,
"s": 25562,
"text": "pip3 install torch torchvision torchaudio"
},
{
"code": null,
"e": 25712,
"s": 25604,
"text": "Step 4: Check if Pytorch is successfully installed by entering the following command in the command prompt."
},
{
"code": null,
"e": 25728,
"s": 25712,
"text": "pip3 show torch"
},
{
"code": null,
"e": 25847,
"s": 25728,
"text": "If this command runs successfully, and we are able to get a torch version then we are good to go or else reinstall it."
},
{
"code": null,
"e": 25902,
"s": 25847,
"text": "Step 1: Activate Anaconda prompt if it is deactivated."
},
{
"code": null,
"e": 25917,
"s": 25902,
"text": "conda activate"
},
{
"code": null,
"e": 26007,
"s": 25917,
"text": "Step 2: Check if conda is installed by entering the following command in Anaconda Prompt."
},
{
"code": null,
"e": 26023,
"s": 26007,
"text": "conda --version"
},
{
"code": null,
"e": 26155,
"s": 26023,
"text": "If this command runs successfully, and we are able to get a conda version then we are good to go or else install Anaconda on MacOS."
},
{
"code": null,
"e": 26241,
"s": 26155,
"text": "Step 3: Enter the following commands to install the latest stable release of Pytorch."
},
{
"code": null,
"e": 26267,
"s": 26241,
"text": "1. Compute Platform : CPU"
},
{
"code": null,
"e": 26323,
"s": 26267,
"text": "conda install pytorch torchvision torchaudio -c pytorch"
},
{
"code": null,
"e": 26428,
"s": 26323,
"text": "Step 4: Check if Pytorch is successfully installed by entering the following command in Anaconda prompt."
},
{
"code": null,
"e": 26450,
"s": 26428,
"text": "conda list -f pytorch"
},
{
"code": null,
"e": 26569,
"s": 26450,
"text": "If this command runs successfully, and we are able to get a torch version then we are good to go or else reinstall it."
},
{
"code": null,
"e": 26581,
"s": 26569,
"text": "RajuKumar19"
},
{
"code": null,
"e": 26596,
"s": 26581,
"text": "how-to-install"
},
{
"code": null,
"e": 26603,
"s": 26596,
"text": "Picked"
},
{
"code": null,
"e": 26618,
"s": 26603,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 26625,
"s": 26618,
"text": "How To"
},
{
"code": null,
"e": 26644,
"s": 26625,
"text": "Installation Guide"
},
{
"code": null,
"e": 26651,
"s": 26644,
"text": "Python"
},
{
"code": null,
"e": 26749,
"s": 26651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26758,
"s": 26749,
"text": "Comments"
},
{
"code": null,
"e": 26771,
"s": 26758,
"text": "Old Comments"
},
{
"code": null,
"e": 26805,
"s": 26771,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26854,
"s": 26805,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 26912,
"s": 26854,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 26954,
"s": 26912,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27014,
"s": 26954,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 27047,
"s": 27014,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27081,
"s": 27047,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27116,
"s": 27081,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 27174,
"s": 27116,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
How to get the current date in Java?
|
You can get the current date in Java in various ways. Following are some of them −
The no-arg constructor of the java.util.Date class returns the Date object representing the current date and time, using this you can print the current date as shown below −
Live Demo
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class Demo {
public static void main(String args[])throws ParseException {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
String str = formatter.format(date);
System.out.print("Current date: "+str);
}
}
05/11/20
The now() method of the Localdate class returns the Date object representing the current time.
Live Demo
import java.time.LocalDate;
public class CreateDate {
public static void main(String args[]) {
LocalDate date = LocalDate.now();
System.out.println("Current Date: "+date);
}
}
Current Date: 2020-11-05
The getInstance() (without arguments) method of the this class returns the Calendar object representing the current date and time, using this you can print the current date value as shown below −
Live Demo
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;
public class Test {
public static void main(String[] args) throws ParseException{
DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
Calendar obj = Calendar.getInstance();
String str = formatter.format(obj.getTime());
System.out.println("Current Date: "+str );
}
}
Current Date: 05/11/20
One of the constructor of the java.sql.Date class accepts a long value representing a date and creates a Date object. Therefore to create a Data object you need to pass the return value of the System.currentTimeMillis() method (returns current epoch value) as a parameter of the java.sql.Date constructor.
Live Demo
public class CreateDate {
public static void main(String[] args) {
java.sql.Date date=new java.sql.Date(System.currentTimeMillis());
System.out.println("Current Date: "+date);
}
}
Current Date: 2020-11-05
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "You can get the current date in Java in various ways. Following are some of them −"
},
{
"code": null,
"e": 1319,
"s": 1145,
"text": "The no-arg constructor of the java.util.Date class returns the Date object representing the current date and time, using this you can print the current date as shown below −"
},
{
"code": null,
"e": 1329,
"s": 1319,
"text": "Live Demo"
},
{
"code": null,
"e": 1707,
"s": 1329,
"text": "import java.text.SimpleDateFormat;\nimport java.text.ParseException;\nimport java.util.Date;\npublic class Demo {\n public static void main(String args[])throws ParseException { \n Date date = new Date();\n SimpleDateFormat formatter = new SimpleDateFormat(\"dd/MM/yy\");\n String str = formatter.format(date);\n System.out.print(\"Current date: \"+str);\n }\n}"
},
{
"code": null,
"e": 1716,
"s": 1707,
"text": "05/11/20"
},
{
"code": null,
"e": 1811,
"s": 1716,
"text": "The now() method of the Localdate class returns the Date object representing the current time."
},
{
"code": null,
"e": 1821,
"s": 1811,
"text": "Live Demo"
},
{
"code": null,
"e": 2017,
"s": 1821,
"text": "import java.time.LocalDate;\npublic class CreateDate {\n public static void main(String args[]) { \n LocalDate date = LocalDate.now();\n System.out.println(\"Current Date: \"+date);\n }\n}"
},
{
"code": null,
"e": 2042,
"s": 2017,
"text": "Current Date: 2020-11-05"
},
{
"code": null,
"e": 2238,
"s": 2042,
"text": "The getInstance() (without arguments) method of the this class returns the Calendar object representing the current date and time, using this you can print the current date value as shown below −"
},
{
"code": null,
"e": 2248,
"s": 2238,
"text": "Live Demo"
},
{
"code": null,
"e": 2673,
"s": 2248,
"text": "import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.text.ParseException;\nimport java.util.Calendar;\npublic class Test {\n public static void main(String[] args) throws ParseException{\n DateFormat formatter = new SimpleDateFormat(\"dd/MM/yy\");\n Calendar obj = Calendar.getInstance();\n String str = formatter.format(obj.getTime());\n System.out.println(\"Current Date: \"+str );\n }\n}"
},
{
"code": null,
"e": 2696,
"s": 2673,
"text": "Current Date: 05/11/20"
},
{
"code": null,
"e": 3002,
"s": 2696,
"text": "One of the constructor of the java.sql.Date class accepts a long value representing a date and creates a Date object. Therefore to create a Data object you need to pass the return value of the System.currentTimeMillis() method (returns current epoch value) as a parameter of the java.sql.Date constructor."
},
{
"code": null,
"e": 3012,
"s": 3002,
"text": "Live Demo"
},
{
"code": null,
"e": 3210,
"s": 3012,
"text": "public class CreateDate {\n public static void main(String[] args) {\n java.sql.Date date=new java.sql.Date(System.currentTimeMillis());\n System.out.println(\"Current Date: \"+date);\n }\n}"
},
{
"code": null,
"e": 3235,
"s": 3210,
"text": "Current Date: 2020-11-05"
}
] |
Tryit Editor v3.6 - Show Python
|
from mymodule import person1
|
[] |
AI-Memer: Using Machine Learning to Create Funny Memes | Towards Data Science
|
In this article, I’ll show you how I built a system called AI-Memer that generates memes using the latest AI models. I start with a high-level description of the system components before getting into the background of memes and details of the components. I’ll then show you how to generate your own memes using the Google Colab, here. After a brief discussion of results and next steps, you can see some sample memes in the appendix. Oh, and I’ll show a newly generated meme at the head of each section 😄.
The main system components are shown in the diagram below.
The user starts by entering a search query to find a background image, like “apple pie”. The system then checks for matching images in Wikimedia Commons [1] and the OpenImages dataset [2]. Both datasets have corresponding text descriptions of the images. I use the CLIP [3] encoders from OpenAI to first perform a semantic search on the text descriptions. A semantic search looks for matching concepts, not just a word search. I then perform a semantic search on the images. The user checks out the top 10 images that match the query and selects their favorite. Either the GPT-3 model from OpenAI [4] or the GPT-Neo model from EleutherAI [5] is used to generate 10 possible captions. The user selects the best caption to create the new meme, which can be downloaded.
The Wiktionary defines the word meme as “any unit of cultural information, such as a practice or idea, that is transmitted verbally or by repeated action from one mind to another in a comparable way to the transmission of genes” [6]. The term originated in Richard Dawkins’ book “The Selfish Gene” [7]. In the age of the Internet, the term meme has been narrowed to mean a piece of content, typically an image with a funny caption, that’s spread online via social media [8].
Dylan Wenzlau created an automatic meme generator using a deep convolutional network [9]. He used 100M public meme captions by users of the Imgflip Meme Generator and trained the system to generate captions based on 48 commonly used background images. You can read about his system here, and run it online here. Here are three examples.
These are pretty good but the system is limited to use only common background images. I was looking for a way to inject a set of new images into the memesphere.
The AI-Memer system creates memes in three steps: finding background images, generating captions, and typesetting the meme captions.
The background images are pulled from two sources, the Wikimedia Commons and the OpenImages dataset. I use OpenAI’s CLIP to perform a semantic search. The CLIP system accomplishes two functions, encoding both text and images into “embeddings”, which are strings of numbers that represent the gist of the original data. The CLIP model was pretrained on 40 million pairs of images with text labels such that the embeddings encoded from the images will be similar to the embeddings encoded from the text labels. For more information about how CLIP works, check out my article, here.
The Wikimedia Commons has over 73 million JPEG files. Most of them are released with permissive rights, like the Creative Commons Attribution license. I use Goldsmith’s Wikipedia search API [10] to find the top 3 pages related to the text query and gather the image descriptions using the CommonsAPI on the Magnus Toolserver [11]. I use the shutil.copyfileobj() function in python to download the image files. There are typically 3 to 10 images on a Wikipedia page so there will be about 9 to 30 images in total coming down.
The OpenImages dataset from Google is comprised of 675,000 photos scraped from Flikr that were all released under the Creative Commons Attribution license. A dataset of image descriptions is available for download [12]. I ran each of the descriptions through OpenAI’s CLIP system and cached the embeddings for quick access. When the user types in a query, I run it through CLIP and compare it to the cached embeddings. I then download the top 20 matching images using the OpenImages download API [13].
For a final filtering pass, I run the images from the 3 Wikipedia pages and the 20 images from the OpenImages through the image encoder and compare the results to the embedding of the text query. I present the top 10 images to the user to choose their favorite.
For example, if you search for “apple pie”, you will be presented with the top 10 images sorted by closest match.
Picture number 8 looks pretty good. It came from a user named W.carter via Wikipedia Commons. The description is “Simple and easy apple pie served with vanilla ice cream, on a gingham tablecloth in Lysekil, Sweden”. Up next we’ll generate some captions for our new meme.
I use two different implementations of GPT to generate the captions. There’s the latest GPT-3 Da Vinci model [4] from OpenAI that does an excellent job, but you have to be enrolled in their beta program to use it. And there’s the open-source GPT-Neo model [5] from EleutherAI. The model is a lot smaller, but it’s free to use.
OpenAI’s GPT-3 Da Vinci is currently the largest AI model for Natural Language Processing [4]. I am using their latest “zero-shot” style of prompting with their new Da Vinci Instruct model. Instead of providing examples of what you are asking the model to do, you can just simply ask it what to do directly.
Here is the prompt that creates a caption for the apple pie picture.
Create a funny caption for a new meme about apple pie. The background picture is Simple and easy apple pie served with vanilla ice cream, on a gingham tablecloth in Lysekil, Sweden.
I pass the prompt into the call to OpenAI along with some additional parameters. Here’s the Python code.
import openairesponse = openai.Completion.create( engine="davinci-instruct-beta", prompt=prompt, max_tokens=64, temperature=0.7, top_p=0.5, frequency_penalty=0.5, presence_penalty=0.5, best_of=1)
The max_token parameter indicates how long the response should be. The temperature and top_p parameters are similar in that they indicate the amount of variety in the response. The frequency_penalty and presence_penalty are also similar in that they control how often there are new deviations and new topics in the response. If you want to know what all these parameters do, check out my article from last month, here.
Before I show examples of the output from GPT-3, here is the legal disclaimer that OpenAI suggests that I show, which is all true.
The author generated the following text in part with GPT-3, OpenAI’s large-scale language-generation model. Upon generating draft language, the author reviewed and revised the language to their own liking and takes ultimate responsibility for the content of this publication.
Running the code 10 times will yield the following results, at a total cost of $0.03. Note that I formatted the text to be in uppercase.
1: THIS IS THE PERFECT WAY TO END A DAY OF APPLE PICKING 2: NO, IT'S NOT THAT EASY 3: I'LL TAKE THE ONE WITH THE VANILLA ICE CREAM, PLEASE 4: APPLE PIE IS THE BEST! 5: THIS APPLE PIE IS SO GOOD, I CAN'T EVEN! 6: YOU'RE NOT THE ONLY ONE WHO LOVES APPLE PIE 7: IF YOU CAN'T FIND THE RECIPE, JUST GOOGLE IT 8: THE PIE IS GOOD, BUT IT'S NOT AS GOOD AS MY MOM'S 9: I'LL HAVE A SLICE OF THAT APPLE PIE, PLEASE10: WE'RE GOING TO NEED A BIGGER PIE
OK, these are pretty good. One thing I learned is that GTP-3 Da Vinci can be funny! For example, caption number 2 seems to refer to the “easy as pie” idiom.
Note that GPT-3, like all AI models trained on a large corpus of text, will reflect societal biases. Occasionally the system will produce text that may be inappropriate or offensive. OpenAI has a feature to label generated text with one of three warning levels: 0 - the text is safe, 1 - this text is sensitive, or 2 - this text is unsafe. My code will show a warning for any of the generated captions that are flagged as sensitive or unsafe.
GPT-Neo is a transformer model created primarily by developers known as sdtblck and leogao2 on GitHub. The project is an implementation of “GPT-2 and GPT-3-style models using the mesh-tensorflow library” [5]. So far, their system is the size of OpenAI’s GPT-3 Ada, their smallest model. But GPT-Neo is available for free. I used the Huggingface Transformers [14] interface to access GPT-Neo from my Python code.
Since GPT-Neo doesn’t have “instruct” versions of their pre-trained models, I had to write a “few-shot” prompt in order to get the system to generate captions for memes using examples. Here’s the prompt I wrote using Disaster Girl and Grumpy Cat memes with example captions.
Create a funny caption for a meme.Theme: disaster girlImage description: A picture of a girl looking at us as her house burns downCaption: There was a spider. It's gone now.Theme: grumpy catImage description: A face of a cat who looks unhappyCaption: I don't like Mondays.Theme: apple pie.Image description: Simple and easy apple pie served with vanilla ice cream, on a gingham tablecloth in Lysekil, Sweden.Caption:
After setting the temperature parameter to 0.7 and the top_p to 1.0, I pass the prompt into GPT-Neo to generate new captions. Here’s the code to generate a caption.
from transformers import pipeline, AutoTokenizergenerator = pipeline('text-generation', device=0, model='EleutherAI/gpt-neo-2.7B')results = generator(prompt, do_sample=True, min_length=50, max_length=150, temperature=0.7, top_p=1.0, pad_token_id=gpt_neo_tokenizer.eos_token_id)
Here are the sample results.
1: I LOVE APPLE PIE 2: I CAN'T. I'M NOT ALLOWED 3: I LOVE THE SIMPLICITY OF AN APPLE PIE 4: APPLE PIE. THE ONLY THING BETTER THAN THIS IS A HOT BATH 5: I'M A PIE. YOU'RE A PIE 6: I LOVE PIE, AND THIS IS A GOOD ONE 7: I LOVE APPLES, BUT I'M NOT VERY GOOD AT BAKING 8: THE PIE IS DELICIOUS, BUT THE ICE CREAM IS NOT 9: I LOVE APPLE PIE. IT'S THE BEST10: THE BEST FOOD IS WHEN YOU CAN TASTE THE DIFFERENCE BETWEEN THE FOOD AND THE TABLECLOTH
Hmmm. These are not as good as the GPT-3 captions. Most of them are quite simple and not very funny. Number 10 is just plain absurd. But number 4 seems to be OK. Let’s use this as our caption.
The final step is to compose the meme by writing the caption into the background image.
Adding the captions to memes is fairly straightforward. Most memes are composed using the Impact font designed by Geoffrey Lee in 1965 [15]. For AI-Memer, I used some code by Emmanuel Pire for positioning and rendering the caption into the background image [16]. I give the user the option to adjust the size of the font and place the caption at the top or bottom of the image.
Here are our two memes. The caption on the left was generated by GPT-3 and the one on the right was generated by GPT-Neo.
You can create your own memes using the Google Colab, here.
With this project, I learned that large-scale language-generation models can create good captions for memes given a description of the image. Although many of the generated captions are straightforward, occasionally they can be very clever and funny. The GPT-3 Da Vinci model, in particular, seems to create clever memes frequently, demonstrating both a command of the language with a seemingly deep understanding of cultural history.
Although the results are pretty good, there is definitely room for improvement. For example, the choices for background images seem somewhat limited, especially for pop culture. This may be due to the fact that I am restricting the search to use only freely licensed photos. I don’t know if a US court has weighed in yet on whether or not the background images in memes can be deemed to be fair use or not, so I’ll leave that question to the lawyers.
The developers behind GPT-Neo at EleutherAI are continuing to build and train bigger language models. Their next model is called GPT-NeoX. They say their “primary goal is to train an equivalent model to the full-sized GPT-3 and make it available to the public under an open licence.” [17]
Don’t forget to check out more generated memes in the appendix below.
All source code for this project is available on GitHub. You can experiment with the code using this Google Colab. I released the source code under the CC BY-SA license.
If you create any memes with AI-Memer and post them online, please mention the project and add a link to this article.
I would like to thank Jennifer Lim and Oliver Strimpel for their help with this project.
[1] Wikimedia Commons (2004-present)
[2] OpenImages (2020)
[3] A. Radford, J. W. Kim, C. Hallacy, A. Ramesh, G. Goh, S. Agarwal, G. Sastry, A. Askell, P. Mishkin, J. Clark, et al., Learning Transferable Visual Models From Natural Language Supervision (2021)
[4] T. B. Brown, B. Mann, N. Ryder, M. Subbiah, J. Kaplan, P. Dhariwal, A.Neelakantan, et al. Language Models Are Few-Shot Learners (2020)
[5] EleutherAI, GPT-Neo (2020)
[6] Wiktionary (2004-present)
[7] R. Dawkins, The Selfish Gene (2016), Oxford University Press
[8] L. K. Börzsei, Makes a Meme Instead (2013), The Selected Works of Linda Börzsei
[9] D. Wenzlau, Meme Text Generation with a Deep Convolutional Network in Keras & Tensorflow (2019), Towards Data Science
[10] Goldsmith, Wikipedia API (2014)
[11] M. Manske, Wikimedia Commons API (2020)
[12] J. Pont-Tuset, J. Uijlings, S. Changpinyo, R. Soricut, and V. Ferrari, Connecting Vision and Language with Localized Narratives (2020) ECCV (Spotlight)
[13] OpenImages Download API (2018)
[14] Huggingface Transformers (2019)
[15] P. McNeil, The Visual History of Type (2017), Laurence King, p. 372–373
[16] E. Pire, Captioning Memes in Python (2017)
[17] EleutherAI, GPT-NeoX (2021)
Here are some more memes generated by AI-Memer.
To get unlimited access to all articles on Medium, become a member for $5/month. Non-members can only read three locked stories each month.
Some rights reserved
|
[
{
"code": null,
"e": 677,
"s": 171,
"text": "In this article, I’ll show you how I built a system called AI-Memer that generates memes using the latest AI models. I start with a high-level description of the system components before getting into the background of memes and details of the components. I’ll then show you how to generate your own memes using the Google Colab, here. After a brief discussion of results and next steps, you can see some sample memes in the appendix. Oh, and I’ll show a newly generated meme at the head of each section 😄."
},
{
"code": null,
"e": 736,
"s": 677,
"text": "The main system components are shown in the diagram below."
},
{
"code": null,
"e": 1503,
"s": 736,
"text": "The user starts by entering a search query to find a background image, like “apple pie”. The system then checks for matching images in Wikimedia Commons [1] and the OpenImages dataset [2]. Both datasets have corresponding text descriptions of the images. I use the CLIP [3] encoders from OpenAI to first perform a semantic search on the text descriptions. A semantic search looks for matching concepts, not just a word search. I then perform a semantic search on the images. The user checks out the top 10 images that match the query and selects their favorite. Either the GPT-3 model from OpenAI [4] or the GPT-Neo model from EleutherAI [5] is used to generate 10 possible captions. The user selects the best caption to create the new meme, which can be downloaded."
},
{
"code": null,
"e": 1978,
"s": 1503,
"text": "The Wiktionary defines the word meme as “any unit of cultural information, such as a practice or idea, that is transmitted verbally or by repeated action from one mind to another in a comparable way to the transmission of genes” [6]. The term originated in Richard Dawkins’ book “The Selfish Gene” [7]. In the age of the Internet, the term meme has been narrowed to mean a piece of content, typically an image with a funny caption, that’s spread online via social media [8]."
},
{
"code": null,
"e": 2315,
"s": 1978,
"text": "Dylan Wenzlau created an automatic meme generator using a deep convolutional network [9]. He used 100M public meme captions by users of the Imgflip Meme Generator and trained the system to generate captions based on 48 commonly used background images. You can read about his system here, and run it online here. Here are three examples."
},
{
"code": null,
"e": 2476,
"s": 2315,
"text": "These are pretty good but the system is limited to use only common background images. I was looking for a way to inject a set of new images into the memesphere."
},
{
"code": null,
"e": 2609,
"s": 2476,
"text": "The AI-Memer system creates memes in three steps: finding background images, generating captions, and typesetting the meme captions."
},
{
"code": null,
"e": 3189,
"s": 2609,
"text": "The background images are pulled from two sources, the Wikimedia Commons and the OpenImages dataset. I use OpenAI’s CLIP to perform a semantic search. The CLIP system accomplishes two functions, encoding both text and images into “embeddings”, which are strings of numbers that represent the gist of the original data. The CLIP model was pretrained on 40 million pairs of images with text labels such that the embeddings encoded from the images will be similar to the embeddings encoded from the text labels. For more information about how CLIP works, check out my article, here."
},
{
"code": null,
"e": 3714,
"s": 3189,
"text": "The Wikimedia Commons has over 73 million JPEG files. Most of them are released with permissive rights, like the Creative Commons Attribution license. I use Goldsmith’s Wikipedia search API [10] to find the top 3 pages related to the text query and gather the image descriptions using the CommonsAPI on the Magnus Toolserver [11]. I use the shutil.copyfileobj() function in python to download the image files. There are typically 3 to 10 images on a Wikipedia page so there will be about 9 to 30 images in total coming down."
},
{
"code": null,
"e": 4216,
"s": 3714,
"text": "The OpenImages dataset from Google is comprised of 675,000 photos scraped from Flikr that were all released under the Creative Commons Attribution license. A dataset of image descriptions is available for download [12]. I ran each of the descriptions through OpenAI’s CLIP system and cached the embeddings for quick access. When the user types in a query, I run it through CLIP and compare it to the cached embeddings. I then download the top 20 matching images using the OpenImages download API [13]."
},
{
"code": null,
"e": 4478,
"s": 4216,
"text": "For a final filtering pass, I run the images from the 3 Wikipedia pages and the 20 images from the OpenImages through the image encoder and compare the results to the embedding of the text query. I present the top 10 images to the user to choose their favorite."
},
{
"code": null,
"e": 4592,
"s": 4478,
"text": "For example, if you search for “apple pie”, you will be presented with the top 10 images sorted by closest match."
},
{
"code": null,
"e": 4863,
"s": 4592,
"text": "Picture number 8 looks pretty good. It came from a user named W.carter via Wikipedia Commons. The description is “Simple and easy apple pie served with vanilla ice cream, on a gingham tablecloth in Lysekil, Sweden”. Up next we’ll generate some captions for our new meme."
},
{
"code": null,
"e": 5190,
"s": 4863,
"text": "I use two different implementations of GPT to generate the captions. There’s the latest GPT-3 Da Vinci model [4] from OpenAI that does an excellent job, but you have to be enrolled in their beta program to use it. And there’s the open-source GPT-Neo model [5] from EleutherAI. The model is a lot smaller, but it’s free to use."
},
{
"code": null,
"e": 5498,
"s": 5190,
"text": "OpenAI’s GPT-3 Da Vinci is currently the largest AI model for Natural Language Processing [4]. I am using their latest “zero-shot” style of prompting with their new Da Vinci Instruct model. Instead of providing examples of what you are asking the model to do, you can just simply ask it what to do directly."
},
{
"code": null,
"e": 5567,
"s": 5498,
"text": "Here is the prompt that creates a caption for the apple pie picture."
},
{
"code": null,
"e": 5749,
"s": 5567,
"text": "Create a funny caption for a new meme about apple pie. The background picture is Simple and easy apple pie served with vanilla ice cream, on a gingham tablecloth in Lysekil, Sweden."
},
{
"code": null,
"e": 5854,
"s": 5749,
"text": "I pass the prompt into the call to OpenAI along with some additional parameters. Here’s the Python code."
},
{
"code": null,
"e": 6058,
"s": 5854,
"text": "import openairesponse = openai.Completion.create( engine=\"davinci-instruct-beta\", prompt=prompt, max_tokens=64, temperature=0.7, top_p=0.5, frequency_penalty=0.5, presence_penalty=0.5, best_of=1)"
},
{
"code": null,
"e": 6477,
"s": 6058,
"text": "The max_token parameter indicates how long the response should be. The temperature and top_p parameters are similar in that they indicate the amount of variety in the response. The frequency_penalty and presence_penalty are also similar in that they control how often there are new deviations and new topics in the response. If you want to know what all these parameters do, check out my article from last month, here."
},
{
"code": null,
"e": 6608,
"s": 6477,
"text": "Before I show examples of the output from GPT-3, here is the legal disclaimer that OpenAI suggests that I show, which is all true."
},
{
"code": null,
"e": 6884,
"s": 6608,
"text": "The author generated the following text in part with GPT-3, OpenAI’s large-scale language-generation model. Upon generating draft language, the author reviewed and revised the language to their own liking and takes ultimate responsibility for the content of this publication."
},
{
"code": null,
"e": 7021,
"s": 6884,
"text": "Running the code 10 times will yield the following results, at a total cost of $0.03. Note that I formatted the text to be in uppercase."
},
{
"code": null,
"e": 7462,
"s": 7021,
"text": " 1: THIS IS THE PERFECT WAY TO END A DAY OF APPLE PICKING 2: NO, IT'S NOT THAT EASY 3: I'LL TAKE THE ONE WITH THE VANILLA ICE CREAM, PLEASE 4: APPLE PIE IS THE BEST! 5: THIS APPLE PIE IS SO GOOD, I CAN'T EVEN! 6: YOU'RE NOT THE ONLY ONE WHO LOVES APPLE PIE 7: IF YOU CAN'T FIND THE RECIPE, JUST GOOGLE IT 8: THE PIE IS GOOD, BUT IT'S NOT AS GOOD AS MY MOM'S 9: I'LL HAVE A SLICE OF THAT APPLE PIE, PLEASE10: WE'RE GOING TO NEED A BIGGER PIE"
},
{
"code": null,
"e": 7619,
"s": 7462,
"text": "OK, these are pretty good. One thing I learned is that GTP-3 Da Vinci can be funny! For example, caption number 2 seems to refer to the “easy as pie” idiom."
},
{
"code": null,
"e": 8062,
"s": 7619,
"text": "Note that GPT-3, like all AI models trained on a large corpus of text, will reflect societal biases. Occasionally the system will produce text that may be inappropriate or offensive. OpenAI has a feature to label generated text with one of three warning levels: 0 - the text is safe, 1 - this text is sensitive, or 2 - this text is unsafe. My code will show a warning for any of the generated captions that are flagged as sensitive or unsafe."
},
{
"code": null,
"e": 8474,
"s": 8062,
"text": "GPT-Neo is a transformer model created primarily by developers known as sdtblck and leogao2 on GitHub. The project is an implementation of “GPT-2 and GPT-3-style models using the mesh-tensorflow library” [5]. So far, their system is the size of OpenAI’s GPT-3 Ada, their smallest model. But GPT-Neo is available for free. I used the Huggingface Transformers [14] interface to access GPT-Neo from my Python code."
},
{
"code": null,
"e": 8749,
"s": 8474,
"text": "Since GPT-Neo doesn’t have “instruct” versions of their pre-trained models, I had to write a “few-shot” prompt in order to get the system to generate captions for memes using examples. Here’s the prompt I wrote using Disaster Girl and Grumpy Cat memes with example captions."
},
{
"code": null,
"e": 9166,
"s": 8749,
"text": "Create a funny caption for a meme.Theme: disaster girlImage description: A picture of a girl looking at us as her house burns downCaption: There was a spider. It's gone now.Theme: grumpy catImage description: A face of a cat who looks unhappyCaption: I don't like Mondays.Theme: apple pie.Image description: Simple and easy apple pie served with vanilla ice cream, on a gingham tablecloth in Lysekil, Sweden.Caption:"
},
{
"code": null,
"e": 9331,
"s": 9166,
"text": "After setting the temperature parameter to 0.7 and the top_p to 1.0, I pass the prompt into GPT-Neo to generate new captions. Here’s the code to generate a caption."
},
{
"code": null,
"e": 9617,
"s": 9331,
"text": "from transformers import pipeline, AutoTokenizergenerator = pipeline('text-generation', device=0, model='EleutherAI/gpt-neo-2.7B')results = generator(prompt, do_sample=True, min_length=50, max_length=150, temperature=0.7, top_p=1.0, pad_token_id=gpt_neo_tokenizer.eos_token_id)"
},
{
"code": null,
"e": 9646,
"s": 9617,
"text": "Here are the sample results."
},
{
"code": null,
"e": 10086,
"s": 9646,
"text": " 1: I LOVE APPLE PIE 2: I CAN'T. I'M NOT ALLOWED 3: I LOVE THE SIMPLICITY OF AN APPLE PIE 4: APPLE PIE. THE ONLY THING BETTER THAN THIS IS A HOT BATH 5: I'M A PIE. YOU'RE A PIE 6: I LOVE PIE, AND THIS IS A GOOD ONE 7: I LOVE APPLES, BUT I'M NOT VERY GOOD AT BAKING 8: THE PIE IS DELICIOUS, BUT THE ICE CREAM IS NOT 9: I LOVE APPLE PIE. IT'S THE BEST10: THE BEST FOOD IS WHEN YOU CAN TASTE THE DIFFERENCE BETWEEN THE FOOD AND THE TABLECLOTH"
},
{
"code": null,
"e": 10279,
"s": 10086,
"text": "Hmmm. These are not as good as the GPT-3 captions. Most of them are quite simple and not very funny. Number 10 is just plain absurd. But number 4 seems to be OK. Let’s use this as our caption."
},
{
"code": null,
"e": 10367,
"s": 10279,
"text": "The final step is to compose the meme by writing the caption into the background image."
},
{
"code": null,
"e": 10745,
"s": 10367,
"text": "Adding the captions to memes is fairly straightforward. Most memes are composed using the Impact font designed by Geoffrey Lee in 1965 [15]. For AI-Memer, I used some code by Emmanuel Pire for positioning and rendering the caption into the background image [16]. I give the user the option to adjust the size of the font and place the caption at the top or bottom of the image."
},
{
"code": null,
"e": 10867,
"s": 10745,
"text": "Here are our two memes. The caption on the left was generated by GPT-3 and the one on the right was generated by GPT-Neo."
},
{
"code": null,
"e": 10927,
"s": 10867,
"text": "You can create your own memes using the Google Colab, here."
},
{
"code": null,
"e": 11362,
"s": 10927,
"text": "With this project, I learned that large-scale language-generation models can create good captions for memes given a description of the image. Although many of the generated captions are straightforward, occasionally they can be very clever and funny. The GPT-3 Da Vinci model, in particular, seems to create clever memes frequently, demonstrating both a command of the language with a seemingly deep understanding of cultural history."
},
{
"code": null,
"e": 11813,
"s": 11362,
"text": "Although the results are pretty good, there is definitely room for improvement. For example, the choices for background images seem somewhat limited, especially for pop culture. This may be due to the fact that I am restricting the search to use only freely licensed photos. I don’t know if a US court has weighed in yet on whether or not the background images in memes can be deemed to be fair use or not, so I’ll leave that question to the lawyers."
},
{
"code": null,
"e": 12104,
"s": 11813,
"text": "The developers behind GPT-Neo at EleutherAI are continuing to build and train bigger language models. Their next model is called GPT-NeoX. They say their “primary goal is to train an equivalent model to the full-sized GPT-3 and make it available to the public under an open licence.” [17]"
},
{
"code": null,
"e": 12174,
"s": 12104,
"text": "Don’t forget to check out more generated memes in the appendix below."
},
{
"code": null,
"e": 12344,
"s": 12174,
"text": "All source code for this project is available on GitHub. You can experiment with the code using this Google Colab. I released the source code under the CC BY-SA license."
},
{
"code": null,
"e": 12463,
"s": 12344,
"text": "If you create any memes with AI-Memer and post them online, please mention the project and add a link to this article."
},
{
"code": null,
"e": 12552,
"s": 12463,
"text": "I would like to thank Jennifer Lim and Oliver Strimpel for their help with this project."
},
{
"code": null,
"e": 12589,
"s": 12552,
"text": "[1] Wikimedia Commons (2004-present)"
},
{
"code": null,
"e": 12611,
"s": 12589,
"text": "[2] OpenImages (2020)"
},
{
"code": null,
"e": 12810,
"s": 12611,
"text": "[3] A. Radford, J. W. Kim, C. Hallacy, A. Ramesh, G. Goh, S. Agarwal, G. Sastry, A. Askell, P. Mishkin, J. Clark, et al., Learning Transferable Visual Models From Natural Language Supervision (2021)"
},
{
"code": null,
"e": 12949,
"s": 12810,
"text": "[4] T. B. Brown, B. Mann, N. Ryder, M. Subbiah, J. Kaplan, P. Dhariwal, A.Neelakantan, et al. Language Models Are Few-Shot Learners (2020)"
},
{
"code": null,
"e": 12980,
"s": 12949,
"text": "[5] EleutherAI, GPT-Neo (2020)"
},
{
"code": null,
"e": 13010,
"s": 12980,
"text": "[6] Wiktionary (2004-present)"
},
{
"code": null,
"e": 13075,
"s": 13010,
"text": "[7] R. Dawkins, The Selfish Gene (2016), Oxford University Press"
},
{
"code": null,
"e": 13161,
"s": 13075,
"text": "[8] L. K. Börzsei, Makes a Meme Instead (2013), The Selected Works of Linda Börzsei"
},
{
"code": null,
"e": 13283,
"s": 13161,
"text": "[9] D. Wenzlau, Meme Text Generation with a Deep Convolutional Network in Keras & Tensorflow (2019), Towards Data Science"
},
{
"code": null,
"e": 13320,
"s": 13283,
"text": "[10] Goldsmith, Wikipedia API (2014)"
},
{
"code": null,
"e": 13365,
"s": 13320,
"text": "[11] M. Manske, Wikimedia Commons API (2020)"
},
{
"code": null,
"e": 13522,
"s": 13365,
"text": "[12] J. Pont-Tuset, J. Uijlings, S. Changpinyo, R. Soricut, and V. Ferrari, Connecting Vision and Language with Localized Narratives (2020) ECCV (Spotlight)"
},
{
"code": null,
"e": 13558,
"s": 13522,
"text": "[13] OpenImages Download API (2018)"
},
{
"code": null,
"e": 13595,
"s": 13558,
"text": "[14] Huggingface Transformers (2019)"
},
{
"code": null,
"e": 13672,
"s": 13595,
"text": "[15] P. McNeil, The Visual History of Type (2017), Laurence King, p. 372–373"
},
{
"code": null,
"e": 13720,
"s": 13672,
"text": "[16] E. Pire, Captioning Memes in Python (2017)"
},
{
"code": null,
"e": 13753,
"s": 13720,
"text": "[17] EleutherAI, GPT-NeoX (2021)"
},
{
"code": null,
"e": 13801,
"s": 13753,
"text": "Here are some more memes generated by AI-Memer."
},
{
"code": null,
"e": 13941,
"s": 13801,
"text": "To get unlimited access to all articles on Medium, become a member for $5/month. Non-members can only read three locked stories each month."
}
] |
Xception: Implementing from scratch using Tensorflow | by Arjun Sarkar | Towards Data Science
|
Convolutional Neural Networks (CNN) have come a long way, from the LeNet-style, AlexNet, VGG models, which used simple stacks of convolutional layers for feature extraction and max-pooling layers for spatial sub-sampling, stacked one after the other, to Inception and ResNet networks which use skip connections and multiple convolutional and max-pooling blocks in each layer. Since its introduction, one of the best networks in computer vision has been the Inception network. The Inception model uses a stack of modules, each module containing a bunch of feature extractors, which allow them to learn richer representations with fewer parameters.
Xception paper — https://arxiv.org/abs/1610.02357
As we see in figure 1, the Xception module has 3 main parts. The Entry flow, the Middle flow (which is repeated 8 times), and the Exit flow.
The entry flow has two blocks of convolutional layer followed by a ReLU activation. The diagram also mentions in detail the number of filters, the filter size (kernel size), and the strides.
There are also various Separable convolutional layers. There are also Max Pooling layers. When the strides are different than one, the strides are also mentioned. There are also Skip connections, where we use ‘ADD’ to merge the two tensors. It also shows the shape of the input tensor in each flow. For example, we begin with an image size of 299x299x3, and after the entry flow, we get an image size of 19x19x728.
Similarly, for the Middle flow and the Exit flow, this diagram clearly explains the image size, the various layers, the number of filters, the shape of filters, the type of pooling, the number of repetitions, and the option of adding a fully connected layer in the end.
Also, all Convolutional and Separable Convolutional layers are followed by batch normalization.
Separable convolutions consist of first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes the resulting output channels.- From Keras Documentation
Let's assume that we have an input tensor of size (K, K,3). K is the spatial dimension and 3 is the number of feature maps/channels. As we see from the above Keras documentation, first we need to implement depthwise spatial convolution on each input channel separately. So we use K, K,1 — the first channel of the image/tensor. Suppose we use a filter of size 3x3x1. And this filter is applied across all three channels of the input tensor. As there are 3 channels, so the dimension we get is 3x3x1x3. This is shown in the Depthwise convolution part of Figure 4.
After this, all the 3 outputs are taken together, and we obtain a tensor of size (L, L,3). The dimensions of L can be the same as K or can be different, depending on the strides and padding used in the previous convolutions.
Then the Pointwise convolution is applied. The filter is of size 1x1x3 (3 channels). And the number of filters can be any number of filters we want. Let’s say we use 64 filters. So the total dimension comes to 1x1x3x64. Finally, we obtain an output tensor of size LxLx64. this is shown in the Pointwise convolution part of Figure 4.
Why is separable convolution better than normal convolution?
If we were to use a normal convolution on the input tensor, and we use a filter/kernel size of 3x3x3 (kernel size — (3,3) and 3 feature maps). And the total number of filters we want is 64. So a total of 3x3x3x64.
Instead, in separable convolution, we first use 3x3x1x3 in depthwise convolution and 1x1x3x64 in pointwise convolution.
The difference lies in the dimensionality of the filters.
Traditional Convolutional layer = 3x3x3x64 = 1,728
Separable Convolutional layer = (3x3x1x3)+(1x1x3x64) = 27+192 = 219
As we see, separable convolution layers are way more advantageous than traditional convolutional layers, both in terms of computation cost as well as memory. The main difference is that in the normal convolution, we are transforming the image multiple times. And every transformation uses up 3x3x3x64 = 1,728 multiplications. In the separable convolution, we only transform the image once — in the depthwise convolution. Then, we take the transformed image and simply elongate it to 64 channels. Without having to transform the image over and over again, we can save up on computational power.
Algorithm:
Import all the necessary layersWrite all the necessary functions for:
Import all the necessary layers
Write all the necessary functions for:
a. Conv-BatchNorm block
b. SeparableConv- BatchNorm block
3. Write one function for each one of the 3 flows — Entry, Middle, and Exit
4. Use these functions to build the complete model
#import necessary librariesimport tensorflow as tffrom tensorflow.keras.layers import Input,Dense,Conv2D,Addfrom tensorflow.keras.layers import SeparableConv2D,ReLUfrom tensorflow.keras.layers import BatchNormalization,MaxPool2Dfrom tensorflow.keras.layers import GlobalAvgPool2Dfrom tensorflow.keras import Model
Creating the Conv-BatchNorm block:
# creating the Conv-Batch Norm blockdef conv_bn(x, filters, kernel_size, strides=1): x = Conv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x
The Conv-Batch Norm block takes as inputs, a tensor — x, number of filters — filters, kernel size of the convolutional layer — kernel_size, strides of convolutional layer — strides. Then we apply a convolution layer to x and then apply Batch Normalization. We add use_bias = False, so that the number of parameters of the final model, will be the same as the number of parameters of the original paper.
Creating the SeparableConv- BatchNorm block:
# creating separableConv-Batch Norm blockdef sep_bn(x, filters, kernel_size, strides=1): x = SeparableConv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x
Similar structure as the Conv-Batch Norm block, except we use SeparableConv2D instead of Conv2D.
Functions for Entry, Middle, and Exit flow:
# entry flowdef entry_flow(x): x = conv_bn(x, filters =32, kernel_size =3, strides=2) x = ReLU()(x) x = conv_bn(x, filters =64, kernel_size =3, strides=1) tensor = ReLU()(x) x = sep_bn(tensor, filters = 128, kernel_size =3) x = ReLU()(x) x = sep_bn(x, filters = 128, kernel_size =3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=128, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=256, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=728, kernel_size = 1,strides=2) x = Add()([tensor,x])return x
Here we just follow Figure 2. It begins with two Conv layers with 32 and 64 filters respectively. Each followed by a ReLU activation.
Then there is a skip connection, which is done by using Add.
Inside each of the skip connection blocks, there are two separable Conv layers followed by MaxPooling. The skip connections itself have a Conv layer of 1x1 with strides 2.
# middle flowdef middle_flow(tensor): for _ in range(8): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) tensor = Add()([tensor,x]) return tensor
The middle flow follows the steps as shown in figure 7.
# exit flowdef exit_flow(tensor): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 1024, kernel_size=3) x = MaxPool2D(pool_size = 3, strides = 2, padding ='same')(x) tensor = conv_bn(tensor, filters =1024, kernel_size=1, strides =2) x = Add()([tensor,x]) x = sep_bn(x, filters = 1536, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 2048, kernel_size=3) x = GlobalAvgPool2D()(x) x = Dense (units = 1000, activation = 'softmax')(x) return x
The exit flow follows the steps as shown in figure 8.
Creating the Xception Model:
# model codeinput = Input(shape = (299,299,3))x = entry_flow(input)x = middle_flow(x)output = exit_flow(x)model = Model (inputs=input, outputs=output)model.summary()
Output snippet:
from tensorflow.python.keras.utils.vis_utils import model_to_dotfrom IPython.display import SVGimport pydotimport graphvizSVG(model_to_dot(model, show_shapes=True, show_layer_names=True, rankdir='TB',expand_nested=False, dpi=60, subgraph=False).create(prog='dot',format='svg'))
Output snippet:
import numpy as np import tensorflow.keras.backend as K np.sum([K.count_params(p) for p in model.trainable_weights])
Output: 22855952
The above code displays the number of trainable parameters.
Entire code to create Xception model from scratch using Tensorflow:
#import necessary librariesimport tensorflow as tffrom tensorflow.keras.layers import Input,Dense,Conv2D,Addfrom tensorflow.keras.layers import SeparableConv2D,ReLUfrom tensorflow.keras.layers import BatchNormalization,MaxPool2Dfrom tensorflow.keras.layers import GlobalAvgPool2Dfrom tensorflow.keras import Model# creating the Conv-Batch Norm blockdef conv_bn(x, filters, kernel_size, strides=1): x = Conv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x# creating separableConv-Batch Norm blockdef sep_bn(x, filters, kernel_size, strides=1): x = SeparableConv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x# entry flowdef entry_flow(x): x = conv_bn(x, filters =32, kernel_size =3, strides=2) x = ReLU()(x) x = conv_bn(x, filters =64, kernel_size =3, strides=1) tensor = ReLU()(x) x = sep_bn(tensor, filters = 128, kernel_size =3) x = ReLU()(x) x = sep_bn(x, filters = 128, kernel_size =3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=128, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=256, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=728, kernel_size = 1,strides=2) x = Add()([tensor,x])return x# middle flowdef middle_flow(tensor): for _ in range(8): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) tensor = Add()([tensor,x]) return tensor# exit flowdef exit_flow(tensor): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 1024, kernel_size=3) x = MaxPool2D(pool_size = 3, strides = 2, padding ='same')(x) tensor = conv_bn(tensor, filters =1024, kernel_size=1, strides =2) x = Add()([tensor,x]) x = sep_bn(x, filters = 1536, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 2048, kernel_size=3) x = GlobalAvgPool2D()(x) x = Dense (units = 1000, activation = 'softmax')(x) return x# model codeinput = Input(shape = (299,299,3))x = entry_flow(input)x = middle_flow(x)output = exit_flow(x)model = Model (inputs=input, outputs=output)model.summary()
Conclusion:
As seen in Figures 5 and 6, the Xception architecture shows much better performance improvement than the Inception network on the JFT dataset as compared to the ImageNet dataset. The authors of Xception believe that this is due to the fact that Inception was designed to focus on ImageNet and thus might have over-fit on the specific task. On the other hand, neither architectures were tuned for the JFT dataset.
Also, Inception has approximately 23.6 million parameters while Xception has 22.8 million parameters.
The Xception architecture is very easily explained in the paper as seen in Figure 1, making it very easy to implement the network architecture using TensorFlow.
References:
François Chollet, Xception: Deep Learning with Depthwise Separable Convolutions, arXiv:1610.02357v3 [cs.CV], 2017
François Chollet, Xception: Deep Learning with Depthwise Separable Convolutions, arXiv:1610.02357v3 [cs.CV], 2017
|
[
{
"code": null,
"e": 819,
"s": 172,
"text": "Convolutional Neural Networks (CNN) have come a long way, from the LeNet-style, AlexNet, VGG models, which used simple stacks of convolutional layers for feature extraction and max-pooling layers for spatial sub-sampling, stacked one after the other, to Inception and ResNet networks which use skip connections and multiple convolutional and max-pooling blocks in each layer. Since its introduction, one of the best networks in computer vision has been the Inception network. The Inception model uses a stack of modules, each module containing a bunch of feature extractors, which allow them to learn richer representations with fewer parameters."
},
{
"code": null,
"e": 869,
"s": 819,
"text": "Xception paper — https://arxiv.org/abs/1610.02357"
},
{
"code": null,
"e": 1010,
"s": 869,
"text": "As we see in figure 1, the Xception module has 3 main parts. The Entry flow, the Middle flow (which is repeated 8 times), and the Exit flow."
},
{
"code": null,
"e": 1201,
"s": 1010,
"text": "The entry flow has two blocks of convolutional layer followed by a ReLU activation. The diagram also mentions in detail the number of filters, the filter size (kernel size), and the strides."
},
{
"code": null,
"e": 1616,
"s": 1201,
"text": "There are also various Separable convolutional layers. There are also Max Pooling layers. When the strides are different than one, the strides are also mentioned. There are also Skip connections, where we use ‘ADD’ to merge the two tensors. It also shows the shape of the input tensor in each flow. For example, we begin with an image size of 299x299x3, and after the entry flow, we get an image size of 19x19x728."
},
{
"code": null,
"e": 1886,
"s": 1616,
"text": "Similarly, for the Middle flow and the Exit flow, this diagram clearly explains the image size, the various layers, the number of filters, the shape of filters, the type of pooling, the number of repetitions, and the option of adding a fully connected layer in the end."
},
{
"code": null,
"e": 1982,
"s": 1886,
"text": "Also, all Convolutional and Separable Convolutional layers are followed by batch normalization."
},
{
"code": null,
"e": 2216,
"s": 1982,
"text": "Separable convolutions consist of first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes the resulting output channels.- From Keras Documentation"
},
{
"code": null,
"e": 2779,
"s": 2216,
"text": "Let's assume that we have an input tensor of size (K, K,3). K is the spatial dimension and 3 is the number of feature maps/channels. As we see from the above Keras documentation, first we need to implement depthwise spatial convolution on each input channel separately. So we use K, K,1 — the first channel of the image/tensor. Suppose we use a filter of size 3x3x1. And this filter is applied across all three channels of the input tensor. As there are 3 channels, so the dimension we get is 3x3x1x3. This is shown in the Depthwise convolution part of Figure 4."
},
{
"code": null,
"e": 3004,
"s": 2779,
"text": "After this, all the 3 outputs are taken together, and we obtain a tensor of size (L, L,3). The dimensions of L can be the same as K or can be different, depending on the strides and padding used in the previous convolutions."
},
{
"code": null,
"e": 3337,
"s": 3004,
"text": "Then the Pointwise convolution is applied. The filter is of size 1x1x3 (3 channels). And the number of filters can be any number of filters we want. Let’s say we use 64 filters. So the total dimension comes to 1x1x3x64. Finally, we obtain an output tensor of size LxLx64. this is shown in the Pointwise convolution part of Figure 4."
},
{
"code": null,
"e": 3398,
"s": 3337,
"text": "Why is separable convolution better than normal convolution?"
},
{
"code": null,
"e": 3612,
"s": 3398,
"text": "If we were to use a normal convolution on the input tensor, and we use a filter/kernel size of 3x3x3 (kernel size — (3,3) and 3 feature maps). And the total number of filters we want is 64. So a total of 3x3x3x64."
},
{
"code": null,
"e": 3732,
"s": 3612,
"text": "Instead, in separable convolution, we first use 3x3x1x3 in depthwise convolution and 1x1x3x64 in pointwise convolution."
},
{
"code": null,
"e": 3790,
"s": 3732,
"text": "The difference lies in the dimensionality of the filters."
},
{
"code": null,
"e": 3841,
"s": 3790,
"text": "Traditional Convolutional layer = 3x3x3x64 = 1,728"
},
{
"code": null,
"e": 3909,
"s": 3841,
"text": "Separable Convolutional layer = (3x3x1x3)+(1x1x3x64) = 27+192 = 219"
},
{
"code": null,
"e": 4503,
"s": 3909,
"text": "As we see, separable convolution layers are way more advantageous than traditional convolutional layers, both in terms of computation cost as well as memory. The main difference is that in the normal convolution, we are transforming the image multiple times. And every transformation uses up 3x3x3x64 = 1,728 multiplications. In the separable convolution, we only transform the image once — in the depthwise convolution. Then, we take the transformed image and simply elongate it to 64 channels. Without having to transform the image over and over again, we can save up on computational power."
},
{
"code": null,
"e": 4514,
"s": 4503,
"text": "Algorithm:"
},
{
"code": null,
"e": 4584,
"s": 4514,
"text": "Import all the necessary layersWrite all the necessary functions for:"
},
{
"code": null,
"e": 4616,
"s": 4584,
"text": "Import all the necessary layers"
},
{
"code": null,
"e": 4655,
"s": 4616,
"text": "Write all the necessary functions for:"
},
{
"code": null,
"e": 4679,
"s": 4655,
"text": "a. Conv-BatchNorm block"
},
{
"code": null,
"e": 4713,
"s": 4679,
"text": "b. SeparableConv- BatchNorm block"
},
{
"code": null,
"e": 4789,
"s": 4713,
"text": "3. Write one function for each one of the 3 flows — Entry, Middle, and Exit"
},
{
"code": null,
"e": 4840,
"s": 4789,
"text": "4. Use these functions to build the complete model"
},
{
"code": null,
"e": 5154,
"s": 4840,
"text": "#import necessary librariesimport tensorflow as tffrom tensorflow.keras.layers import Input,Dense,Conv2D,Addfrom tensorflow.keras.layers import SeparableConv2D,ReLUfrom tensorflow.keras.layers import BatchNormalization,MaxPool2Dfrom tensorflow.keras.layers import GlobalAvgPool2Dfrom tensorflow.keras import Model"
},
{
"code": null,
"e": 5189,
"s": 5154,
"text": "Creating the Conv-BatchNorm block:"
},
{
"code": null,
"e": 5491,
"s": 5189,
"text": "# creating the Conv-Batch Norm blockdef conv_bn(x, filters, kernel_size, strides=1): x = Conv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x"
},
{
"code": null,
"e": 5894,
"s": 5491,
"text": "The Conv-Batch Norm block takes as inputs, a tensor — x, number of filters — filters, kernel size of the convolutional layer — kernel_size, strides of convolutional layer — strides. Then we apply a convolution layer to x and then apply Batch Normalization. We add use_bias = False, so that the number of parameters of the final model, will be the same as the number of parameters of the original paper."
},
{
"code": null,
"e": 5939,
"s": 5894,
"text": "Creating the SeparableConv- BatchNorm block:"
},
{
"code": null,
"e": 6290,
"s": 5939,
"text": "# creating separableConv-Batch Norm blockdef sep_bn(x, filters, kernel_size, strides=1): x = SeparableConv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x"
},
{
"code": null,
"e": 6387,
"s": 6290,
"text": "Similar structure as the Conv-Batch Norm block, except we use SeparableConv2D instead of Conv2D."
},
{
"code": null,
"e": 6431,
"s": 6387,
"text": "Functions for Entry, Middle, and Exit flow:"
},
{
"code": null,
"e": 7488,
"s": 6431,
"text": "# entry flowdef entry_flow(x): x = conv_bn(x, filters =32, kernel_size =3, strides=2) x = ReLU()(x) x = conv_bn(x, filters =64, kernel_size =3, strides=1) tensor = ReLU()(x) x = sep_bn(tensor, filters = 128, kernel_size =3) x = ReLU()(x) x = sep_bn(x, filters = 128, kernel_size =3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=128, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=256, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=728, kernel_size = 1,strides=2) x = Add()([tensor,x])return x"
},
{
"code": null,
"e": 7622,
"s": 7488,
"text": "Here we just follow Figure 2. It begins with two Conv layers with 32 and 64 filters respectively. Each followed by a ReLU activation."
},
{
"code": null,
"e": 7683,
"s": 7622,
"text": "Then there is a skip connection, which is done by using Add."
},
{
"code": null,
"e": 7855,
"s": 7683,
"text": "Inside each of the skip connection blocks, there are two separable Conv layers followed by MaxPooling. The skip connections itself have a Conv layer of 1x1 with strides 2."
},
{
"code": null,
"e": 8226,
"s": 7855,
"text": "# middle flowdef middle_flow(tensor): for _ in range(8): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) tensor = Add()([tensor,x]) return tensor"
},
{
"code": null,
"e": 8282,
"s": 8226,
"text": "The middle flow follows the steps as shown in figure 7."
},
{
"code": null,
"e": 8842,
"s": 8282,
"text": "# exit flowdef exit_flow(tensor): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 1024, kernel_size=3) x = MaxPool2D(pool_size = 3, strides = 2, padding ='same')(x) tensor = conv_bn(tensor, filters =1024, kernel_size=1, strides =2) x = Add()([tensor,x]) x = sep_bn(x, filters = 1536, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 2048, kernel_size=3) x = GlobalAvgPool2D()(x) x = Dense (units = 1000, activation = 'softmax')(x) return x"
},
{
"code": null,
"e": 8896,
"s": 8842,
"text": "The exit flow follows the steps as shown in figure 8."
},
{
"code": null,
"e": 8925,
"s": 8896,
"text": "Creating the Xception Model:"
},
{
"code": null,
"e": 9091,
"s": 8925,
"text": "# model codeinput = Input(shape = (299,299,3))x = entry_flow(input)x = middle_flow(x)output = exit_flow(x)model = Model (inputs=input, outputs=output)model.summary()"
},
{
"code": null,
"e": 9107,
"s": 9091,
"text": "Output snippet:"
},
{
"code": null,
"e": 9385,
"s": 9107,
"text": "from tensorflow.python.keras.utils.vis_utils import model_to_dotfrom IPython.display import SVGimport pydotimport graphvizSVG(model_to_dot(model, show_shapes=True, show_layer_names=True, rankdir='TB',expand_nested=False, dpi=60, subgraph=False).create(prog='dot',format='svg'))"
},
{
"code": null,
"e": 9401,
"s": 9385,
"text": "Output snippet:"
},
{
"code": null,
"e": 9518,
"s": 9401,
"text": "import numpy as np import tensorflow.keras.backend as K np.sum([K.count_params(p) for p in model.trainable_weights])"
},
{
"code": null,
"e": 9535,
"s": 9518,
"text": "Output: 22855952"
},
{
"code": null,
"e": 9595,
"s": 9535,
"text": "The above code displays the number of trainable parameters."
},
{
"code": null,
"e": 9663,
"s": 9595,
"text": "Entire code to create Xception model from scratch using Tensorflow:"
},
{
"code": null,
"e": 12778,
"s": 9663,
"text": "#import necessary librariesimport tensorflow as tffrom tensorflow.keras.layers import Input,Dense,Conv2D,Addfrom tensorflow.keras.layers import SeparableConv2D,ReLUfrom tensorflow.keras.layers import BatchNormalization,MaxPool2Dfrom tensorflow.keras.layers import GlobalAvgPool2Dfrom tensorflow.keras import Model# creating the Conv-Batch Norm blockdef conv_bn(x, filters, kernel_size, strides=1): x = Conv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x# creating separableConv-Batch Norm blockdef sep_bn(x, filters, kernel_size, strides=1): x = SeparableConv2D(filters=filters, kernel_size = kernel_size, strides=strides, padding = 'same', use_bias = False)(x) x = BatchNormalization()(x)return x# entry flowdef entry_flow(x): x = conv_bn(x, filters =32, kernel_size =3, strides=2) x = ReLU()(x) x = conv_bn(x, filters =64, kernel_size =3, strides=1) tensor = ReLU()(x) x = sep_bn(tensor, filters = 128, kernel_size =3) x = ReLU()(x) x = sep_bn(x, filters = 128, kernel_size =3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=128, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =256, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=256, kernel_size = 1,strides=2) x = Add()([tensor,x]) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters =728, kernel_size=3) x = MaxPool2D(pool_size=3, strides=2, padding = 'same')(x) tensor = conv_bn(tensor, filters=728, kernel_size = 1,strides=2) x = Add()([tensor,x])return x# middle flowdef middle_flow(tensor): for _ in range(8): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) x = sep_bn(x, filters = 728, kernel_size = 3) x = ReLU()(x) tensor = Add()([tensor,x]) return tensor# exit flowdef exit_flow(tensor): x = ReLU()(tensor) x = sep_bn(x, filters = 728, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 1024, kernel_size=3) x = MaxPool2D(pool_size = 3, strides = 2, padding ='same')(x) tensor = conv_bn(tensor, filters =1024, kernel_size=1, strides =2) x = Add()([tensor,x]) x = sep_bn(x, filters = 1536, kernel_size=3) x = ReLU()(x) x = sep_bn(x, filters = 2048, kernel_size=3) x = GlobalAvgPool2D()(x) x = Dense (units = 1000, activation = 'softmax')(x) return x# model codeinput = Input(shape = (299,299,3))x = entry_flow(input)x = middle_flow(x)output = exit_flow(x)model = Model (inputs=input, outputs=output)model.summary()"
},
{
"code": null,
"e": 12790,
"s": 12778,
"text": "Conclusion:"
},
{
"code": null,
"e": 13203,
"s": 12790,
"text": "As seen in Figures 5 and 6, the Xception architecture shows much better performance improvement than the Inception network on the JFT dataset as compared to the ImageNet dataset. The authors of Xception believe that this is due to the fact that Inception was designed to focus on ImageNet and thus might have over-fit on the specific task. On the other hand, neither architectures were tuned for the JFT dataset."
},
{
"code": null,
"e": 13305,
"s": 13203,
"text": "Also, Inception has approximately 23.6 million parameters while Xception has 22.8 million parameters."
},
{
"code": null,
"e": 13466,
"s": 13305,
"text": "The Xception architecture is very easily explained in the paper as seen in Figure 1, making it very easy to implement the network architecture using TensorFlow."
},
{
"code": null,
"e": 13478,
"s": 13466,
"text": "References:"
},
{
"code": null,
"e": 13593,
"s": 13478,
"text": "François Chollet, Xception: Deep Learning with Depthwise Separable Convolutions, arXiv:1610.02357v3 [cs.CV], 2017"
}
] |
Batch Script - Reading from Files
|
Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the ‘for’ loop needs to be used to serve this purpose.
Let’s look at an example on how this can be achieved.
@echo off
FOR /F "tokens=* delims=" %%x in (new.txt) DO echo %%x
The delims parameter is used to break up the text in the file into different tokens or words. Each word or token is then stored in the variable x. For each word which is read from the file, an echo is done to print the word to the console output.
If you consider the new.txt file which has been considered in previous examples, you might get the following output when the above program is run.
"This is the directory listing of C:\ Drive"
Volume in drive C is Windows8_OS
Volume Serial Number is E41C-6F43
Directory of C:\
12/22/2015 09:02 PM <DIR> 01 - Music
06/14/2015 10:31 AM <DIR> 02 - Videos
09/12/2015 06:23 AM <DIR> 03 - Pictures
12/17/2015 12:19 AM <DIR> 04 - Software
12/15/2015 11:06 PM <DIR> 05 - Studies
12/20/2014 09:09 AM <DIR> 06 - Future
12/20/2014 09:07 AM <DIR> 07 - Fitness
09/19/2015 09:56 AM <DIR> 08 - Tracking
10/19/2015 10:28 PM <DIR> 09 – Misc
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2451,
"s": 2169,
"text": "Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the ‘for’ loop needs to be used to serve this purpose."
},
{
"code": null,
"e": 2505,
"s": 2451,
"text": "Let’s look at an example on how this can be achieved."
},
{
"code": null,
"e": 2570,
"s": 2505,
"text": "@echo off\nFOR /F \"tokens=* delims=\" %%x in (new.txt) DO echo %%x"
},
{
"code": null,
"e": 2817,
"s": 2570,
"text": "The delims parameter is used to break up the text in the file into different tokens or words. Each word or token is then stored in the variable x. For each word which is read from the file, an echo is done to print the word to the console output."
},
{
"code": null,
"e": 2964,
"s": 2817,
"text": "If you consider the new.txt file which has been considered in previous examples, you might get the following output when the above program is run."
},
{
"code": null,
"e": 3515,
"s": 2964,
"text": "\"This is the directory listing of C:\\ Drive\"\nVolume in drive C is Windows8_OS\nVolume Serial Number is E41C-6F43\n\nDirectory of C:\\\n\n12/22/2015 09:02 PM <DIR> 01 - Music\n06/14/2015 10:31 AM <DIR> 02 - Videos\n09/12/2015 06:23 AM <DIR> 03 - Pictures\n12/17/2015 12:19 AM <DIR> 04 - Software\n12/15/2015 11:06 PM <DIR> 05 - Studies\n12/20/2014 09:09 AM <DIR> 06 - Future\n12/20/2014 09:07 AM <DIR> 07 - Fitness\n09/19/2015 09:56 AM <DIR> 08 - Tracking\n10/19/2015 10:28 PM <DIR> 09 – Misc\n"
},
{
"code": null,
"e": 3522,
"s": 3515,
"text": " Print"
},
{
"code": null,
"e": 3533,
"s": 3522,
"text": " Add Notes"
}
] |
How to return the nth record from MySQL query?
|
To get the nth record from MySQL query, you can use LIMIT. The syntax is as follows −
select *from yourTableName order by yourColumnName limit n,1;
To understand the above syntax, let us create a table. The following is the query to create a table −
mysql> create table NthRecordDemo
−> (
−> Id int,
−> Name varchar(200)
−> );
Query OK, 0 rows affected (0.92 sec)
Insert some records in the table using the following query −
mysql> insert into NthRecordDemo values(100,'John');
Query OK, 1 row affected (0.09 sec)
mysql> insert into NthRecordDemo values(101,'Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into NthRecordDemo values(102,'Carol');
Query OK, 1 row affected (0.22 sec)
mysql> insert into NthRecordDemo values(103,'Smith');
Query OK, 1 row affected (0.18 sec)
mysql> insert into NthRecordDemo values(104,'Johnson');
Query OK, 1 row affected (0.16 sec)
mysql> insert into NthRecordDemo values(105,'Sam');
Query OK, 1 row affected (0.16 sec)
mysql> insert into NthRecordDemo values(106,'David');
Query OK, 1 row affected (0.13 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from NthRecordDemo;
The following is the output −
+------+---------+
| Id | Name |
+------+---------+
| 100 | John |
| 101 | Bob |
| 102 | Carol |
| 103 | Smith |
| 104 | Johnson |
| 105 | Sam |
| 106 | David |
+------+---------+
7 rows in set (0.00 sec)
Use the following query to get nth record from the table −
mysql> select *from NthRecordDemo order by Id limit 6,1;
The following is the output −
+------+-------+
| Id | Name |
+------+-------+
| 106 | David |
+------+-------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To get the nth record from MySQL query, you can use LIMIT. The syntax is as follows −"
},
{
"code": null,
"e": 1210,
"s": 1148,
"text": "select *from yourTableName order by yourColumnName limit n,1;"
},
{
"code": null,
"e": 1312,
"s": 1210,
"text": "To understand the above syntax, let us create a table. The following is the query to create a table −"
},
{
"code": null,
"e": 1438,
"s": 1312,
"text": "mysql> create table NthRecordDemo\n −> (\n −> Id int,\n −> Name varchar(200)\n −> );\nQuery OK, 0 rows affected (0.92 sec)"
},
{
"code": null,
"e": 1499,
"s": 1438,
"text": "Insert some records in the table using the following query −"
},
{
"code": null,
"e": 2132,
"s": 1499,
"text": "mysql> insert into NthRecordDemo values(100,'John');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into NthRecordDemo values(101,'Bob');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into NthRecordDemo values(102,'Carol');\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into NthRecordDemo values(103,'Smith');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into NthRecordDemo values(104,'Johnson');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into NthRecordDemo values(105,'Sam');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into NthRecordDemo values(106,'David');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 2228,
"s": 2132,
"text": "Display all records from the table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 2263,
"s": 2228,
"text": "mysql> select *from NthRecordDemo;"
},
{
"code": null,
"e": 2293,
"s": 2263,
"text": "The following is the output −"
},
{
"code": null,
"e": 2527,
"s": 2293,
"text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 100 | John |\n| 101 | Bob |\n| 102 | Carol |\n| 103 | Smith |\n| 104 | Johnson |\n| 105 | Sam |\n| 106 | David |\n+------+---------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2586,
"s": 2527,
"text": "Use the following query to get nth record from the table −"
},
{
"code": null,
"e": 2643,
"s": 2586,
"text": "mysql> select *from NthRecordDemo order by Id limit 6,1;"
},
{
"code": null,
"e": 2673,
"s": 2643,
"text": "The following is the output −"
},
{
"code": null,
"e": 2782,
"s": 2673,
"text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 106 | David |\n+------+-------+\n1 row in set (0.00 sec)"
}
] |
Dictionary as an Alternative to If-Else | by Khuyen Tran | Towards Data Science
|
You may have been frequently working with Python’s dictionaries. But have you unlocked the full capacity of the dictionary to create a more efficient code? If you didn’t know how to create an ordered dictionary, group multiple dictionaries into a single mapping, create a read-only dictionary, you could found out more here.
This article will focus on how to use Python’s dictionaries as an alternative to if-else statements.
Imagine we have the price list of items in the grocery store:
price_list = {'fish': 8,'beef': 7,'broccoli': 3,}
We want to print the price of the item but anticipate that not every item is in the price_list.So we decide to create a function:
def find_price(item): if item in price_list: return 'The price for {} is {}'.format(item, price_list[item]) else: return 'The price for {} is not available'.format(item)>>> find_price('fish')'The price for fish is 8'>>> find_price('cauliflower')'The price for cauliflower is not available'
Smart. The if-else statement does exactly what we want it to do: return another value when the item is not available. But we query the dictionary twice and use two statements just to return almost the same thing. Can we do better? Is there a way that if the item is not in the list, a default value will be returned? Fortunately, there is a way to do that with Python’s dictionaries method called get()
def find_price(item): return 'The price for {} is {}'.format(item, price_list.get( item, 'not available'))
.get() looks up a key and returns default value with the non-existent key. The code definitely looks shorter, but does it performs like how we want?
>>> find_price('fish')'The price for fish is 8'>>> find_price('cauliflower')'The price for cauliflower is not available'
Neat!
Good question. Let’s tackle an example that completely does not involve a dictionary.
Imagine you want to create a function that returns a value for operation between 2 numbers. So this is what you come up with:
def operations(operator, x, y): if operator == 'add': return x + y elif operator == 'sub': return x - y elif operator == 'mul': return x * y elif operator == 'div': return x / y>>> operations('mul', 2, 8)16
You can utilize dictionaries and get() method to get a more elegant code:
def operations(operator, x, y): return { 'add': lambda: x+y, 'sub': lambda: x-y, 'mul': lambda: x*y, 'div': lambda: x/y, }.get(operator, lambda: 'Not a valid operation')()
Names of the operator become the keys and lambda efficiently condense the functions into the values of the dictionaries. get() returns a default value when no key is found. Let’s check our function:
>>> operations('mul', 2, 8)16>>> operations('unknown', 2, 8)'Not a valid operation'
Great! It works like how we want.
The alternative makes the code look cleaner. But if we want to use dictionary, we should consider the downsides of this switch. Every time we call operations() , it creates a temporary dictionary and lambdas for the opcode to loopup. This will slow down the performance of the code.
Thus, if we want to use dictionaries, we should consider creating the dictionary once before the function call. This act prevents the code from recreating the dictionary every time we lookup. This technique certainly won’t apply in every situation, but it will be beneficial to have another technique in your toolbox to choose from.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
medium.com
Bader, Dan. “Python Tricks.” 2017
|
[
{
"code": null,
"e": 497,
"s": 172,
"text": "You may have been frequently working with Python’s dictionaries. But have you unlocked the full capacity of the dictionary to create a more efficient code? If you didn’t know how to create an ordered dictionary, group multiple dictionaries into a single mapping, create a read-only dictionary, you could found out more here."
},
{
"code": null,
"e": 598,
"s": 497,
"text": "This article will focus on how to use Python’s dictionaries as an alternative to if-else statements."
},
{
"code": null,
"e": 660,
"s": 598,
"text": "Imagine we have the price list of items in the grocery store:"
},
{
"code": null,
"e": 710,
"s": 660,
"text": "price_list = {'fish': 8,'beef': 7,'broccoli': 3,}"
},
{
"code": null,
"e": 840,
"s": 710,
"text": "We want to print the price of the item but anticipate that not every item is in the price_list.So we decide to create a function:"
},
{
"code": null,
"e": 1150,
"s": 840,
"text": "def find_price(item): if item in price_list: return 'The price for {} is {}'.format(item, price_list[item]) else: return 'The price for {} is not available'.format(item)>>> find_price('fish')'The price for fish is 8'>>> find_price('cauliflower')'The price for cauliflower is not available'"
},
{
"code": null,
"e": 1553,
"s": 1150,
"text": "Smart. The if-else statement does exactly what we want it to do: return another value when the item is not available. But we query the dictionary twice and use two statements just to return almost the same thing. Can we do better? Is there a way that if the item is not in the list, a default value will be returned? Fortunately, there is a way to do that with Python’s dictionaries method called get()"
},
{
"code": null,
"e": 1670,
"s": 1553,
"text": "def find_price(item): return 'The price for {} is {}'.format(item, price_list.get( item, 'not available'))"
},
{
"code": null,
"e": 1819,
"s": 1670,
"text": ".get() looks up a key and returns default value with the non-existent key. The code definitely looks shorter, but does it performs like how we want?"
},
{
"code": null,
"e": 1940,
"s": 1819,
"text": ">>> find_price('fish')'The price for fish is 8'>>> find_price('cauliflower')'The price for cauliflower is not available'"
},
{
"code": null,
"e": 1946,
"s": 1940,
"text": "Neat!"
},
{
"code": null,
"e": 2032,
"s": 1946,
"text": "Good question. Let’s tackle an example that completely does not involve a dictionary."
},
{
"code": null,
"e": 2158,
"s": 2032,
"text": "Imagine you want to create a function that returns a value for operation between 2 numbers. So this is what you come up with:"
},
{
"code": null,
"e": 2405,
"s": 2158,
"text": "def operations(operator, x, y): if operator == 'add': return x + y elif operator == 'sub': return x - y elif operator == 'mul': return x * y elif operator == 'div': return x / y>>> operations('mul', 2, 8)16"
},
{
"code": null,
"e": 2479,
"s": 2405,
"text": "You can utilize dictionaries and get() method to get a more elegant code:"
},
{
"code": null,
"e": 2685,
"s": 2479,
"text": "def operations(operator, x, y): return { 'add': lambda: x+y, 'sub': lambda: x-y, 'mul': lambda: x*y, 'div': lambda: x/y, }.get(operator, lambda: 'Not a valid operation')()"
},
{
"code": null,
"e": 2884,
"s": 2685,
"text": "Names of the operator become the keys and lambda efficiently condense the functions into the values of the dictionaries. get() returns a default value when no key is found. Let’s check our function:"
},
{
"code": null,
"e": 2968,
"s": 2884,
"text": ">>> operations('mul', 2, 8)16>>> operations('unknown', 2, 8)'Not a valid operation'"
},
{
"code": null,
"e": 3002,
"s": 2968,
"text": "Great! It works like how we want."
},
{
"code": null,
"e": 3285,
"s": 3002,
"text": "The alternative makes the code look cleaner. But if we want to use dictionary, we should consider the downsides of this switch. Every time we call operations() , it creates a temporary dictionary and lambdas for the opcode to loopup. This will slow down the performance of the code."
},
{
"code": null,
"e": 3618,
"s": 3285,
"text": "Thus, if we want to use dictionaries, we should consider creating the dictionary once before the function call. This act prevents the code from recreating the dictionary every time we lookup. This technique certainly won’t apply in every situation, but it will be beneficial to have another technique in your toolbox to choose from."
},
{
"code": null,
"e": 3697,
"s": 3618,
"text": "Feel free to fork and play with the code for this article in this Github repo."
},
{
"code": null,
"e": 3857,
"s": 3697,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
},
{
"code": null,
"e": 4033,
"s": 3857,
"text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:"
},
{
"code": null,
"e": 4056,
"s": 4033,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4079,
"s": 4056,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4102,
"s": 4079,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4125,
"s": 4102,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4136,
"s": 4125,
"text": "medium.com"
}
] |
Convert English text into the Phonetics using Python - GeeksforGeeks
|
11 Oct, 2020
In this article, we are going to see how to convert English text into the International Phonetic Alphabet. We are going to use the eng-to-ipa module to convert into phonetic.
Installation: Run this code into your terminal.
pip install eng-to-ipa
Let’s understands this module step-by-step:
1. Import this module and use convert() method to convert a string into phonetics.
Syntax: eng_to_ipa.convert(str)
Parameter:
str: the text to be converted
Returns: IPA string
Python3
import eng_to_ipa as p p.convert("Hello Geeks")
Output:
'hɛˈloʊ giks'
2. Using ipa_list() instead of convert() it returns the list of each word as a list of all its possible transcriptions.
Syntax: eng_to_ipa.ipa_list(str)
Parameter:
str: the text to be converted
Return: list of all its possible transcriptions.
Python3
p.ipa_list("Yes i am geeks, How are you")
Output:
[[‘jɛs’], [‘aɪ’], [‘eɪɛm’, ‘æm’], [‘giks,’], [‘haʊ’], [‘ɑr’, ‘ər’], [‘ju’]]
3. The get_rhymes() methods return a list of rhymes for a word or set of words.
Syntax: eng_to_ipa.get_rhymes(str)
Parameter:
str: the text to be rhymed
Returns: list of rhymes for a word or set of words.
Python3
p.get_rhymes("Geeks")
Output:
['antiques',
'batiks',
'beeks',
"belgique's",
'bespeaks',
'boutiques',
'cheeks',
"creek's",
'creeks',
'critiques',
"deak's",
'eakes',...
......
..
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 24467,
"s": 24292,
"text": "In this article, we are going to see how to convert English text into the International Phonetic Alphabet. We are going to use the eng-to-ipa module to convert into phonetic."
},
{
"code": null,
"e": 24515,
"s": 24467,
"text": "Installation: Run this code into your terminal."
},
{
"code": null,
"e": 24541,
"s": 24515,
"text": "pip install eng-to-ipa \n\n"
},
{
"code": null,
"e": 24585,
"s": 24541,
"text": "Let’s understands this module step-by-step:"
},
{
"code": null,
"e": 24668,
"s": 24585,
"text": "1. Import this module and use convert() method to convert a string into phonetics."
},
{
"code": null,
"e": 24700,
"s": 24668,
"text": "Syntax: eng_to_ipa.convert(str)"
},
{
"code": null,
"e": 24711,
"s": 24700,
"text": "Parameter:"
},
{
"code": null,
"e": 24741,
"s": 24711,
"text": "str: the text to be converted"
},
{
"code": null,
"e": 24761,
"s": 24741,
"text": "Returns: IPA string"
},
{
"code": null,
"e": 24769,
"s": 24761,
"text": "Python3"
},
{
"code": "import eng_to_ipa as p p.convert(\"Hello Geeks\")",
"e": 24820,
"s": 24769,
"text": null
},
{
"code": null,
"e": 24828,
"s": 24820,
"text": "Output:"
},
{
"code": null,
"e": 24844,
"s": 24828,
"text": "'hɛˈloʊ giks'\n\n"
},
{
"code": null,
"e": 24964,
"s": 24844,
"text": "2. Using ipa_list() instead of convert() it returns the list of each word as a list of all its possible transcriptions."
},
{
"code": null,
"e": 24997,
"s": 24964,
"text": "Syntax: eng_to_ipa.ipa_list(str)"
},
{
"code": null,
"e": 25008,
"s": 24997,
"text": "Parameter:"
},
{
"code": null,
"e": 25038,
"s": 25008,
"text": "str: the text to be converted"
},
{
"code": null,
"e": 25087,
"s": 25038,
"text": "Return: list of all its possible transcriptions."
},
{
"code": null,
"e": 25095,
"s": 25087,
"text": "Python3"
},
{
"code": "p.ipa_list(\"Yes i am geeks, How are you\")",
"e": 25137,
"s": 25095,
"text": null
},
{
"code": null,
"e": 25145,
"s": 25137,
"text": "Output:"
},
{
"code": null,
"e": 25221,
"s": 25145,
"text": "[[‘jɛs’], [‘aɪ’], [‘eɪɛm’, ‘æm’], [‘giks,’], [‘haʊ’], [‘ɑr’, ‘ər’], [‘ju’]]"
},
{
"code": null,
"e": 25301,
"s": 25221,
"text": "3. The get_rhymes() methods return a list of rhymes for a word or set of words."
},
{
"code": null,
"e": 25336,
"s": 25301,
"text": "Syntax: eng_to_ipa.get_rhymes(str)"
},
{
"code": null,
"e": 25347,
"s": 25336,
"text": "Parameter:"
},
{
"code": null,
"e": 25374,
"s": 25347,
"text": "str: the text to be rhymed"
},
{
"code": null,
"e": 25426,
"s": 25374,
"text": "Returns: list of rhymes for a word or set of words."
},
{
"code": null,
"e": 25434,
"s": 25426,
"text": "Python3"
},
{
"code": "p.get_rhymes(\"Geeks\")",
"e": 25456,
"s": 25434,
"text": null
},
{
"code": null,
"e": 25464,
"s": 25456,
"text": "Output:"
},
{
"code": null,
"e": 25625,
"s": 25464,
"text": "['antiques',\n 'batiks',\n 'beeks',\n \"belgique's\",\n 'bespeaks',\n 'boutiques',\n 'cheeks',\n \"creek's\",\n 'creeks',\n 'critiques',\n \"deak's\",\n 'eakes',...\n ......\n ..\n"
},
{
"code": null,
"e": 25640,
"s": 25625,
"text": "python-utility"
},
{
"code": null,
"e": 25647,
"s": 25640,
"text": "Python"
},
{
"code": null,
"e": 25745,
"s": 25647,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25777,
"s": 25745,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25819,
"s": 25777,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25875,
"s": 25819,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25917,
"s": 25875,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25948,
"s": 25917,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25970,
"s": 25948,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26025,
"s": 25970,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26064,
"s": 26025,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26093,
"s": 26064,
"text": "Create a directory in Python"
}
] |
JavaScript Array reverse() Method
|
Javascript array reverse() method reverses the element of an array. The first array element becomes the last and the last becomes the first.
Its syntax is as follows −
array.reverse();
Returns the reversed single value of the array.
Try the following example.
<html>
<head>
<title>JavaScript Array reverse Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = [0, 1, 2, 3].reverse();
document.write("Reversed array is : " + arr );
</script>
</body>
</html>
Reversed array is : 3,2,1,0
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2607,
"s": 2466,
"text": "Javascript array reverse() method reverses the element of an array. The first array element becomes the last and the last becomes the first."
},
{
"code": null,
"e": 2634,
"s": 2607,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2652,
"s": 2634,
"text": "array.reverse();\n"
},
{
"code": null,
"e": 2700,
"s": 2652,
"text": "Returns the reversed single value of the array."
},
{
"code": null,
"e": 2727,
"s": 2700,
"text": "Try the following example."
},
{
"code": null,
"e": 3005,
"s": 2727,
"text": "<html>\n <head>\n <title>JavaScript Array reverse Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var arr = [0, 1, 2, 3].reverse();\n document.write(\"Reversed array is : \" + arr ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3035,
"s": 3005,
"text": "Reversed array is : 3,2,1,0 \n"
},
{
"code": null,
"e": 3070,
"s": 3035,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3084,
"s": 3070,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3118,
"s": 3084,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3132,
"s": 3118,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3167,
"s": 3132,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3184,
"s": 3167,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3219,
"s": 3184,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3236,
"s": 3219,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3269,
"s": 3236,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3297,
"s": 3269,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3331,
"s": 3297,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3359,
"s": 3331,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3366,
"s": 3359,
"text": " Print"
},
{
"code": null,
"e": 3377,
"s": 3366,
"text": " Add Notes"
}
] |
Golang | Deadlock and Default Case in Select Statement - GeeksforGeeks
|
03 Oct, 2019
In Go language, the select statement is just like a switch statement, but in the select statement, the case statement refers to communication, i.e. sent or receive operation on the channel.
Syntax:
select{
case SendOrReceive1: // Statement
case SendOrReceive2: // Statement
case SendOrReceive3: // Statement
.......
default: // Statement
In this article, we learn how the default case is used to avoid deadlock. But first, we learn what is a deadlock?
Deadlock: When you trying to read or write data from the channel but the channel does not have value. So, it blocks the current execution of the goroutine and passes the control to other goroutines, but if there is no other goroutine is available or other goroutines are sleeping due to this situation program will crash. This phenomenon is known as deadlock. As shown in the below example:
Example:
// Go program to illustrate// how deadlock arisespackage main // Main functionfunc main() { // Creating a channel // Here deadlock arises because // no goroutine is writing // to this channel so, the select // statement has been blocked forever c := make(chan int) select { case <-c: }}
Output:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
To avoid this situation we use a default case in the select statement. Or in other words, when the deadlock arises in the program, then default case of the select statement executed to avoid deadlock. As shown in the below example, we use a default case in the select statement to avoid deadlock.
Example:
// Go program to illustrate how to resolve// the deadlock problem using the default casepackage main import "fmt" // Main functionfunc main() { // Creating a channel c := make(chan int) select { case <-c: default: fmt.Println("!.. Default case..!") }}
Output:
!.. Default case..!
You are also allowed to use default case when the select statement has only nil channel. As shown in the below example, channel c is nil, so default case executed if here default case is not available, then the program will be blocked forever and deadlock arises.
Example:
// Go program to illustrate// the execution of default casepackage main import "fmt" // Main functionfunc main() { // Creating a channel var c chan int select { case x1 := <-c: fmt.Println("Value: ", x1) default: fmt.Println("Default case..!") }}
Output:
Default case..!
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Anonymous function in Go Language
time.Parse() Function in Golang With Examples
How to iterate over an Array using for loop in Golang?
Loops in Go Language
Strings in Golang
Class and Object in Golang
Structures in Golang
|
[
{
"code": null,
"e": 24460,
"s": 24432,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 24650,
"s": 24460,
"text": "In Go language, the select statement is just like a switch statement, but in the select statement, the case statement refers to communication, i.e. sent or receive operation on the channel."
},
{
"code": null,
"e": 24658,
"s": 24650,
"text": "Syntax:"
},
{
"code": null,
"e": 24800,
"s": 24658,
"text": "select{\n\ncase SendOrReceive1: // Statement\ncase SendOrReceive2: // Statement\ncase SendOrReceive3: // Statement\n.......\ndefault: // Statement\n"
},
{
"code": null,
"e": 24914,
"s": 24800,
"text": "In this article, we learn how the default case is used to avoid deadlock. But first, we learn what is a deadlock?"
},
{
"code": null,
"e": 25305,
"s": 24914,
"text": "Deadlock: When you trying to read or write data from the channel but the channel does not have value. So, it blocks the current execution of the goroutine and passes the control to other goroutines, but if there is no other goroutine is available or other goroutines are sleeping due to this situation program will crash. This phenomenon is known as deadlock. As shown in the below example:"
},
{
"code": null,
"e": 25314,
"s": 25305,
"text": "Example:"
},
{
"code": "// Go program to illustrate// how deadlock arisespackage main // Main functionfunc main() { // Creating a channel // Here deadlock arises because // no goroutine is writing // to this channel so, the select // statement has been blocked forever c := make(chan int) select { case <-c: }}",
"e": 25633,
"s": 25314,
"text": null
},
{
"code": null,
"e": 25641,
"s": 25633,
"text": "Output:"
},
{
"code": null,
"e": 25734,
"s": 25641,
"text": "fatal error: all goroutines are asleep - deadlock!\n\ngoroutine 1 [chan receive]:\nmain.main()\n"
},
{
"code": null,
"e": 26031,
"s": 25734,
"text": "To avoid this situation we use a default case in the select statement. Or in other words, when the deadlock arises in the program, then default case of the select statement executed to avoid deadlock. As shown in the below example, we use a default case in the select statement to avoid deadlock."
},
{
"code": null,
"e": 26040,
"s": 26031,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to resolve// the deadlock problem using the default casepackage main import \"fmt\" // Main functionfunc main() { // Creating a channel c := make(chan int) select { case <-c: default: fmt.Println(\"!.. Default case..!\") }}",
"e": 26321,
"s": 26040,
"text": null
},
{
"code": null,
"e": 26329,
"s": 26321,
"text": "Output:"
},
{
"code": null,
"e": 26349,
"s": 26329,
"text": "!.. Default case..!"
},
{
"code": null,
"e": 26613,
"s": 26349,
"text": "You are also allowed to use default case when the select statement has only nil channel. As shown in the below example, channel c is nil, so default case executed if here default case is not available, then the program will be blocked forever and deadlock arises."
},
{
"code": null,
"e": 26622,
"s": 26613,
"text": "Example:"
},
{
"code": "// Go program to illustrate// the execution of default casepackage main import \"fmt\" // Main functionfunc main() { // Creating a channel var c chan int select { case x1 := <-c: fmt.Println(\"Value: \", x1) default: fmt.Println(\"Default case..!\") }}",
"e": 26907,
"s": 26622,
"text": null
},
{
"code": null,
"e": 26915,
"s": 26907,
"text": "Output:"
},
{
"code": null,
"e": 26931,
"s": 26915,
"text": "Default case..!"
},
{
"code": null,
"e": 26938,
"s": 26931,
"text": "Golang"
},
{
"code": null,
"e": 26950,
"s": 26938,
"text": "Go Language"
},
{
"code": null,
"e": 27048,
"s": 26950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27077,
"s": 27048,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 27101,
"s": 27077,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 27126,
"s": 27101,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 27160,
"s": 27126,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 27206,
"s": 27160,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 27261,
"s": 27206,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 27282,
"s": 27261,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 27300,
"s": 27282,
"text": "Strings in Golang"
},
{
"code": null,
"e": 27327,
"s": 27300,
"text": "Class and Object in Golang"
}
] |
Consecutive sequenced numbers in a string - GeeksforGeeks
|
18 Jan, 2022
Given a string that contains only numeric digits, we need to check whether that strings contains numbers in consecutive sequential manner in increasing order. Note: Negative numbers are not considered part of this problem. So we consider that input only contains positive integer.Examples:
Input : str = "1234"
Output : Yes
1
Explanation :
There are 1, 2, 3, 4 which are
consecutive and in increasing order.
And the starting number is 1
Input : str = "91012"
Output : No
Explanation :
There are no such sequence in the
string.
Input : str = "99100"
Output : Yes
99
Explanation : The consecutive sequential
numbers are 99, 100
Input : str = "010203"
Output : NO
Explanation :
Although at first glance there seems to
be 01, 02, 03. But those wouldn't be
considered a number. 01 is not 1 it's 0, 1
Approach: An easily implementable and useful approach is to start taking one character at first (assuming that our string start with 1 digit number) and then form a new string by concatenating the next number until the length of new string is equal to original string. Perhaps an example may clarify : Lets take string “99100”
C++
Java
Python3
C#
Javascript
// CPP Program to check whether a string contains// consecutive sequential numbers or not#include <iostream>using namespace std; // function to check consecutive sequential numberint isConsecutive(string str){ // variable to store starting number int start; // length of the input string int length = str.size(); // find the number till half of the string for (int i = 0; i < length / 2; i++) { // new string containing the starting // substring of input string string new_str = str.substr(0, i + 1); // converting starting substring into number int num = atoi(new_str.c_str()); // backing up the starting number in start start = num; // while loop until the new_string is // smaller than input string while (new_str.size() < length) { // next number num++; // concatenate the next number new_str = new_str + to_string(num); } // check if new string becomes equal to // input string if (new_str == str) return start; } // if string doesn't contains consecutive numbers return -1;} // Driver's Codeint main(){ string str = "99100"; cout << "String: " << str << endl; int start = isConsecutive(str); if (start != -1) cout << "Yes \n" << start << endl; else cout << "No" << endl; string str1 = "121315"; cout << "\nString: " << str1 << endl; start = isConsecutive(str1); if (start != -1) cout << "Yes \n" << start << endl; else cout << "No" << endl; return 0;}
// Java Program to check whether a String contains// consecutive sequential numbers or notclass GFG{ // function to check consecutive sequential numberstatic int isConsecutive(String str){ // variable to store starting number int start; // length of the input String int length = str.length(); // find the number till half of the String for (int i = 0; i < length / 2; i++) { // new String containing the starting // substring of input String String new_str = str.substring(0, i + 1); // converting starting substring into number int num = Integer.parseInt(new_str); // backing up the starting number in start start = num; // while loop until the new_String is // smaller than input String while (new_str.length() < length) { // next number num++; // concatenate the next number new_str = new_str + String.valueOf(num); } // check if new String becomes equal to // input String if (new_str.equals(str)) return start; } // if String doesn't contains consecutive numbers return -1;} // Driver Codepublic static void main(String[] args){ String str = "99100"; System.out.println("String: " + str); int start = isConsecutive(str); if (start != -1) System.out.println("Yes \n" + start); else System.out.println("No"); String str1 = "121315"; System.out.println("\nString: " + str1); start = isConsecutive(str1); if (start != -1) System.out.println("Yes \n" + start); else System.out.println("No"); }} // This code contributed by Rajput-Ji
# Python Program to check whether a String contains# consecutive sequential numbers or not # function to check consecutive sequential numberdef isConsecutive(strs): # variable to store starting number start = 0; # length of the input String length = len(strs); # find the number till half of the String for i in range(length // 2): # new String containing the starting # substring of input String new_str = strs[0: i + 1]; # converting starting substring into number num = int(new_str); # backing up the starting number in start start = num; # while loop until the new_String is # smaller than input String while (len(new_str) < length): # next number num += 1; # concatenate the next number new_str = new_str + str(num); # check if new String becomes equal to # input String if (new_str==(strs)): return start; # if String doesn't contains consecutive numbers return -1; # Driver Codeif __name__ == '__main__': str0 = "99100"; print("String: " + str0); start = isConsecutive(str0); if (start != -1): print("Yes \n" , start); else: print("No"); str1 = "121315"; print("\nString: " , str1); start = isConsecutive(str1); if (start != -1): print("Yes \n" , start); else: print("No"); # This code is contributed by shikhasingrajput
// C# Program to check whether a String contains// consecutive sequential numbers or notusing System; class GFG{ // function to check consecutive sequential numberstatic int isConsecutive(String str){ // variable to store starting number int start; // length of the input String int length = str.Length; // find the number till half of the String for (int i = 0; i < length / 2; i++) { // new String containing the starting // substring of input String String new_str = str.Substring(0, i + 1); // converting starting substring into number int num = int.Parse(new_str); // backing up the starting number in start start = num; // while loop until the new_String is // smaller than input String while (new_str.Length < length) { // next number num++; // concatenate the next number new_str = new_str + String.Join("",num); } // check if new String becomes equal to // input String if (new_str.Equals(str)) return start; } // if String doesn't contains consecutive numbers return -1;} // Driver Codepublic static void Main(String[] args){ String str = "99100"; Console.WriteLine("String: " + str); int start = isConsecutive(str); if (start != -1) Console.WriteLine("Yes \n" + start); else Console.WriteLine("No"); String str1 = "121315"; Console.WriteLine("\nString: " + str1); start = isConsecutive(str1); if (start != -1) Console.WriteLine("Yes \n" + start); else Console.WriteLine("No"); }} // This code has been contributed by 29AjayKumar
<script> // JavaScript Program to check whether a String contains// consecutive sequential numbers or not // function to check consecutive sequential numberfunction isConsecutive(str){ // variable to store starting number let start; // length of the input String let length = str.length; // find the number till half of the String for (let i = 0; i < length / 2; i++) { // new String containing the starting // substring of input String let new_str = str.substring(0, i + 1); // converting starting substring into number let num = parseInt(new_str); // backing up the starting number in start start = num; // while loop until the new_String is // smaller than input String while (new_str.length < length) { // next number num++; // concatenate the next number new_str = new_str + (num).toString(); } // check if new String becomes equal to // input String if (new_str == (str)) return start; } // if String doesn't contains consecutive numbers return -1;} // Driver Codelet str = "99100";document.write("String: " + str+"<br>");let start = isConsecutive(str);if (start != -1) document.write("Yes <br>" + start+"<br>");else document.write("No<br>"); let str1 = "121315";document.write("<br>String: " + str1+"<br>");start = isConsecutive(str1);if (start != -1) document.write("Yes <br>" + start+"<br>");else document.write("No<br>"); // This code is contributed by rag2127 </script>
String: 99100
Yes
99
String: 121315
No
Rajput-Ji
29AjayKumar
rag2127
shikhasingrajput
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Naive algorithm for Pattern Searching
Vigenère Cipher
Hill Cipher
Count words in a given string
How to Append a Character to a String in C
Convert character array to string in C++
sprintf() in C
Program to count occurrence of a given character in a string
Converting Roman Numerals to Decimal lying between 1 to 3999
|
[
{
"code": null,
"e": 24854,
"s": 24826,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 25146,
"s": 24854,
"text": "Given a string that contains only numeric digits, we need to check whether that strings contains numbers in consecutive sequential manner in increasing order. Note: Negative numbers are not considered part of this problem. So we consider that input only contains positive integer.Examples: "
},
{
"code": null,
"e": 25688,
"s": 25146,
"text": "Input : str = \"1234\"\nOutput : Yes \n 1\nExplanation : \nThere are 1, 2, 3, 4 which are \nconsecutive and in increasing order.\nAnd the starting number is 1\n\nInput : str = \"91012\"\nOutput : No\nExplanation : \nThere are no such sequence in the\nstring. \n\nInput : str = \"99100\"\nOutput : Yes \n 99\nExplanation : The consecutive sequential \nnumbers are 99, 100\n\nInput : str = \"010203\"\nOutput : NO \nExplanation : \nAlthough at first glance there seems to\nbe 01, 02, 03. But those wouldn't be \nconsidered a number. 01 is not 1 it's 0, 1 "
},
{
"code": null,
"e": 26019,
"s": 25690,
"text": "Approach: An easily implementable and useful approach is to start taking one character at first (assuming that our string start with 1 digit number) and then form a new string by concatenating the next number until the length of new string is equal to original string. Perhaps an example may clarify : Lets take string “99100” "
},
{
"code": null,
"e": 26025,
"s": 26021,
"text": "C++"
},
{
"code": null,
"e": 26030,
"s": 26025,
"text": "Java"
},
{
"code": null,
"e": 26038,
"s": 26030,
"text": "Python3"
},
{
"code": null,
"e": 26041,
"s": 26038,
"text": "C#"
},
{
"code": null,
"e": 26052,
"s": 26041,
"text": "Javascript"
},
{
"code": "// CPP Program to check whether a string contains// consecutive sequential numbers or not#include <iostream>using namespace std; // function to check consecutive sequential numberint isConsecutive(string str){ // variable to store starting number int start; // length of the input string int length = str.size(); // find the number till half of the string for (int i = 0; i < length / 2; i++) { // new string containing the starting // substring of input string string new_str = str.substr(0, i + 1); // converting starting substring into number int num = atoi(new_str.c_str()); // backing up the starting number in start start = num; // while loop until the new_string is // smaller than input string while (new_str.size() < length) { // next number num++; // concatenate the next number new_str = new_str + to_string(num); } // check if new string becomes equal to // input string if (new_str == str) return start; } // if string doesn't contains consecutive numbers return -1;} // Driver's Codeint main(){ string str = \"99100\"; cout << \"String: \" << str << endl; int start = isConsecutive(str); if (start != -1) cout << \"Yes \\n\" << start << endl; else cout << \"No\" << endl; string str1 = \"121315\"; cout << \"\\nString: \" << str1 << endl; start = isConsecutive(str1); if (start != -1) cout << \"Yes \\n\" << start << endl; else cout << \"No\" << endl; return 0;}",
"e": 27662,
"s": 26052,
"text": null
},
{
"code": "// Java Program to check whether a String contains// consecutive sequential numbers or notclass GFG{ // function to check consecutive sequential numberstatic int isConsecutive(String str){ // variable to store starting number int start; // length of the input String int length = str.length(); // find the number till half of the String for (int i = 0; i < length / 2; i++) { // new String containing the starting // substring of input String String new_str = str.substring(0, i + 1); // converting starting substring into number int num = Integer.parseInt(new_str); // backing up the starting number in start start = num; // while loop until the new_String is // smaller than input String while (new_str.length() < length) { // next number num++; // concatenate the next number new_str = new_str + String.valueOf(num); } // check if new String becomes equal to // input String if (new_str.equals(str)) return start; } // if String doesn't contains consecutive numbers return -1;} // Driver Codepublic static void main(String[] args){ String str = \"99100\"; System.out.println(\"String: \" + str); int start = isConsecutive(str); if (start != -1) System.out.println(\"Yes \\n\" + start); else System.out.println(\"No\"); String str1 = \"121315\"; System.out.println(\"\\nString: \" + str1); start = isConsecutive(str1); if (start != -1) System.out.println(\"Yes \\n\" + start); else System.out.println(\"No\"); }} // This code contributed by Rajput-Ji",
"e": 29354,
"s": 27662,
"text": null
},
{
"code": "# Python Program to check whether a String contains# consecutive sequential numbers or not # function to check consecutive sequential numberdef isConsecutive(strs): # variable to store starting number start = 0; # length of the input String length = len(strs); # find the number till half of the String for i in range(length // 2): # new String containing the starting # substring of input String new_str = strs[0: i + 1]; # converting starting substring into number num = int(new_str); # backing up the starting number in start start = num; # while loop until the new_String is # smaller than input String while (len(new_str) < length): # next number num += 1; # concatenate the next number new_str = new_str + str(num); # check if new String becomes equal to # input String if (new_str==(strs)): return start; # if String doesn't contains consecutive numbers return -1; # Driver Codeif __name__ == '__main__': str0 = \"99100\"; print(\"String: \" + str0); start = isConsecutive(str0); if (start != -1): print(\"Yes \\n\" , start); else: print(\"No\"); str1 = \"121315\"; print(\"\\nString: \" , str1); start = isConsecutive(str1); if (start != -1): print(\"Yes \\n\" , start); else: print(\"No\"); # This code is contributed by shikhasingrajput",
"e": 30823,
"s": 29354,
"text": null
},
{
"code": "// C# Program to check whether a String contains// consecutive sequential numbers or notusing System; class GFG{ // function to check consecutive sequential numberstatic int isConsecutive(String str){ // variable to store starting number int start; // length of the input String int length = str.Length; // find the number till half of the String for (int i = 0; i < length / 2; i++) { // new String containing the starting // substring of input String String new_str = str.Substring(0, i + 1); // converting starting substring into number int num = int.Parse(new_str); // backing up the starting number in start start = num; // while loop until the new_String is // smaller than input String while (new_str.Length < length) { // next number num++; // concatenate the next number new_str = new_str + String.Join(\"\",num); } // check if new String becomes equal to // input String if (new_str.Equals(str)) return start; } // if String doesn't contains consecutive numbers return -1;} // Driver Codepublic static void Main(String[] args){ String str = \"99100\"; Console.WriteLine(\"String: \" + str); int start = isConsecutive(str); if (start != -1) Console.WriteLine(\"Yes \\n\" + start); else Console.WriteLine(\"No\"); String str1 = \"121315\"; Console.WriteLine(\"\\nString: \" + str1); start = isConsecutive(str1); if (start != -1) Console.WriteLine(\"Yes \\n\" + start); else Console.WriteLine(\"No\"); }} // This code has been contributed by 29AjayKumar",
"e": 32521,
"s": 30823,
"text": null
},
{
"code": "<script> // JavaScript Program to check whether a String contains// consecutive sequential numbers or not // function to check consecutive sequential numberfunction isConsecutive(str){ // variable to store starting number let start; // length of the input String let length = str.length; // find the number till half of the String for (let i = 0; i < length / 2; i++) { // new String containing the starting // substring of input String let new_str = str.substring(0, i + 1); // converting starting substring into number let num = parseInt(new_str); // backing up the starting number in start start = num; // while loop until the new_String is // smaller than input String while (new_str.length < length) { // next number num++; // concatenate the next number new_str = new_str + (num).toString(); } // check if new String becomes equal to // input String if (new_str == (str)) return start; } // if String doesn't contains consecutive numbers return -1;} // Driver Codelet str = \"99100\";document.write(\"String: \" + str+\"<br>\");let start = isConsecutive(str);if (start != -1) document.write(\"Yes <br>\" + start+\"<br>\");else document.write(\"No<br>\"); let str1 = \"121315\";document.write(\"<br>String: \" + str1+\"<br>\");start = isConsecutive(str1);if (start != -1) document.write(\"Yes <br>\" + start+\"<br>\");else document.write(\"No<br>\"); // This code is contributed by rag2127 </script>",
"e": 34132,
"s": 32521,
"text": null
},
{
"code": null,
"e": 34173,
"s": 34132,
"text": "String: 99100\nYes \n99\n\nString: 121315\nNo"
},
{
"code": null,
"e": 34185,
"s": 34175,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34197,
"s": 34185,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34205,
"s": 34197,
"text": "rag2127"
},
{
"code": null,
"e": 34222,
"s": 34205,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 34230,
"s": 34222,
"text": "Strings"
},
{
"code": null,
"e": 34238,
"s": 34230,
"text": "Strings"
},
{
"code": null,
"e": 34336,
"s": 34238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34381,
"s": 34336,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 34419,
"s": 34381,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 34436,
"s": 34419,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 34448,
"s": 34436,
"text": "Hill Cipher"
},
{
"code": null,
"e": 34478,
"s": 34448,
"text": "Count words in a given string"
},
{
"code": null,
"e": 34521,
"s": 34478,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 34562,
"s": 34521,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 34577,
"s": 34562,
"text": "sprintf() in C"
},
{
"code": null,
"e": 34638,
"s": 34577,
"text": "Program to count occurrence of a given character in a string"
}
] |
Few Tricky Programs in Java - GeeksforGeeks
|
25 Sep, 2017
Comments that execute :Till now, we were always taught “Comments do not Execute”. Let us see today “The comments that execute”Following is the code snippet:public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("comment executed"); }}Output:comment executedThe reason for this is that the Java compiler parses the unicode character \u000d as a new line and gets transformed into:public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("comment executed"); }}Named loops :// A Java program to demonstrate working of named loops.public class Testing { public static void main(String[] args) { loop1: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 3) break loop1; System.out.println("i = " + i + " j = " + j); } } }}Output:i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 0 j = 4
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 1 j = 4
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 2 j = 4You can also use continue to jump to start of the named loop.We can also use break (or continue) in a nested if-else with for loops in order to break several loops with if-else, so one can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level.
Comments that execute :Till now, we were always taught “Comments do not Execute”. Let us see today “The comments that execute”Following is the code snippet:public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("comment executed"); }}Output:comment executedThe reason for this is that the Java compiler parses the unicode character \u000d as a new line and gets transformed into:public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("comment executed"); }}
Till now, we were always taught “Comments do not Execute”. Let us see today “The comments that execute”
Following is the code snippet:
public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("comment executed"); }}
Output:
comment executed
The reason for this is that the Java compiler parses the unicode character \u000d as a new line and gets transformed into:
public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("comment executed"); }}
Named loops :// A Java program to demonstrate working of named loops.public class Testing { public static void main(String[] args) { loop1: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 3) break loop1; System.out.println("i = " + i + " j = " + j); } } }}Output:i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 0 j = 4
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 1 j = 4
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 2 j = 4You can also use continue to jump to start of the named loop.We can also use break (or continue) in a nested if-else with for loops in order to break several loops with if-else, so one can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level.
// A Java program to demonstrate working of named loops.public class Testing { public static void main(String[] args) { loop1: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 3) break loop1; System.out.println("i = " + i + " j = " + j); } } }}
Output:
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 0 j = 4
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 1 j = 4
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 2 j = 4
You can also use continue to jump to start of the named loop.
We can also use break (or continue) in a nested if-else with for loops in order to break several loops with if-else, so one can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level.
This article is contributed by Abhineet Nigam. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
java-puzzle
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
StringBuilder Class in Java with Examples
Strings in Java
|
[
{
"code": null,
"e": 23974,
"s": 23946,
"text": "\n25 Sep, 2017"
},
{
"code": null,
"e": 25483,
"s": 23974,
"text": "Comments that execute :Till now, we were always taught “Comments do not Execute”. Let us see today “The comments that execute”Following is the code snippet:public class Testing { public static void main(String[] args) { // the line below this gives an output // \\u000d System.out.println(\"comment executed\"); }}Output:comment executedThe reason for this is that the Java compiler parses the unicode character \\u000d as a new line and gets transformed into:public class Testing { public static void main(String[] args) { // the line below this gives an output // \\u000d System.out.println(\"comment executed\"); }}Named loops :// A Java program to demonstrate working of named loops.public class Testing { public static void main(String[] args) { loop1: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 3) break loop1; System.out.println(\"i = \" + i + \" j = \" + j); } } }}Output:i = 0 j = 0\ni = 0 j = 1\ni = 0 j = 2\ni = 0 j = 3\ni = 0 j = 4\ni = 1 j = 0\ni = 1 j = 1\ni = 1 j = 2\ni = 1 j = 3\ni = 1 j = 4\ni = 2 j = 0\ni = 2 j = 1\ni = 2 j = 2\ni = 2 j = 3\ni = 2 j = 4You can also use continue to jump to start of the named loop.We can also use break (or continue) in a nested if-else with for loops in order to break several loops with if-else, so one can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level."
},
{
"code": null,
"e": 26152,
"s": 25483,
"text": "Comments that execute :Till now, we were always taught “Comments do not Execute”. Let us see today “The comments that execute”Following is the code snippet:public class Testing { public static void main(String[] args) { // the line below this gives an output // \\u000d System.out.println(\"comment executed\"); }}Output:comment executedThe reason for this is that the Java compiler parses the unicode character \\u000d as a new line and gets transformed into:public class Testing { public static void main(String[] args) { // the line below this gives an output // \\u000d System.out.println(\"comment executed\"); }}"
},
{
"code": null,
"e": 26256,
"s": 26152,
"text": "Till now, we were always taught “Comments do not Execute”. Let us see today “The comments that execute”"
},
{
"code": null,
"e": 26287,
"s": 26256,
"text": "Following is the code snippet:"
},
{
"code": "public class Testing { public static void main(String[] args) { // the line below this gives an output // \\u000d System.out.println(\"comment executed\"); }}",
"e": 26470,
"s": 26287,
"text": null
},
{
"code": null,
"e": 26478,
"s": 26470,
"text": "Output:"
},
{
"code": null,
"e": 26495,
"s": 26478,
"text": "comment executed"
},
{
"code": null,
"e": 26618,
"s": 26495,
"text": "The reason for this is that the Java compiler parses the unicode character \\u000d as a new line and gets transformed into:"
},
{
"code": "public class Testing { public static void main(String[] args) { // the line below this gives an output // \\u000d System.out.println(\"comment executed\"); }}",
"e": 26804,
"s": 26618,
"text": null
},
{
"code": null,
"e": 27645,
"s": 26804,
"text": "Named loops :// A Java program to demonstrate working of named loops.public class Testing { public static void main(String[] args) { loop1: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 3) break loop1; System.out.println(\"i = \" + i + \" j = \" + j); } } }}Output:i = 0 j = 0\ni = 0 j = 1\ni = 0 j = 2\ni = 0 j = 3\ni = 0 j = 4\ni = 1 j = 0\ni = 1 j = 1\ni = 1 j = 2\ni = 1 j = 3\ni = 1 j = 4\ni = 2 j = 0\ni = 2 j = 1\ni = 2 j = 2\ni = 2 j = 3\ni = 2 j = 4You can also use continue to jump to start of the named loop.We can also use break (or continue) in a nested if-else with for loops in order to break several loops with if-else, so one can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level."
},
{
"code": "// A Java program to demonstrate working of named loops.public class Testing { public static void main(String[] args) { loop1: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 3) break loop1; System.out.println(\"i = \" + i + \" j = \" + j); } } }}",
"e": 27990,
"s": 27645,
"text": null
},
{
"code": null,
"e": 27998,
"s": 27990,
"text": "Output:"
},
{
"code": null,
"e": 28178,
"s": 27998,
"text": "i = 0 j = 0\ni = 0 j = 1\ni = 0 j = 2\ni = 0 j = 3\ni = 0 j = 4\ni = 1 j = 0\ni = 1 j = 1\ni = 1 j = 2\ni = 1 j = 3\ni = 1 j = 4\ni = 2 j = 0\ni = 2 j = 1\ni = 2 j = 2\ni = 2 j = 3\ni = 2 j = 4"
},
{
"code": null,
"e": 28240,
"s": 28178,
"text": "You can also use continue to jump to start of the named loop."
},
{
"code": null,
"e": 28477,
"s": 28240,
"text": "We can also use break (or continue) in a nested if-else with for loops in order to break several loops with if-else, so one can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level."
},
{
"code": null,
"e": 28745,
"s": 28477,
"text": "This article is contributed by Abhineet Nigam. 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": 28870,
"s": 28745,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28882,
"s": 28870,
"text": "java-puzzle"
},
{
"code": null,
"e": 28887,
"s": 28882,
"text": "Java"
},
{
"code": null,
"e": 28906,
"s": 28887,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28911,
"s": 28906,
"text": "Java"
},
{
"code": null,
"e": 29009,
"s": 28911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29018,
"s": 29009,
"text": "Comments"
},
{
"code": null,
"e": 29031,
"s": 29018,
"text": "Old Comments"
},
{
"code": null,
"e": 29077,
"s": 29031,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29098,
"s": 29077,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29113,
"s": 29098,
"text": "Stream In Java"
},
{
"code": null,
"e": 29130,
"s": 29113,
"text": "Generics in Java"
},
{
"code": null,
"e": 29149,
"s": 29130,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29192,
"s": 29149,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29221,
"s": 29192,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 29251,
"s": 29221,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29293,
"s": 29251,
"text": "StringBuilder Class in Java with Examples"
}
] |
KNIME - Quick Guide
|
Developing Machine Learning models is always considered very challenging due to its cryptic nature. Generally, to develop machine learning applications, you must be a good developer with an expertise in command-driven development. The introduction of KNIME has brought the development of Machine Learning models in the purview of a common man.
KNIME provides a graphical interface (a user friendly GUI) for the entire development. In KNIME, you simply have to define the workflow between the various predefined nodes provided in its repository. KNIME provides several predefined components called nodes for various tasks such as reading data, applying various ML algorithms, and visualizing data in various formats. Thus, for working with KNIME, no programming knowledge is required. Isn’t this exciting?
The upcoming chapters of this tutorial will teach you how to master the data analytics using several well-tested ML algorithms.
KNIME Analytics Platform is available for Windows, Linux and MacOS. In this chapter, let us look into the steps for installing the platform on the Mac. If you use Windows or Linux, just follow the installation instructions given on the KNIME download page. The binary installation for all three platforms is available at KNIME’s page.
Download the binary installation from the KNIME official site. Double click on the downloaded dmg file to start the installation. When the installation completes, just drag the KNIME icon to the Applications folder as seen here −
Double-click the KNIME icon to start the KNIME Analytics Platform. Initially, you will be asked to setup a workspace folder for saving your work. Your screen will look like the following −
You may set the selected folder as default and the next time you launch KNIME, it will not
show up this dialog again.
After a while, the KNIME platform will start on your desktop. This is the workbench where you would carry your analytics work. Let us now look at the various portions of the workbench.
When KNIME starts, you will see the following screen −
As has been marked in the screenshot, the workbench consists of several views. The views which are of immediate use to us are marked in the screenshot and listed below −
Workspace
Workspace
Outline
Outline
Nodes Repository
Nodes Repository
KNIME Explorer
KNIME Explorer
Console
Console
Description
Description
As we move ahead in this chapter, let us learn these views each in detail.
The most important view for us is the Workspace view. This is where you would create your machine learning model. The workspace view is highlighted in the screenshot below −
The screenshot shows an opened workspace. You will soon learn how to open an existing workspace.
Each workspace contains one or more nodes. You will learn the significance of these nodes later in the tutorial. The nodes are connected using arrows. Generally, the program flow is defined from left to right, though this is not required. You may freely move each node anywhere in the workspace. The connecting lines between the two would move appropriately to maintain the connection between the nodes. You may add/remove connections between nodes at any time. For each node a small description may be optionally added.
The workspace view may not be able to show you the entire workflow at a time. That is the reason, the outline view is provided.
The outline view shows a miniature view of the entire workspace. There is a zoom window inside this view that you can slide to see the different portions of the workflow in the Workspace view.
This is the next important view in the workbench. The Node repository lists the various nodes available for your analytics. The entire repository is nicely categorized based on the node functions. You will find categories such as −
IO
IO
Views
Views
Analytics
Analytics
Under each category you would find several options. Just expand each category view to see what you have there. Under the IO category, you will find nodes to read your data in various file formats, such as ARFF, CSV, PMML, XLS, etc.
Depending on your input source data format, you will select the appropriate node for reading your dataset.
By this time, probably you have understood the purpose of a node. A node defines a certain kind of functionality that you can visually include in your workflow.
The Analytics node defines the various machine learning algorithms, such as Bayes, Clustering, Decision Tree, Ensemble Learning, and so on.
The implementation of these various ML algorithms is provided in these nodes. To apply any algorithm in your analytics, simply pick up the desired node from the repository and add it to your workspace. Connect the output of the Data reader node to the input of this ML node and your workflow is created.
We suggest you to explore the various nodes available in the repository.
The next important view in the workbench is the Explorer view as shown in the screenshot below −
The first two categories list the workspaces defined on the KNIME server. The third option LOCAL is used for storing all the workspaces that you create on your local machine. Try expanding these tabs to see the various predefined workspaces. Especially, expand EXAMPLES tab.
KNIME provides several examples to get you started with the platform. In the next chapter, you will be using one of these examples to get yourself acquainted with the platform.
As the name indicates, the Console view provides a view of the various console messages while executing your workflow.
The Console view is useful in diagnosing the workflow and examining the analytics results.
The last important view that is of immediate relevance to us is the Description view. This view provides a description of a selected item in the workspace. A typical view is shown in the screenshot below −
The above view shows the description of a File Reader node. When you select the File Reader node in your workspace, you will see its description in this view. Clicking on any other node shows the description of the selected node. Thus, this view becomes very useful in the initial stages of learning when you do not precisely know the purpose of the various nodes in the workspace and/or the nodes repository.
Besides the above described views, the workbench has other views such as toolbar. The toolbar contains various icons that facilitate a quick action. The icons are enabled/disabled depending on the context. You can see the action that each icon performs by hovering mouse on it. The following screen shows the action taken by Configure icon.
The various views that you have seen so far can be turned on/off easily. Clicking the Close icon in the view will close the view. To reinstate the view, go to the View menu option and select the desired view. The selected view will be added to the workbench.
Now, as you have been acquainted with the workbench, I will show you how to run a workflow and study the analytics performed by it.
KNIME has provided several good workflows for ease of learning. In this chapter, we shall pick up one of the workflows provided in the installation to explain the various features and the power of analytics platform. We will use a simple classifier based on a Decision Tree for our study.
In the KNIME Explorer locate the following workflow −
LOCAL / Example Workflows / Basic Examples / Building a Simple Classifier
This is also shown in the screenshot below for your quick reference −
Double click on the selected item to open the workflow. Observe the Workspace view. You will see the workflow containing several nodes. The purpose of this workflow is to predict the income group from the democratic attributes of the adult data set taken from UCI Machine Learning Repository. The task of this ML model is to classify the people in a specific region as having income greater or lesser than 50K.
The Workspace view along with its outline is shown in the screenshot below −
Notice the presence of several nodes picked up from the Nodes repository and connected in a workflow by arrows. The connection indicates that the output of one node is fed to the input of the next node. Before we learn the functionality of each of the nodes in the workflow, let us first execute the entire workflow.
Before we look into the execution of the workflow, it is important to understand the status report of each node. Examine any node in the workflow. At the bottom of each node you would find a status indicator containing three circles. The Decision Tree Learner node is shown in the screenshot below −
The status indicator is red indicating that this node has not been executed so far. During the execution, the center circle which is yellow in color would light up. On successful execution, the last circle turns green. There are more indicators to give you the status information in case of errors. You will learn them when an error occurs in the processing.
Note that currently the indicators on all nodes are red indicating that no node is executed so far. To run all nodes, click on the following menu item −
Node → Execute All
After a while, you will find that each node status indicator has now turned green indicating that there are no errors.
In the next chapter, we will explore the functionality of the various nodes in the workflow.
If you check out the nodes in the workflow, you can see that it contains the following −
File Reader,
File Reader,
Color Manager
Color Manager
Partitioning
Partitioning
Decision Tree Learner
Decision Tree Learner
Decision Tree Predictor
Decision Tree Predictor
Score
Score
Interactive Table
Interactive Table
Scatter Plot
Scatter Plot
Statistics
Statistics
These are easily seen in the Outline view as shown here −
Each node provides a specific functionality in the workflow. We will now look into how to configure these nodes to meet up the desired functionality. Please note that we will discuss only those nodes that are relevant to us in the current context of exploring the workflow.
The File Reader node is depicted in the screenshot below −
There is some description at the top of the window that is provided by the creator of the workflow. It tells that this node reads the adult data set. The name of the file is adult.csv as seen from the description underneath the node symbol. The File Reader has two outputs - one goes to Color Manager node and the other one goes to Statistics node.
If you right click the File Manager, a popup menu would show up as follows −
The Configure menu option allows for the node configuration. The Execute menu runs the node. Note that if the node has already been run and if it is in a green state, this menu is disabled. Also, note the presence of Edit Note Description menu option. This allows you to write the description for your node.
Now, select the Configure menu option, it shows the screen containing the data from the adult.csv file as seen in the screenshot here −
When you execute this node, the data will be loaded in the memory. The entire data loading program code is hidden from the user. You can now appreciate the usefulness of such nodes - no coding required.
Our next node is the Color Manager.
Select the Color Manager node and go into its configuration by right clicking on it. A colors settings dialog would appear. Select the income column from the dropdown list.
Your screen would look like the following −
Notice the presence of two constraints. If the income is less than 50K, the datapoint will acquire green color and if it is more it gets red color. You will see the data point mappings when we look at the scatter plot later in this chapter.
In machine learning, we usually split the entire available data in two parts. The larger part is used in training the model, while the smaller portion is used for testing. There are different strategies used for partitioning the data.
To define the desired partitioning, right click on the Partitioning node and select the Configure option. You would see the following screen −
In the case, the system modeller has used the Relative (%) mode and the data is split in 80:20 ratio. While doing the split, the data points are picked up randomly. This ensures that your test data may not be biased. In case of Linear sampling, the remaining 20% data used for testing may not correctly represent the training data as it may be totally biased during its collection.
If you are sure that during data collection, the randomness is guaranteed, then you may select the linear sampling. Once your data is ready for training the model, feed it to the next node, which is the Decision Tree Learner.
The Decision Tree Learner node as the name suggests uses the training data and builds a model. Check out the configuration setting of this node, which is depicted in the screenshot below −
As you see the Class is income. Thus the tree would be built based on the income column and that is what we are trying to achieve in this model. We want a separation of people having income greater or lesser than 50K.
After this node runs successfully, your model would be ready for testing.
The Decision Tree Predictor node applies the developed model to the test data set and appends the model predictions.
The output of the predictor is fed to two different nodes - Scorer and Scatter Plot. Next, we will examine the output of prediction.
This node generates the confusion matrix. To view it, right click on the node. You will see the following popup menu −
Click the View: Confusion Matrix menu option and the matrix will pop up in a separate window as shown in the screenshot here −
It indicates that the accuracy of our developed model is 83.71%. If you are not satisfied with this, you may play around with other parameters in model building, especially, you may like to revisit and cleanse your data.
To see the scatter plot of the data distribution, right click on the Scatter Plot node and select the menu option Interactive View: Scatter Plot. You will see the following plot −
The plot gives the distribution of different income group people based on the threshold of 50K in two different colored dots - red and blue. These were the colors set in our Color Manager node. The distribution is relative to the age as plotted on the x-axis. You may select a different feature for x-axis by changing the configuration of the node.
The configuration dialog is shown here where we have selected the marital-status as a feature for x-axis.
This completes our discussion on the predefined model provided by KNIME. We suggest you to take up the other two nodes (Statistics and Interactive Table) in the model for your self-study.
Let us now move on to the most important part of the tutorial – creating your own model.
In this chapter, you will build your own machine learning model to categorize the plants based on a few observed features. We will use the well-known iris dataset from UCI Machine Learning Repository for this purpose. The dataset contains three different classes of plants. We will train our model to classify an unknown plant into one of these three classes.
We will start with creating a new workflow in KNIME for creating our machine learning models.
To create a new workflow, select the following menu option in the KNIME workbench.
File → New
You will see the following screen −
Select the New KNIME Workflow option and click on the Next button. On the next screen, you will be asked for the desired name for the workflow and the destination folder for saving it. Enter this information as desired and click Finish to create a new workspace.
A new workspace with the given name would be added to the Workspace view as seen here −
You will now add the various nodes in this workspace to create your model. Before, you add nodes, you have to download and prepare the iris dataset for our use.
Download the iris dataset from the UCI Machine Learning Repository site Download Iris Dataset. The downloaded iris.data file is in CSV format. We will make some changes in it to add the column names.
Open the downloaded file in your favorite text editor and add the following line at the beginning.
sepal length, petal length, sepal width, petal width, class
When our File Reader node reads this file, it will automatically take the above fields as column names.
Now, you will start adding various nodes.
Go to the Node Repository view, type “file” in the search box to locate the File Reader node. This is seen in the screenshot below −
Select and double click the File Reader to add the node into the workspace. Alternatively, you may use drag-n-drop feature to add the node into the workspace. After the node is added, you will have to configure it. Right click on the node and select the Configure menu option. You have done this in the earlier lesson.
The settings screen looks like the following after the datafile is loaded.
To load your dataset, click on the Browse button and select the location of your iris.data file. The node will load the contents of the file which are displayed in the lower portion of the configuration box. Once you are satisfied that the datafile is located properly and loaded, click on the OK button to close the configuration dialog.
You will now add some annotation to this node. Right click on the node and select New Workflow Annotation menu option. An annotation box would appear on the screen as shown in the screenshot here:
Click inside the box and add the following annotation −
Reads iris.data
Click anywhere outside the box to exit the edit mode. Resize and place the box around the node as desired. Finally, double click on the Node 1 text underneath the node to change this string to the following −
Loads data
At this point, your screen would look like the following −
We will now add a new node for partitioning our loaded dataset into training and testing.
In the Node Repository search window, type a few characters to locate the Partitioning node, as seen in the screenshot below −
Add the node to our workspace. Set its configuration as follows −
Relative (%) : 95
Draw Randomly
The following screenshot shows the configuration parameters.
Next, make the connection between the two nodes. To do so, click on the output of the File Reader node, keep the mouse button clicked, a rubber band line would appear, drag it to the input of Partitioning node, release the mouse button. A connection is now established between the two nodes.
Add the annotation, change the description, position the node and annotation view as desired. Your screen should look like the following at this stage −
Next, we will add the k-Means node.
Select the k-Means node from the repository and add it to the workspace. If you want to refresh your knowledge on k-Means algorithm, just look up its description in the description view of the workbench. This is shown in the screenshot below −
Incidentally, you may look up the description of different algorithms in the description window before taking a final decision on which one to use.
Open the configuration dialog for the node. We will use the defaults for all fields as shown here −
Click OK to accept the defaults and to close the dialog.
Set the annotation and description to the following −
Annotation: Classify clusters
Annotation: Classify clusters
Description:Perform clustering
Description:Perform clustering
Connect the top output of the Partitioning node to the input of k-Means node. Reposition your items and your screen should look like the following −
Next, we will add a Cluster Assigner node.
The Cluster Assigner assigns new data to an existing set of prototypes. It takes two inputs - the prototype model and the datatable containing the input data. Look up the node’s description in the description window which is depicted in the screenshot below −
Thus, for this node you have to make two connections −
The PMML Cluster Model output of Partitioning node → Prototypes Input of Cluster Assigner
The PMML Cluster Model output of Partitioning node → Prototypes Input of Cluster Assigner
Second partition output of Partitioning node → Input data of Cluster Assigner
Second partition output of Partitioning node → Input data of Cluster Assigner
These two connections are shown in the screenshot below −
The Cluster Assigner does not need any special configuration. Just accept the defaults.
Now, add some annotation and description to this node. Rearrange your nodes. Your screen should look like the following −
At this point, our clustering is completed. We need to visualize the output graphically. For this, we will add a scatter plot. We will set the colors and shapes for three classes differently in the scatter plot. Thus, we will filter the output of the k-Means node first through the Color Manager node and then through Shape Manager node.
Locate the Color Manager node in the repository. Add it to the workspace. Leave the configuration to its defaults. Note that you must open the configuration dialog and hit OK to accept the defaults. Set the description text for the node.
Make a connection from the output of k-Means to the input of Color Manager. Your screen would look like the following at this stage −
Locate the Shape Manager in the repository and add it to the workspace. Leave its configuration to the defaults. Like the previous one, you must open the configuration dialog and hit OK to set defaults. Establish the connection from the output of Color Manager to the input of Shape Manager. Set the description for the node.
Your screen should look like the following −
Now, you will be adding the last node in our model and that is the scatter plot.
Locate Scatter Plot node in the repository and add it to the workspace. Connect the output of Shape Manager to the input of Scatter Plot. Leave the configuration to defaults. Set the description.
Finally, add a group annotation to the recently added three nodes
Annotation: Visualization
Reposition the nodes as desired. Your screen should look like the following at this stage.
This completes the task of model building.
To test the model, execute the following menu options: Node → Execute All
If everything goes correct, the status signal at the bottom of each node would turn green. If not, you will need to look up the Console view for the errors, fix them up and re-run the workflow.
Now, you are ready to visualize the predicted output of the model. For this, right click the Scatter Plot node and select the following menu options: Interactive View: Scatter Plot
This is shown in the screenshot below −
You would see the scatter plot on the screen as shown here −
You can run through different visualizations by changing x- and y- axis. To do so, click on the settings menu at the top right corner of the scatter plot. A popup menu would appear as shown in the screenshot below −
You can set the various parameters for the plot on this screen to visualize the data from several aspects.
This completes our task of model building.
KNIME provides a graphical tool for building Machine Learning models. In this tutorial, you learned how to download and install KNIME on your machine.
You learned the various views provided in the KNIME workbench. KNIME provides several predefined workflows for your learning. We used one such workflow to learn the capabilities of KNIME. KNIME provides several pre-programmed nodes for reading data in various formats, analyzing data using several ML algorithms, and finally visualizing data in many different ways. Towards the end of the tutorial, you created your own model starting from scratch. We used the well-known iris dataset to classify the plants using k-Means algorithm.
You are now ready to use these techniques for your own analytics.
If you are a developer and would like to use the KNIME components in your programming applications, you will be glad to know that KNIME natively integrates with a wide range of programming languages such as Java, R, Python and many more.
27 Lectures
2 hours
Yoda Learning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2144,
"s": 1800,
"text": "Developing Machine Learning models is always considered very challenging due to its cryptic nature. Generally, to develop machine learning applications, you must be a good developer with an expertise in command-driven development. The introduction of KNIME has brought the development of Machine Learning models in the purview of a common man."
},
{
"code": null,
"e": 2605,
"s": 2144,
"text": "KNIME provides a graphical interface (a user friendly GUI) for the entire development. In KNIME, you simply have to define the workflow between the various predefined nodes provided in its repository. KNIME provides several predefined components called nodes for various tasks such as reading data, applying various ML algorithms, and visualizing data in various formats. Thus, for working with KNIME, no programming knowledge is required. Isn’t this exciting?"
},
{
"code": null,
"e": 2733,
"s": 2605,
"text": "The upcoming chapters of this tutorial will teach you how to master the data analytics using several well-tested ML algorithms."
},
{
"code": null,
"e": 3068,
"s": 2733,
"text": "KNIME Analytics Platform is available for Windows, Linux and MacOS. In this chapter, let us look into the steps for installing the platform on the Mac. If you use Windows or Linux, just follow the installation instructions given on the KNIME download page. The binary installation for all three platforms is available at KNIME’s page."
},
{
"code": null,
"e": 3298,
"s": 3068,
"text": "Download the binary installation from the KNIME official site. Double click on the downloaded dmg file to start the installation. When the installation completes, just drag the KNIME icon to the Applications folder as seen here −"
},
{
"code": null,
"e": 3487,
"s": 3298,
"text": "Double-click the KNIME icon to start the KNIME Analytics Platform. Initially, you will be asked to setup a workspace folder for saving your work. Your screen will look like the following −"
},
{
"code": null,
"e": 3578,
"s": 3487,
"text": "You may set the selected folder as default and the next time you launch KNIME, it will not"
},
{
"code": null,
"e": 3605,
"s": 3578,
"text": "show up this dialog again."
},
{
"code": null,
"e": 3790,
"s": 3605,
"text": "After a while, the KNIME platform will start on your desktop. This is the workbench where you would carry your analytics work. Let us now look at the various portions of the workbench."
},
{
"code": null,
"e": 3845,
"s": 3790,
"text": "When KNIME starts, you will see the following screen −"
},
{
"code": null,
"e": 4015,
"s": 3845,
"text": "As has been marked in the screenshot, the workbench consists of several views. The views which are of immediate use to us are marked in the screenshot and listed below −"
},
{
"code": null,
"e": 4025,
"s": 4015,
"text": "Workspace"
},
{
"code": null,
"e": 4035,
"s": 4025,
"text": "Workspace"
},
{
"code": null,
"e": 4043,
"s": 4035,
"text": "Outline"
},
{
"code": null,
"e": 4051,
"s": 4043,
"text": "Outline"
},
{
"code": null,
"e": 4068,
"s": 4051,
"text": "Nodes Repository"
},
{
"code": null,
"e": 4085,
"s": 4068,
"text": "Nodes Repository"
},
{
"code": null,
"e": 4100,
"s": 4085,
"text": "KNIME Explorer"
},
{
"code": null,
"e": 4115,
"s": 4100,
"text": "KNIME Explorer"
},
{
"code": null,
"e": 4123,
"s": 4115,
"text": "Console"
},
{
"code": null,
"e": 4131,
"s": 4123,
"text": "Console"
},
{
"code": null,
"e": 4143,
"s": 4131,
"text": "Description"
},
{
"code": null,
"e": 4155,
"s": 4143,
"text": "Description"
},
{
"code": null,
"e": 4230,
"s": 4155,
"text": "As we move ahead in this chapter, let us learn these views each in detail."
},
{
"code": null,
"e": 4404,
"s": 4230,
"text": "The most important view for us is the Workspace view. This is where you would create your machine learning model. The workspace view is highlighted in the screenshot below −"
},
{
"code": null,
"e": 4501,
"s": 4404,
"text": "The screenshot shows an opened workspace. You will soon learn how to open an existing workspace."
},
{
"code": null,
"e": 5022,
"s": 4501,
"text": "Each workspace contains one or more nodes. You will learn the significance of these nodes later in the tutorial. The nodes are connected using arrows. Generally, the program flow is defined from left to right, though this is not required. You may freely move each node anywhere in the workspace. The connecting lines between the two would move appropriately to maintain the connection between the nodes. You may add/remove connections between nodes at any time. For each node a small description may be optionally added."
},
{
"code": null,
"e": 5150,
"s": 5022,
"text": "The workspace view may not be able to show you the entire workflow at a time. That is the reason, the outline view is provided."
},
{
"code": null,
"e": 5343,
"s": 5150,
"text": "The outline view shows a miniature view of the entire workspace. There is a zoom window inside this view that you can slide to see the different portions of the workflow in the Workspace view."
},
{
"code": null,
"e": 5575,
"s": 5343,
"text": "This is the next important view in the workbench. The Node repository lists the various nodes available for your analytics. The entire repository is nicely categorized based on the node functions. You will find categories such as −"
},
{
"code": null,
"e": 5578,
"s": 5575,
"text": "IO"
},
{
"code": null,
"e": 5581,
"s": 5578,
"text": "IO"
},
{
"code": null,
"e": 5587,
"s": 5581,
"text": "Views"
},
{
"code": null,
"e": 5593,
"s": 5587,
"text": "Views"
},
{
"code": null,
"e": 5603,
"s": 5593,
"text": "Analytics"
},
{
"code": null,
"e": 5613,
"s": 5603,
"text": "Analytics"
},
{
"code": null,
"e": 5845,
"s": 5613,
"text": "Under each category you would find several options. Just expand each category view to see what you have there. Under the IO category, you will find nodes to read your data in various file formats, such as ARFF, CSV, PMML, XLS, etc."
},
{
"code": null,
"e": 5952,
"s": 5845,
"text": "Depending on your input source data format, you will select the appropriate node for reading your dataset."
},
{
"code": null,
"e": 6113,
"s": 5952,
"text": "By this time, probably you have understood the purpose of a node. A node defines a certain kind of functionality that you can visually include in your workflow."
},
{
"code": null,
"e": 6253,
"s": 6113,
"text": "The Analytics node defines the various machine learning algorithms, such as Bayes, Clustering, Decision Tree, Ensemble Learning, and so on."
},
{
"code": null,
"e": 6557,
"s": 6253,
"text": "The implementation of these various ML algorithms is provided in these nodes. To apply any algorithm in your analytics, simply pick up the desired node from the repository and add it to your workspace. Connect the output of the Data reader node to the input of this ML node and your workflow is created."
},
{
"code": null,
"e": 6630,
"s": 6557,
"text": "We suggest you to explore the various nodes available in the repository."
},
{
"code": null,
"e": 6727,
"s": 6630,
"text": "The next important view in the workbench is the Explorer view as shown in the screenshot below −"
},
{
"code": null,
"e": 7002,
"s": 6727,
"text": "The first two categories list the workspaces defined on the KNIME server. The third option LOCAL is used for storing all the workspaces that you create on your local machine. Try expanding these tabs to see the various predefined workspaces. Especially, expand EXAMPLES tab."
},
{
"code": null,
"e": 7179,
"s": 7002,
"text": "KNIME provides several examples to get you started with the platform. In the next chapter, you will be using one of these examples to get yourself acquainted with the platform."
},
{
"code": null,
"e": 7298,
"s": 7179,
"text": "As the name indicates, the Console view provides a view of the various console messages while executing your workflow."
},
{
"code": null,
"e": 7389,
"s": 7298,
"text": "The Console view is useful in diagnosing the workflow and examining the analytics results."
},
{
"code": null,
"e": 7595,
"s": 7389,
"text": "The last important view that is of immediate relevance to us is the Description view. This view provides a description of a selected item in the workspace. A typical view is shown in the screenshot below −"
},
{
"code": null,
"e": 8005,
"s": 7595,
"text": "The above view shows the description of a File Reader node. When you select the File Reader node in your workspace, you will see its description in this view. Clicking on any other node shows the description of the selected node. Thus, this view becomes very useful in the initial stages of learning when you do not precisely know the purpose of the various nodes in the workspace and/or the nodes repository."
},
{
"code": null,
"e": 8346,
"s": 8005,
"text": "Besides the above described views, the workbench has other views such as toolbar. The toolbar contains various icons that facilitate a quick action. The icons are enabled/disabled depending on the context. You can see the action that each icon performs by hovering mouse on it. The following screen shows the action taken by Configure icon."
},
{
"code": null,
"e": 8605,
"s": 8346,
"text": "The various views that you have seen so far can be turned on/off easily. Clicking the Close icon in the view will close the view. To reinstate the view, go to the View menu option and select the desired view. The selected view will be added to the workbench."
},
{
"code": null,
"e": 8737,
"s": 8605,
"text": "Now, as you have been acquainted with the workbench, I will show you how to run a workflow and study the analytics performed by it."
},
{
"code": null,
"e": 9026,
"s": 8737,
"text": "KNIME has provided several good workflows for ease of learning. In this chapter, we shall pick up one of the workflows provided in the installation to explain the various features and the power of analytics platform. We will use a simple classifier based on a Decision Tree for our study."
},
{
"code": null,
"e": 9080,
"s": 9026,
"text": "In the KNIME Explorer locate the following workflow −"
},
{
"code": null,
"e": 9155,
"s": 9080,
"text": "LOCAL / Example Workflows / Basic Examples / Building a Simple Classifier\n"
},
{
"code": null,
"e": 9225,
"s": 9155,
"text": "This is also shown in the screenshot below for your quick reference −"
},
{
"code": null,
"e": 9636,
"s": 9225,
"text": "Double click on the selected item to open the workflow. Observe the Workspace view. You will see the workflow containing several nodes. The purpose of this workflow is to predict the income group from the democratic attributes of the adult data set taken from UCI Machine Learning Repository. The task of this ML model is to classify the people in a specific region as having income greater or lesser than 50K."
},
{
"code": null,
"e": 9713,
"s": 9636,
"text": "The Workspace view along with its outline is shown in the screenshot below −"
},
{
"code": null,
"e": 10030,
"s": 9713,
"text": "Notice the presence of several nodes picked up from the Nodes repository and connected in a workflow by arrows. The connection indicates that the output of one node is fed to the input of the next node. Before we learn the functionality of each of the nodes in the workflow, let us first execute the entire workflow."
},
{
"code": null,
"e": 10330,
"s": 10030,
"text": "Before we look into the execution of the workflow, it is important to understand the status report of each node. Examine any node in the workflow. At the bottom of each node you would find a status indicator containing three circles. The Decision Tree Learner node is shown in the screenshot below −"
},
{
"code": null,
"e": 10689,
"s": 10330,
"text": "The status indicator is red indicating that this node has not been executed so far. During the execution, the center circle which is yellow in color would light up. On successful execution, the last circle turns green. There are more indicators to give you the status information in case of errors. You will learn them when an error occurs in the processing."
},
{
"code": null,
"e": 10842,
"s": 10689,
"text": "Note that currently the indicators on all nodes are red indicating that no node is executed so far. To run all nodes, click on the following menu item −"
},
{
"code": null,
"e": 10862,
"s": 10842,
"text": "Node → Execute All\n"
},
{
"code": null,
"e": 10981,
"s": 10862,
"text": "After a while, you will find that each node status indicator has now turned green indicating that there are no errors."
},
{
"code": null,
"e": 11074,
"s": 10981,
"text": "In the next chapter, we will explore the functionality of the various nodes in the workflow."
},
{
"code": null,
"e": 11163,
"s": 11074,
"text": "If you check out the nodes in the workflow, you can see that it contains the following −"
},
{
"code": null,
"e": 11176,
"s": 11163,
"text": "File Reader,"
},
{
"code": null,
"e": 11189,
"s": 11176,
"text": "File Reader,"
},
{
"code": null,
"e": 11203,
"s": 11189,
"text": "Color Manager"
},
{
"code": null,
"e": 11217,
"s": 11203,
"text": "Color Manager"
},
{
"code": null,
"e": 11230,
"s": 11217,
"text": "Partitioning"
},
{
"code": null,
"e": 11243,
"s": 11230,
"text": "Partitioning"
},
{
"code": null,
"e": 11265,
"s": 11243,
"text": "Decision Tree Learner"
},
{
"code": null,
"e": 11287,
"s": 11265,
"text": "Decision Tree Learner"
},
{
"code": null,
"e": 11311,
"s": 11287,
"text": "Decision Tree Predictor"
},
{
"code": null,
"e": 11335,
"s": 11311,
"text": "Decision Tree Predictor"
},
{
"code": null,
"e": 11341,
"s": 11335,
"text": "Score"
},
{
"code": null,
"e": 11347,
"s": 11341,
"text": "Score"
},
{
"code": null,
"e": 11365,
"s": 11347,
"text": "Interactive Table"
},
{
"code": null,
"e": 11383,
"s": 11365,
"text": "Interactive Table"
},
{
"code": null,
"e": 11396,
"s": 11383,
"text": "Scatter Plot"
},
{
"code": null,
"e": 11409,
"s": 11396,
"text": "Scatter Plot"
},
{
"code": null,
"e": 11420,
"s": 11409,
"text": "Statistics"
},
{
"code": null,
"e": 11431,
"s": 11420,
"text": "Statistics"
},
{
"code": null,
"e": 11489,
"s": 11431,
"text": "These are easily seen in the Outline view as shown here −"
},
{
"code": null,
"e": 11763,
"s": 11489,
"text": "Each node provides a specific functionality in the workflow. We will now look into how to configure these nodes to meet up the desired functionality. Please note that we will discuss only those nodes that are relevant to us in the current context of exploring the workflow."
},
{
"code": null,
"e": 11822,
"s": 11763,
"text": "The File Reader node is depicted in the screenshot below −"
},
{
"code": null,
"e": 12171,
"s": 11822,
"text": "There is some description at the top of the window that is provided by the creator of the workflow. It tells that this node reads the adult data set. The name of the file is adult.csv as seen from the description underneath the node symbol. The File Reader has two outputs - one goes to Color Manager node and the other one goes to Statistics node."
},
{
"code": null,
"e": 12248,
"s": 12171,
"text": "If you right click the File Manager, a popup menu would show up as follows −"
},
{
"code": null,
"e": 12556,
"s": 12248,
"text": "The Configure menu option allows for the node configuration. The Execute menu runs the node. Note that if the node has already been run and if it is in a green state, this menu is disabled. Also, note the presence of Edit Note Description menu option. This allows you to write the description for your node."
},
{
"code": null,
"e": 12692,
"s": 12556,
"text": "Now, select the Configure menu option, it shows the screen containing the data from the adult.csv file as seen in the screenshot here −"
},
{
"code": null,
"e": 12895,
"s": 12692,
"text": "When you execute this node, the data will be loaded in the memory. The entire data loading program code is hidden from the user. You can now appreciate the usefulness of such nodes - no coding required."
},
{
"code": null,
"e": 12931,
"s": 12895,
"text": "Our next node is the Color Manager."
},
{
"code": null,
"e": 13104,
"s": 12931,
"text": "Select the Color Manager node and go into its configuration by right clicking on it. A colors settings dialog would appear. Select the income column from the dropdown list."
},
{
"code": null,
"e": 13148,
"s": 13104,
"text": "Your screen would look like the following −"
},
{
"code": null,
"e": 13389,
"s": 13148,
"text": "Notice the presence of two constraints. If the income is less than 50K, the datapoint will acquire green color and if it is more it gets red color. You will see the data point mappings when we look at the scatter plot later in this chapter."
},
{
"code": null,
"e": 13624,
"s": 13389,
"text": "In machine learning, we usually split the entire available data in two parts. The larger part is used in training the model, while the smaller portion is used for testing. There are different strategies used for partitioning the data."
},
{
"code": null,
"e": 13767,
"s": 13624,
"text": "To define the desired partitioning, right click on the Partitioning node and select the Configure option. You would see the following screen −"
},
{
"code": null,
"e": 14149,
"s": 13767,
"text": "In the case, the system modeller has used the Relative (%) mode and the data is split in 80:20 ratio. While doing the split, the data points are picked up randomly. This ensures that your test data may not be biased. In case of Linear sampling, the remaining 20% data used for testing may not correctly represent the training data as it may be totally biased during its collection."
},
{
"code": null,
"e": 14375,
"s": 14149,
"text": "If you are sure that during data collection, the randomness is guaranteed, then you may select the linear sampling. Once your data is ready for training the model, feed it to the next node, which is the Decision Tree Learner."
},
{
"code": null,
"e": 14564,
"s": 14375,
"text": "The Decision Tree Learner node as the name suggests uses the training data and builds a model. Check out the configuration setting of this node, which is depicted in the screenshot below −"
},
{
"code": null,
"e": 14782,
"s": 14564,
"text": "As you see the Class is income. Thus the tree would be built based on the income column and that is what we are trying to achieve in this model. We want a separation of people having income greater or lesser than 50K."
},
{
"code": null,
"e": 14856,
"s": 14782,
"text": "After this node runs successfully, your model would be ready for testing."
},
{
"code": null,
"e": 14973,
"s": 14856,
"text": "The Decision Tree Predictor node applies the developed model to the test data set and appends the model predictions."
},
{
"code": null,
"e": 15106,
"s": 14973,
"text": "The output of the predictor is fed to two different nodes - Scorer and Scatter Plot. Next, we will examine the output of prediction."
},
{
"code": null,
"e": 15225,
"s": 15106,
"text": "This node generates the confusion matrix. To view it, right click on the node. You will see the following popup menu −"
},
{
"code": null,
"e": 15352,
"s": 15225,
"text": "Click the View: Confusion Matrix menu option and the matrix will pop up in a separate window as shown in the screenshot here −"
},
{
"code": null,
"e": 15573,
"s": 15352,
"text": "It indicates that the accuracy of our developed model is 83.71%. If you are not satisfied with this, you may play around with other parameters in model building, especially, you may like to revisit and cleanse your data."
},
{
"code": null,
"e": 15753,
"s": 15573,
"text": "To see the scatter plot of the data distribution, right click on the Scatter Plot node and select the menu option Interactive View: Scatter Plot. You will see the following plot −"
},
{
"code": null,
"e": 16102,
"s": 15753,
"text": "The plot gives the distribution of different income group people based on the threshold of 50K in two different colored dots - red and blue. These were the colors set in our Color Manager node. The distribution is relative to the age as plotted on the x-axis. You may select a different feature for x-axis by changing the configuration of the node."
},
{
"code": null,
"e": 16208,
"s": 16102,
"text": "The configuration dialog is shown here where we have selected the marital-status as a feature for x-axis."
},
{
"code": null,
"e": 16396,
"s": 16208,
"text": "This completes our discussion on the predefined model provided by KNIME. We suggest you to take up the other two nodes (Statistics and Interactive Table) in the model for your self-study."
},
{
"code": null,
"e": 16485,
"s": 16396,
"text": "Let us now move on to the most important part of the tutorial – creating your own model."
},
{
"code": null,
"e": 16845,
"s": 16485,
"text": "In this chapter, you will build your own machine learning model to categorize the plants based on a few observed features. We will use the well-known iris dataset from UCI Machine Learning Repository for this purpose. The dataset contains three different classes of plants. We will train our model to classify an unknown plant into one of these three classes."
},
{
"code": null,
"e": 16939,
"s": 16845,
"text": "We will start with creating a new workflow in KNIME for creating our machine learning models."
},
{
"code": null,
"e": 17022,
"s": 16939,
"text": "To create a new workflow, select the following menu option in the KNIME workbench."
},
{
"code": null,
"e": 17034,
"s": 17022,
"text": "File → New\n"
},
{
"code": null,
"e": 17070,
"s": 17034,
"text": "You will see the following screen −"
},
{
"code": null,
"e": 17333,
"s": 17070,
"text": "Select the New KNIME Workflow option and click on the Next button. On the next screen, you will be asked for the desired name for the workflow and the destination folder for saving it. Enter this information as desired and click Finish to create a new workspace."
},
{
"code": null,
"e": 17421,
"s": 17333,
"text": "A new workspace with the given name would be added to the Workspace view as seen here −"
},
{
"code": null,
"e": 17582,
"s": 17421,
"text": "You will now add the various nodes in this workspace to create your model. Before, you add nodes, you have to download and prepare the iris dataset for our use."
},
{
"code": null,
"e": 17782,
"s": 17582,
"text": "Download the iris dataset from the UCI Machine Learning Repository site Download Iris Dataset. The downloaded iris.data file is in CSV format. We will make some changes in it to add the column names."
},
{
"code": null,
"e": 17881,
"s": 17782,
"text": "Open the downloaded file in your favorite text editor and add the following line at the beginning."
},
{
"code": null,
"e": 17942,
"s": 17881,
"text": "sepal length, petal length, sepal width, petal width, class\n"
},
{
"code": null,
"e": 18046,
"s": 17942,
"text": "When our File Reader node reads this file, it will automatically take the above fields as column names."
},
{
"code": null,
"e": 18088,
"s": 18046,
"text": "Now, you will start adding various nodes."
},
{
"code": null,
"e": 18221,
"s": 18088,
"text": "Go to the Node Repository view, type “file” in the search box to locate the File Reader node. This is seen in the screenshot below −"
},
{
"code": null,
"e": 18540,
"s": 18221,
"text": "Select and double click the File Reader to add the node into the workspace. Alternatively, you may use drag-n-drop feature to add the node into the workspace. After the node is added, you will have to configure it. Right click on the node and select the Configure menu option. You have done this in the earlier lesson."
},
{
"code": null,
"e": 18615,
"s": 18540,
"text": "The settings screen looks like the following after the datafile is loaded."
},
{
"code": null,
"e": 18954,
"s": 18615,
"text": "To load your dataset, click on the Browse button and select the location of your iris.data file. The node will load the contents of the file which are displayed in the lower portion of the configuration box. Once you are satisfied that the datafile is located properly and loaded, click on the OK button to close the configuration dialog."
},
{
"code": null,
"e": 19151,
"s": 18954,
"text": "You will now add some annotation to this node. Right click on the node and select New Workflow Annotation menu option. An annotation box would appear on the screen as shown in the screenshot here:"
},
{
"code": null,
"e": 19207,
"s": 19151,
"text": "Click inside the box and add the following annotation −"
},
{
"code": null,
"e": 19224,
"s": 19207,
"text": "Reads iris.data\n"
},
{
"code": null,
"e": 19433,
"s": 19224,
"text": "Click anywhere outside the box to exit the edit mode. Resize and place the box around the node as desired. Finally, double click on the Node 1 text underneath the node to change this string to the following −"
},
{
"code": null,
"e": 19445,
"s": 19433,
"text": "Loads data\n"
},
{
"code": null,
"e": 19504,
"s": 19445,
"text": "At this point, your screen would look like the following −"
},
{
"code": null,
"e": 19594,
"s": 19504,
"text": "We will now add a new node for partitioning our loaded dataset into training and testing."
},
{
"code": null,
"e": 19721,
"s": 19594,
"text": "In the Node Repository search window, type a few characters to locate the Partitioning node, as seen in the screenshot below −"
},
{
"code": null,
"e": 19787,
"s": 19721,
"text": "Add the node to our workspace. Set its configuration as follows −"
},
{
"code": null,
"e": 19820,
"s": 19787,
"text": "Relative (%) : 95\nDraw Randomly\n"
},
{
"code": null,
"e": 19881,
"s": 19820,
"text": "The following screenshot shows the configuration parameters."
},
{
"code": null,
"e": 20173,
"s": 19881,
"text": "Next, make the connection between the two nodes. To do so, click on the output of the File Reader node, keep the mouse button clicked, a rubber band line would appear, drag it to the input of Partitioning node, release the mouse button. A connection is now established between the two nodes."
},
{
"code": null,
"e": 20326,
"s": 20173,
"text": "Add the annotation, change the description, position the node and annotation view as desired. Your screen should look like the following at this stage −"
},
{
"code": null,
"e": 20362,
"s": 20326,
"text": "Next, we will add the k-Means node."
},
{
"code": null,
"e": 20606,
"s": 20362,
"text": "Select the k-Means node from the repository and add it to the workspace. If you want to refresh your knowledge on k-Means algorithm, just look up its description in the description view of the workbench. This is shown in the screenshot below −"
},
{
"code": null,
"e": 20754,
"s": 20606,
"text": "Incidentally, you may look up the description of different algorithms in the description window before taking a final decision on which one to use."
},
{
"code": null,
"e": 20854,
"s": 20754,
"text": "Open the configuration dialog for the node. We will use the defaults for all fields as shown here −"
},
{
"code": null,
"e": 20911,
"s": 20854,
"text": "Click OK to accept the defaults and to close the dialog."
},
{
"code": null,
"e": 20965,
"s": 20911,
"text": "Set the annotation and description to the following −"
},
{
"code": null,
"e": 20995,
"s": 20965,
"text": "Annotation: Classify clusters"
},
{
"code": null,
"e": 21025,
"s": 20995,
"text": "Annotation: Classify clusters"
},
{
"code": null,
"e": 21056,
"s": 21025,
"text": "Description:Perform clustering"
},
{
"code": null,
"e": 21087,
"s": 21056,
"text": "Description:Perform clustering"
},
{
"code": null,
"e": 21236,
"s": 21087,
"text": "Connect the top output of the Partitioning node to the input of k-Means node. Reposition your items and your screen should look like the following −"
},
{
"code": null,
"e": 21279,
"s": 21236,
"text": "Next, we will add a Cluster Assigner node."
},
{
"code": null,
"e": 21539,
"s": 21279,
"text": "The Cluster Assigner assigns new data to an existing set of prototypes. It takes two inputs - the prototype model and the datatable containing the input data. Look up the node’s description in the description window which is depicted in the screenshot below −"
},
{
"code": null,
"e": 21594,
"s": 21539,
"text": "Thus, for this node you have to make two connections −"
},
{
"code": null,
"e": 21684,
"s": 21594,
"text": "The PMML Cluster Model output of Partitioning node → Prototypes Input of Cluster Assigner"
},
{
"code": null,
"e": 21774,
"s": 21684,
"text": "The PMML Cluster Model output of Partitioning node → Prototypes Input of Cluster Assigner"
},
{
"code": null,
"e": 21852,
"s": 21774,
"text": "Second partition output of Partitioning node → Input data of Cluster Assigner"
},
{
"code": null,
"e": 21930,
"s": 21852,
"text": "Second partition output of Partitioning node → Input data of Cluster Assigner"
},
{
"code": null,
"e": 21988,
"s": 21930,
"text": "These two connections are shown in the screenshot below −"
},
{
"code": null,
"e": 22076,
"s": 21988,
"text": "The Cluster Assigner does not need any special configuration. Just accept the defaults."
},
{
"code": null,
"e": 22198,
"s": 22076,
"text": "Now, add some annotation and description to this node. Rearrange your nodes. Your screen should look like the following −"
},
{
"code": null,
"e": 22536,
"s": 22198,
"text": "At this point, our clustering is completed. We need to visualize the output graphically. For this, we will add a scatter plot. We will set the colors and shapes for three classes differently in the scatter plot. Thus, we will filter the output of the k-Means node first through the Color Manager node and then through Shape Manager node."
},
{
"code": null,
"e": 22774,
"s": 22536,
"text": "Locate the Color Manager node in the repository. Add it to the workspace. Leave the configuration to its defaults. Note that you must open the configuration dialog and hit OK to accept the defaults. Set the description text for the node."
},
{
"code": null,
"e": 22908,
"s": 22774,
"text": "Make a connection from the output of k-Means to the input of Color Manager. Your screen would look like the following at this stage −"
},
{
"code": null,
"e": 23234,
"s": 22908,
"text": "Locate the Shape Manager in the repository and add it to the workspace. Leave its configuration to the defaults. Like the previous one, you must open the configuration dialog and hit OK to set defaults. Establish the connection from the output of Color Manager to the input of Shape Manager. Set the description for the node."
},
{
"code": null,
"e": 23279,
"s": 23234,
"text": "Your screen should look like the following −"
},
{
"code": null,
"e": 23360,
"s": 23279,
"text": "Now, you will be adding the last node in our model and that is the scatter plot."
},
{
"code": null,
"e": 23556,
"s": 23360,
"text": "Locate Scatter Plot node in the repository and add it to the workspace. Connect the output of Shape Manager to the input of Scatter Plot. Leave the configuration to defaults. Set the description."
},
{
"code": null,
"e": 23622,
"s": 23556,
"text": "Finally, add a group annotation to the recently added three nodes"
},
{
"code": null,
"e": 23648,
"s": 23622,
"text": "Annotation: Visualization"
},
{
"code": null,
"e": 23739,
"s": 23648,
"text": "Reposition the nodes as desired. Your screen should look like the following at this stage."
},
{
"code": null,
"e": 23782,
"s": 23739,
"text": "This completes the task of model building."
},
{
"code": null,
"e": 23856,
"s": 23782,
"text": "To test the model, execute the following menu options: Node → Execute All"
},
{
"code": null,
"e": 24050,
"s": 23856,
"text": "If everything goes correct, the status signal at the bottom of each node would turn green. If not, you will need to look up the Console view for the errors, fix them up and re-run the workflow."
},
{
"code": null,
"e": 24231,
"s": 24050,
"text": "Now, you are ready to visualize the predicted output of the model. For this, right click the Scatter Plot node and select the following menu options: Interactive View: Scatter Plot"
},
{
"code": null,
"e": 24271,
"s": 24231,
"text": "This is shown in the screenshot below −"
},
{
"code": null,
"e": 24332,
"s": 24271,
"text": "You would see the scatter plot on the screen as shown here −"
},
{
"code": null,
"e": 24548,
"s": 24332,
"text": "You can run through different visualizations by changing x- and y- axis. To do so, click on the settings menu at the top right corner of the scatter plot. A popup menu would appear as shown in the screenshot below −"
},
{
"code": null,
"e": 24655,
"s": 24548,
"text": "You can set the various parameters for the plot on this screen to visualize the data from several aspects."
},
{
"code": null,
"e": 24698,
"s": 24655,
"text": "This completes our task of model building."
},
{
"code": null,
"e": 24849,
"s": 24698,
"text": "KNIME provides a graphical tool for building Machine Learning models. In this tutorial, you learned how to download and install KNIME on your machine."
},
{
"code": null,
"e": 25382,
"s": 24849,
"text": "You learned the various views provided in the KNIME workbench. KNIME provides several predefined workflows for your learning. We used one such workflow to learn the capabilities of KNIME. KNIME provides several pre-programmed nodes for reading data in various formats, analyzing data using several ML algorithms, and finally visualizing data in many different ways. Towards the end of the tutorial, you created your own model starting from scratch. We used the well-known iris dataset to classify the plants using k-Means algorithm."
},
{
"code": null,
"e": 25448,
"s": 25382,
"text": "You are now ready to use these techniques for your own analytics."
},
{
"code": null,
"e": 25686,
"s": 25448,
"text": "If you are a developer and would like to use the KNIME components in your programming applications, you will be glad to know that KNIME natively integrates with a wide range of programming languages such as Java, R, Python and many more."
},
{
"code": null,
"e": 25719,
"s": 25686,
"text": "\n 27 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 25734,
"s": 25719,
"text": " Yoda Learning"
},
{
"code": null,
"e": 25741,
"s": 25734,
"text": " Print"
},
{
"code": null,
"e": 25752,
"s": 25741,
"text": " Add Notes"
}
] |
Android Linear Layout
|
Android LinearLayout is a view group that aligns all children in either vertically or horizontally.
Following are the important attributes specific to LinearLayout −
android:id
This is the ID which uniquely identifies the layout.
android:baselineAligned
This must be a boolean value, either "true" or "false" and prevents the layout from aligning its children's baselines.
android:baselineAlignedChildIndex
When a linear layout is part of another layout that is baseline aligned, it can specify which of its children to baseline align.
android:divider
This is drawable to use as a vertical divider between buttons. You use a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
android:gravity
This specifies how an object should position its content, on both the X and Y axes. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc.
android:orientation
This specifies the direction of arrangement and you will use "horizontal" for a row, "vertical" for a column. The default is horizontal.
android:weightSum
Sum up of child weight
This example will take you through simple steps to show how to create your own Android application using Linear Layout. Follow the following steps to modify the Android application we created in Hello World Example chapter −
Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/btnStartService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="start_service"/>
<Button android:id="@+id/btnPauseService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="pause_service"/>
<Button android:id="@+id/btnStopService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="stop_service"/>
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now let's change the orientation of Layout as android:orientation="horizontal" and try to run the same application, it will give following screen −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3707,
"s": 3607,
"text": "Android LinearLayout is a view group that aligns all children in either vertically or horizontally."
},
{
"code": null,
"e": 3773,
"s": 3707,
"text": "Following are the important attributes specific to LinearLayout −"
},
{
"code": null,
"e": 3784,
"s": 3773,
"text": "android:id"
},
{
"code": null,
"e": 3837,
"s": 3784,
"text": "This is the ID which uniquely identifies the layout."
},
{
"code": null,
"e": 3861,
"s": 3837,
"text": "android:baselineAligned"
},
{
"code": null,
"e": 3980,
"s": 3861,
"text": "This must be a boolean value, either \"true\" or \"false\" and prevents the layout from aligning its children's baselines."
},
{
"code": null,
"e": 4014,
"s": 3980,
"text": "android:baselineAlignedChildIndex"
},
{
"code": null,
"e": 4143,
"s": 4014,
"text": "When a linear layout is part of another layout that is baseline aligned, it can specify which of its children to baseline align."
},
{
"code": null,
"e": 4159,
"s": 4143,
"text": "android:divider"
},
{
"code": null,
"e": 4304,
"s": 4159,
"text": "This is drawable to use as a vertical divider between buttons. You use a color value, in the form of \"#rgb\", \"#argb\", \"#rrggbb\", or \"#aarrggbb\"."
},
{
"code": null,
"e": 4320,
"s": 4304,
"text": "android:gravity"
},
{
"code": null,
"e": 4498,
"s": 4320,
"text": "This specifies how an object should position its content, on both the X and Y axes. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc."
},
{
"code": null,
"e": 4518,
"s": 4498,
"text": "android:orientation"
},
{
"code": null,
"e": 4655,
"s": 4518,
"text": "This specifies the direction of arrangement and you will use \"horizontal\" for a row, \"vertical\" for a column. The default is horizontal."
},
{
"code": null,
"e": 4673,
"s": 4655,
"text": "android:weightSum"
},
{
"code": null,
"e": 4696,
"s": 4673,
"text": "Sum up of child weight"
},
{
"code": null,
"e": 4921,
"s": 4696,
"text": "This example will take you through simple steps to show how to create your own Android application using Linear Layout. Follow the following steps to modify the Android application we created in Hello World Example chapter −"
},
{
"code": null,
"e": 5086,
"s": 4921,
"text": "Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 5378,
"s": 5086,
"text": "package com.example.demo;\n\nimport android.os.Bundle;\nimport android.app.Activity;\n\npublic class MainActivity extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 5447,
"s": 5378,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 6191,
"s": 5447,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"vertical\" >\n \n <Button android:id=\"@+id/btnStartService\"\n android:layout_width=\"270dp\"\n android:layout_height=\"wrap_content\"\n android:text=\"start_service\"/>\n \n <Button android:id=\"@+id/btnPauseService\"\n android:layout_width=\"270dp\"\n android:layout_height=\"wrap_content\"\n android:text=\"pause_service\"/>\n \n <Button android:id=\"@+id/btnStopService\"\n android:layout_width=\"270dp\"\n android:layout_height=\"wrap_content\"\n android:text=\"stop_service\"/>\n \n</LinearLayout>"
},
{
"code": null,
"e": 6278,
"s": 6191,
"text": "Following will be the content of res/values/strings.xml to define two new constants −"
},
{
"code": null,
"e": 6441,
"s": 6278,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">HelloWorld</string>\n <string name=\"action_settings\">Settings</string>\n</resources>"
},
{
"code": null,
"e": 6856,
"s": 6441,
"text": "Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 7004,
"s": 6856,
"text": "Now let's change the orientation of Layout as android:orientation=\"horizontal\" and try to run the same application, it will give following screen −"
},
{
"code": null,
"e": 7039,
"s": 7004,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7051,
"s": 7039,
"text": " Aditya Dua"
},
{
"code": null,
"e": 7086,
"s": 7051,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7100,
"s": 7086,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 7132,
"s": 7100,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7149,
"s": 7132,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7184,
"s": 7149,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7201,
"s": 7184,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7236,
"s": 7201,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7253,
"s": 7236,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7286,
"s": 7253,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7303,
"s": 7286,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7310,
"s": 7303,
"text": " Print"
},
{
"code": null,
"e": 7321,
"s": 7310,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.