title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Distribution of candies according to ages of students - GeeksforGeeks
|
09 Apr, 2021
Given two integer arrays ages and packs where ages store the ages of different students and an element of pack stores the number of candies that packet has (complete array represent the number of packets). The candies can be distributed among students such that:
Every student must get only one pack of candies.All students of the same age must get equal number of candies.A student which is older must get more candies than all the student who are younger than him.
Every student must get only one pack of candies.
All students of the same age must get equal number of candies.
A student which is older must get more candies than all the student who are younger than him.
The task is to determine whether it is possible to distribute candies in the described manner. If possible then print Yes else print No.
Examples:
Input: ages[] = {5, 15, 10}, packs[] = {2, 2, 2, 3, 3, 4} Output: YES There are 3 students with age 5, 15 and 10.And there are 6 packets of candies containing 2, 2, 2, 3, 3, 4 candies respectively. We will give one packet containing 2 candies to the student of age 5, one packet containing 3 candies to student with age 10 and give the packet containing 4 candies to student age 15
Input: ages[] = {5, 5, 6, 7}, packs[] = {5, 4, 6, 6} Output: NO
Approach:
Make 2 frequency arrays, one which will store the number of students with a particular age and one which will store the number of packets with a particular amount of candies.
Then traverse the frequency array for ages starting from the youngest age and for every age in ascending try to find the candy packets that are greater than or equal to the number of students for the selected age (starting from the least number of candies a packet has)
If the above case fails then the answer is No else repeat the above steps until all the student have got the candies and print Yes in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to check The validity of distributionvoid check_distribution(int n, int k, int age[], int candy[]){ // Stroring the max age of all // students + 1 int mxage = *(std::max_element( age, age + n)) + 1; // Stroring the max candy + 1 int mxcandy = *(std::max_element( candy, candy + k)) + 1; int fr1[mxage] = {0}; int fr2[mxcandy] = {0}; // Creating the frequency array of // the age of students for(int j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(int j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not bool Tf = true; for(int j = 0; j < mxage; j++) { if (fr1[j] == 0) continue; // Flag to tell if we can choose // some candy packets for the // students with age j bool flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if (Tf) cout << "YES" << endl; else cout << "NO" << endl;} // Driver code int main(){ int age[] = { 5, 15, 10 }; int candy[] = { 2, 2, 2, 3, 3, 4 }; int n = sizeof(age) / sizeof(age[0]); int k = sizeof(candy) / sizeof(candy[0]); check_distribution(n, k, age, candy); return 0;} // This code is contributed by divyeshrabadiya07
// Java implementation of the approachimport java.util.*; class Main{ // Function to check The validity of distribution public static void check_distribution(int n, int k, int age[], int candy[]) { // Stroring the max age of all // students + 1 int mxage = age[0]; for(int i = 0; i < age.length; i++) { if(mxage < age[i]) { mxage = age[i]; } } // Stroring the max candy + 1 int mxcandy = candy[0]; for(int i = 0; i < candy.length; i++) { if(mxcandy < candy[i]) { mxcandy = candy[i]; } } int fr1[] = new int[mxage + 1]; Arrays.fill(fr1, 0); int fr2[] = new int[mxcandy + 1]; Arrays.fill(fr2, 0); // Creating the frequency array of // the age of students for(int j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(int j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not boolean Tf = true; for(int j = 0; j < mxage; j++) { if (fr1[j] == 0) continue; // Flag to tell if we can choose // some candy packets for the // students with age j boolean flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if (Tf) System.out.println("YES"); else System.out.println("NO"); } // Driver code public static void main(String[] args) { int age[] = { 5, 15, 10 }; int candy[] = { 2, 2, 2, 3, 3, 4 }; int n = age.length; int k = candy.length; check_distribution(n, k, age, candy); }} // This code is contributed by divyesh072019
# Python3 implementation of the approach # Function to check The validity of distributiondef check_distribution(n, k, age, candy): # Stroring the max age of all students + 1 mxage = max(age)+1 # Stroring the max candy + 1 mxcandy = max(candy)+1 fr1 = [0] * mxage fr2 = [0] * mxcandy # creating the frequency array of the # age of students for j in range(n): fr1[age[j]] += 1 # Creating the frequency array of the # packets of candies for j in range(k): fr2[candy[j]] += 1 # pointer to tell whether we have reached # the end of candy frequency array k = 0 # Flag to tell if distribution is possible or not Tf = True for j in range(mxage): if (fr1[j] == 0): continue # Flag to tell if we can choose some # candy packets for the students with age j flag = False while (k < mxcandy): # If the quantity of packets is greater # than or equal to the number of students # of age j, then we can choose these # packets for the students if (fr1[j] <= fr2[k]): flag = True break k += 1 # Start searching from k + 1 in next operation k = k + 1 # If we cannot choose any packets # then the answer is NO if (flag == False): Tf = False break if (Tf): print("YES") else: print("NO") # Driver codeage = [5, 15, 10]candy = [2, 2, 2, 3, 3, 4]n = len(age)k = len(candy)check_distribution(n, k, age, candy)
// C# implementation of the approachusing System.IO;using System;class GFG{ // Function to check The validity of distribution static void check_distribution(int n,int k, int[] age,int[] candy) { // Stroring the max age of all // students + 1 int mxage = age[0]; for(int i = 0; i < age.Length; i++) { if(mxage < age[i]) { mxage = age[i]; } } // Stroring the max candy + 1 int mxcandy = candy[0]; for(int i = 0; i < candy.Length; i++) { if(mxcandy < candy[i]) { mxcandy = candy[i]; } } int[] fr1 = new int[mxage + 1]; Array.Fill(fr1, 0); int[] fr2 = new int[mxcandy + 1]; Array.Fill(fr2, 0); // Creating the frequency array of // the age of students for(int j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(int j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not bool Tf = true; for(int j = 0; j < mxage; j++) { if(fr1[j] == 0) { continue; } // Flag to tell if we can choose // some candy packets for the // students with age j bool flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if(Tf) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } // Driver code static void Main() { int[] age = {5, 15, 10}; int[] candy = { 2, 2, 2, 3, 3, 4 }; int n = age.Length; int k = candy.Length; check_distribution(n, k, age, candy); }} // This code is contributed by avanitrachhadiya2155
<script> // Javascript implementation of the approach // Function to check The validity of distribution function check_distribution(n, k, age, candy) { // Stroring the max age of all // students + 1 let mxage = age[0]; for(let i = 0; i < age.length; i++) { if(mxage < age[i]) { mxage = age[i]; } } // Stroring the max candy + 1 let mxcandy = candy[0]; for(let i = 0; i < candy.length; i++) { if(mxcandy < candy[i]) { mxcandy = candy[i]; } } let fr1 = new Array(mxage + 1); fr1.fill(0); let fr2 = new Array(mxcandy + 1); fr2.fill(0); // Creating the frequency array of // the age of students for(let j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(let j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not let Tf = true; for(let j = 0; j < mxage; j++) { if(fr1[j] == 0) { continue; } // Flag to tell if we can choose // some candy packets for the // students with age j let flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if(Tf) { document.write("YES"); } else { document.write("NO"); } } let age = [5, 15, 10]; let candy = [ 2, 2, 2, 3, 3, 4 ]; let n = age.length; let k = candy.length; check_distribution(n, k, age, candy); // This code is contributed by suresh07.</script>
YES
divyeshrabadiya07
divyesh072019
avanitrachhadiya2155
suresh07
programming-puzzle
Greedy
Python
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Program for First Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
Max Flow Problem Introduction
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26563,
"s": 26535,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 26827,
"s": 26563,
"text": "Given two integer arrays ages and packs where ages store the ages of different students and an element of pack stores the number of candies that packet has (complete array represent the number of packets). The candies can be distributed among students such that: "
},
{
"code": null,
"e": 27031,
"s": 26827,
"text": "Every student must get only one pack of candies.All students of the same age must get equal number of candies.A student which is older must get more candies than all the student who are younger than him."
},
{
"code": null,
"e": 27080,
"s": 27031,
"text": "Every student must get only one pack of candies."
},
{
"code": null,
"e": 27143,
"s": 27080,
"text": "All students of the same age must get equal number of candies."
},
{
"code": null,
"e": 27237,
"s": 27143,
"text": "A student which is older must get more candies than all the student who are younger than him."
},
{
"code": null,
"e": 27374,
"s": 27237,
"text": "The task is to determine whether it is possible to distribute candies in the described manner. If possible then print Yes else print No."
},
{
"code": null,
"e": 27385,
"s": 27374,
"text": "Examples: "
},
{
"code": null,
"e": 27767,
"s": 27385,
"text": "Input: ages[] = {5, 15, 10}, packs[] = {2, 2, 2, 3, 3, 4} Output: YES There are 3 students with age 5, 15 and 10.And there are 6 packets of candies containing 2, 2, 2, 3, 3, 4 candies respectively. We will give one packet containing 2 candies to the student of age 5, one packet containing 3 candies to student with age 10 and give the packet containing 4 candies to student age 15"
},
{
"code": null,
"e": 27832,
"s": 27767,
"text": "Input: ages[] = {5, 5, 6, 7}, packs[] = {5, 4, 6, 6} Output: NO "
},
{
"code": null,
"e": 27843,
"s": 27832,
"text": "Approach: "
},
{
"code": null,
"e": 28018,
"s": 27843,
"text": "Make 2 frequency arrays, one which will store the number of students with a particular age and one which will store the number of packets with a particular amount of candies."
},
{
"code": null,
"e": 28288,
"s": 28018,
"text": "Then traverse the frequency array for ages starting from the youngest age and for every age in ascending try to find the candy packets that are greater than or equal to the number of students for the selected age (starting from the least number of candies a packet has)"
},
{
"code": null,
"e": 28431,
"s": 28288,
"text": "If the above case fails then the answer is No else repeat the above steps until all the student have got the candies and print Yes in the end."
},
{
"code": null,
"e": 28482,
"s": 28431,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28486,
"s": 28482,
"text": "C++"
},
{
"code": null,
"e": 28491,
"s": 28486,
"text": "Java"
},
{
"code": null,
"e": 28499,
"s": 28491,
"text": "Python3"
},
{
"code": null,
"e": 28502,
"s": 28499,
"text": "C#"
},
{
"code": null,
"e": 28513,
"s": 28502,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to check The validity of distributionvoid check_distribution(int n, int k, int age[], int candy[]){ // Stroring the max age of all // students + 1 int mxage = *(std::max_element( age, age + n)) + 1; // Stroring the max candy + 1 int mxcandy = *(std::max_element( candy, candy + k)) + 1; int fr1[mxage] = {0}; int fr2[mxcandy] = {0}; // Creating the frequency array of // the age of students for(int j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(int j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not bool Tf = true; for(int j = 0; j < mxage; j++) { if (fr1[j] == 0) continue; // Flag to tell if we can choose // some candy packets for the // students with age j bool flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if (Tf) cout << \"YES\" << endl; else cout << \"NO\" << endl;} // Driver code int main(){ int age[] = { 5, 15, 10 }; int candy[] = { 2, 2, 2, 3, 3, 4 }; int n = sizeof(age) / sizeof(age[0]); int k = sizeof(candy) / sizeof(candy[0]); check_distribution(n, k, age, candy); return 0;} // This code is contributed by divyeshrabadiya07",
"e": 30740,
"s": 28513,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class Main{ // Function to check The validity of distribution public static void check_distribution(int n, int k, int age[], int candy[]) { // Stroring the max age of all // students + 1 int mxage = age[0]; for(int i = 0; i < age.length; i++) { if(mxage < age[i]) { mxage = age[i]; } } // Stroring the max candy + 1 int mxcandy = candy[0]; for(int i = 0; i < candy.length; i++) { if(mxcandy < candy[i]) { mxcandy = candy[i]; } } int fr1[] = new int[mxage + 1]; Arrays.fill(fr1, 0); int fr2[] = new int[mxcandy + 1]; Arrays.fill(fr2, 0); // Creating the frequency array of // the age of students for(int j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(int j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not boolean Tf = true; for(int j = 0; j < mxage; j++) { if (fr1[j] == 0) continue; // Flag to tell if we can choose // some candy packets for the // students with age j boolean flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if (Tf) System.out.println(\"YES\"); else System.out.println(\"NO\"); } // Driver code public static void main(String[] args) { int age[] = { 5, 15, 10 }; int candy[] = { 2, 2, 2, 3, 3, 4 }; int n = age.length; int k = candy.length; check_distribution(n, k, age, candy); }} // This code is contributed by divyesh072019",
"e": 33588,
"s": 30740,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to check The validity of distributiondef check_distribution(n, k, age, candy): # Stroring the max age of all students + 1 mxage = max(age)+1 # Stroring the max candy + 1 mxcandy = max(candy)+1 fr1 = [0] * mxage fr2 = [0] * mxcandy # creating the frequency array of the # age of students for j in range(n): fr1[age[j]] += 1 # Creating the frequency array of the # packets of candies for j in range(k): fr2[candy[j]] += 1 # pointer to tell whether we have reached # the end of candy frequency array k = 0 # Flag to tell if distribution is possible or not Tf = True for j in range(mxage): if (fr1[j] == 0): continue # Flag to tell if we can choose some # candy packets for the students with age j flag = False while (k < mxcandy): # If the quantity of packets is greater # than or equal to the number of students # of age j, then we can choose these # packets for the students if (fr1[j] <= fr2[k]): flag = True break k += 1 # Start searching from k + 1 in next operation k = k + 1 # If we cannot choose any packets # then the answer is NO if (flag == False): Tf = False break if (Tf): print(\"YES\") else: print(\"NO\") # Driver codeage = [5, 15, 10]candy = [2, 2, 2, 3, 3, 4]n = len(age)k = len(candy)check_distribution(n, k, age, candy)",
"e": 35171,
"s": 33588,
"text": null
},
{
"code": "// C# implementation of the approachusing System.IO;using System;class GFG{ // Function to check The validity of distribution static void check_distribution(int n,int k, int[] age,int[] candy) { // Stroring the max age of all // students + 1 int mxage = age[0]; for(int i = 0; i < age.Length; i++) { if(mxage < age[i]) { mxage = age[i]; } } // Stroring the max candy + 1 int mxcandy = candy[0]; for(int i = 0; i < candy.Length; i++) { if(mxcandy < candy[i]) { mxcandy = candy[i]; } } int[] fr1 = new int[mxage + 1]; Array.Fill(fr1, 0); int[] fr2 = new int[mxcandy + 1]; Array.Fill(fr2, 0); // Creating the frequency array of // the age of students for(int j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(int j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not bool Tf = true; for(int j = 0; j < mxage; j++) { if(fr1[j] == 0) { continue; } // Flag to tell if we can choose // some candy packets for the // students with age j bool flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if(Tf) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } } // Driver code static void Main() { int[] age = {5, 15, 10}; int[] candy = { 2, 2, 2, 3, 3, 4 }; int n = age.Length; int k = candy.Length; check_distribution(n, k, age, candy); }} // This code is contributed by avanitrachhadiya2155",
"e": 38125,
"s": 35171,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to check The validity of distribution function check_distribution(n, k, age, candy) { // Stroring the max age of all // students + 1 let mxage = age[0]; for(let i = 0; i < age.length; i++) { if(mxage < age[i]) { mxage = age[i]; } } // Stroring the max candy + 1 let mxcandy = candy[0]; for(let i = 0; i < candy.length; i++) { if(mxcandy < candy[i]) { mxcandy = candy[i]; } } let fr1 = new Array(mxage + 1); fr1.fill(0); let fr2 = new Array(mxcandy + 1); fr2.fill(0); // Creating the frequency array of // the age of students for(let j = 0; j < n; j++) { fr1[age[j]] += 1; } // Creating the frequency array of the // packets of candies for(let j = 0; j < k; j++) { fr2[candy[j]] += 1; } // Pointer to tell whether we have reached // the end of candy frequency array k = 0; // Flag to tell if distribution // is possible or not let Tf = true; for(let j = 0; j < mxage; j++) { if(fr1[j] == 0) { continue; } // Flag to tell if we can choose // some candy packets for the // students with age j let flag = false; while (k < mxcandy) { // If the quantity of packets is // greater than or equal to the // number of students of age j, // then we can choose these // packets for the students if (fr1[j] <= fr2[k]) { flag = true; break; } k += 1; } // Start searching from k + 1 // in next operation k = k + 1; // If we cannot choose any packets // then the answer is NO if (flag == false) { Tf = false; break; } } if(Tf) { document.write(\"YES\"); } else { document.write(\"NO\"); } } let age = [5, 15, 10]; let candy = [ 2, 2, 2, 3, 3, 4 ]; let n = age.length; let k = candy.length; check_distribution(n, k, age, candy); // This code is contributed by suresh07.</script>",
"e": 40923,
"s": 38125,
"text": null
},
{
"code": null,
"e": 40927,
"s": 40923,
"text": "YES"
},
{
"code": null,
"e": 40947,
"s": 40929,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 40961,
"s": 40947,
"text": "divyesh072019"
},
{
"code": null,
"e": 40982,
"s": 40961,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 40991,
"s": 40982,
"text": "suresh07"
},
{
"code": null,
"e": 41010,
"s": 40991,
"text": "programming-puzzle"
},
{
"code": null,
"e": 41017,
"s": 41010,
"text": "Greedy"
},
{
"code": null,
"e": 41024,
"s": 41017,
"text": "Python"
},
{
"code": null,
"e": 41031,
"s": 41024,
"text": "Greedy"
},
{
"code": null,
"e": 41129,
"s": 41031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41164,
"s": 41129,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 41216,
"s": 41164,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 41269,
"s": 41216,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 41320,
"s": 41269,
"text": "Bin Packing Problem (Minimize number of used Bins)"
},
{
"code": null,
"e": 41350,
"s": 41320,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 41378,
"s": 41350,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 41428,
"s": 41378,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 41450,
"s": 41428,
"text": "Python map() function"
}
] |
Lodash _.intersectionWith() Method - GeeksforGeeks
|
22 Jul, 2020
Lodash is a JavaScript library that works on the top of Underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.The _.intersectionwith() method is used to take the intersection of the one or more arrays. It is same as the intersection function in lodash only difference is that it accepts a comparator which is invoked to compare elements of arrays.
Syntax:
intersectionWith([arrays], [comparator])
Parameter: This method accepts two parameters as mention above and describe below:
arrays: It takes an array as a parameter.
comparator: It is the function that iterates over each value of the array and compares the values with the given comparator function.
Return Value: It returns the array after intersection of arrays.
Note: Please install lodash module by using command npm install lodash before using the code given below.
Example 1:
Javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [ { "a": 1 }, { "b": 2 }, { "b": 2, "a": 1 }] let array2 = [ { "a": 1, "b": 2 }, { "a": 1 }] // Using _.intersectionWith() methodlet newArray = _.intersectionWith( array1, array2, _.isEqual); // Printing original Arrayconsole.log("original Array1: ", array1)console.log("original Array2: ", array2) // Printing the newArrayconsole.log("new Array: ", newArray)
Output:
Example 2: When not using comparator function i.e. _.isequal() then output is empty array.
Javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [ { "a": 1 }, { "b": 2 }, { "b": 2, "a": 1 }] let array2 = [ { "a": 1, "b": 2 }, { "a": 1 }] // Using _.intersectionWith() method// and no comparator functionlet newArray = _.intersectionWith( array1, array2); // Printing original Arrayconsole.log("original Array1: ", array1)console.log("original Array2: ", array2) // Printing the newArrayconsole.log("new Array: ", newArray)
Output:
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n22 Jul, 2020"
},
{
"code": null,
"e": 26921,
"s": 26545,
"text": "Lodash is a JavaScript library that works on the top of Underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.The _.intersectionwith() method is used to take the intersection of the one or more arrays. It is same as the intersection function in lodash only difference is that it accepts a comparator which is invoked to compare elements of arrays."
},
{
"code": null,
"e": 26929,
"s": 26921,
"text": "Syntax:"
},
{
"code": null,
"e": 26970,
"s": 26929,
"text": "intersectionWith([arrays], [comparator])"
},
{
"code": null,
"e": 27053,
"s": 26970,
"text": "Parameter: This method accepts two parameters as mention above and describe below:"
},
{
"code": null,
"e": 27095,
"s": 27053,
"text": "arrays: It takes an array as a parameter."
},
{
"code": null,
"e": 27229,
"s": 27095,
"text": "comparator: It is the function that iterates over each value of the array and compares the values with the given comparator function."
},
{
"code": null,
"e": 27294,
"s": 27229,
"text": "Return Value: It returns the array after intersection of arrays."
},
{
"code": null,
"e": 27401,
"s": 27294,
"text": "Note: Please install lodash module by using command npm install lodash before using the code given below. "
},
{
"code": null,
"e": 27413,
"s": 27401,
"text": "Example 1: "
},
{
"code": null,
"e": 27424,
"s": 27413,
"text": "Javascript"
},
{
"code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arraylet array1 = [ { \"a\": 1 }, { \"b\": 2 }, { \"b\": 2, \"a\": 1 }] let array2 = [ { \"a\": 1, \"b\": 2 }, { \"a\": 1 }] // Using _.intersectionWith() methodlet newArray = _.intersectionWith( array1, array2, _.isEqual); // Printing original Arrayconsole.log(\"original Array1: \", array1)console.log(\"original Array2: \", array2) // Printing the newArrayconsole.log(\"new Array: \", newArray)",
"e": 27894,
"s": 27424,
"text": null
},
{
"code": null,
"e": 27902,
"s": 27894,
"text": "Output:"
},
{
"code": null,
"e": 27993,
"s": 27902,
"text": "Example 2: When not using comparator function i.e. _.isequal() then output is empty array."
},
{
"code": null,
"e": 28004,
"s": 27993,
"text": "Javascript"
},
{
"code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arraylet array1 = [ { \"a\": 1 }, { \"b\": 2 }, { \"b\": 2, \"a\": 1 }] let array2 = [ { \"a\": 1, \"b\": 2 }, { \"a\": 1 }] // Using _.intersectionWith() method// and no comparator functionlet newArray = _.intersectionWith( array1, array2); // Printing original Arrayconsole.log(\"original Array1: \", array1)console.log(\"original Array2: \", array2) // Printing the newArrayconsole.log(\"new Array: \", newArray)",
"e": 28492,
"s": 28004,
"text": null
},
{
"code": null,
"e": 28500,
"s": 28492,
"text": "Output:"
},
{
"code": null,
"e": 28518,
"s": 28500,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 28529,
"s": 28518,
"text": "JavaScript"
},
{
"code": null,
"e": 28546,
"s": 28529,
"text": "Web Technologies"
},
{
"code": null,
"e": 28644,
"s": 28546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28684,
"s": 28644,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28745,
"s": 28684,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28786,
"s": 28745,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28808,
"s": 28786,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28862,
"s": 28808,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28902,
"s": 28862,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28935,
"s": 28902,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28978,
"s": 28935,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29028,
"s": 28978,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Synchronize HashMap in Java? - GeeksforGeeks
|
28 Dec, 2020
HashMap is part of the Collection’s framework of java. It stores the data in the form of key-value pairs. These values of the HashMap can be accessed by using their respective keys. The key-value pairs can be accessed using their indexes (of Integer type).
HashMap is similar to HashTable in java. The main difference between HashTable and HashMap is that HashTable is synchronized but HashMap is not synchronized. Also, a HashMap can have one null key and any number of null values. The insertion order is not preserved in the HashMap.
Synchronization means controlling the access of multiple threads to any shared resource. A synchronized resource can be accessed by only one thread at a time.
HashMap can be synchronized using the Collections.synchronizedMap() method.
The synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.
Syntax:
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
Parameters: This method takes the map as a parameter to be “wrapped” in a synchronized map.
Return Value: This method returns a synchronized view of the specified map.
Code:
Java
// Java program to demonstrate// synchronization of HashMap import java.util.*; public class GFG { public static void main(String[] argv) throws Exception { try { // create a HashMap object Map<String, String> hMap = new HashMap<String, String>(); // add elements into the Map hMap.put("1", "Welcome"); hMap.put("2", "To"); hMap.put("3", "Geeks"); hMap.put("4", "For"); hMap.put("5", "Geeks"); System.out.println("Map : " + hMap); // Synchronizing the map Map<String, String> sMap = Collections.synchronizedMap(hMap); // printing the Collection System.out.println("Synchronized map is : " + sMap); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }}
Map : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}
Synchronized map is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}
Java-HashMap
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
|
[
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 25509,
"s": 25251,
"text": "HashMap is part of the Collection’s framework of java. It stores the data in the form of key-value pairs. These values of the HashMap can be accessed by using their respective keys. The key-value pairs can be accessed using their indexes (of Integer type)."
},
{
"code": null,
"e": 25789,
"s": 25509,
"text": "HashMap is similar to HashTable in java. The main difference between HashTable and HashMap is that HashTable is synchronized but HashMap is not synchronized. Also, a HashMap can have one null key and any number of null values. The insertion order is not preserved in the HashMap."
},
{
"code": null,
"e": 25948,
"s": 25789,
"text": "Synchronization means controlling the access of multiple threads to any shared resource. A synchronized resource can be accessed by only one thread at a time."
},
{
"code": null,
"e": 26024,
"s": 25948,
"text": "HashMap can be synchronized using the Collections.synchronizedMap() method."
},
{
"code": null,
"e": 26293,
"s": 26024,
"text": "The synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map."
},
{
"code": null,
"e": 26301,
"s": 26293,
"text": "Syntax:"
},
{
"code": null,
"e": 26361,
"s": 26301,
"text": "public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)"
},
{
"code": null,
"e": 26453,
"s": 26361,
"text": "Parameters: This method takes the map as a parameter to be “wrapped” in a synchronized map."
},
{
"code": null,
"e": 26529,
"s": 26453,
"text": "Return Value: This method returns a synchronized view of the specified map."
},
{
"code": null,
"e": 26535,
"s": 26529,
"text": "Code:"
},
{
"code": null,
"e": 26540,
"s": 26535,
"text": "Java"
},
{
"code": "// Java program to demonstrate// synchronization of HashMap import java.util.*; public class GFG { public static void main(String[] argv) throws Exception { try { // create a HashMap object Map<String, String> hMap = new HashMap<String, String>(); // add elements into the Map hMap.put(\"1\", \"Welcome\"); hMap.put(\"2\", \"To\"); hMap.put(\"3\", \"Geeks\"); hMap.put(\"4\", \"For\"); hMap.put(\"5\", \"Geeks\"); System.out.println(\"Map : \" + hMap); // Synchronizing the map Map<String, String> sMap = Collections.synchronizedMap(hMap); // printing the Collection System.out.println(\"Synchronized map is : \" + sMap); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27532,
"s": 26540,
"text": null
},
{
"code": null,
"e": 27646,
"s": 27532,
"text": "Map : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}\nSynchronized map is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}"
},
{
"code": null,
"e": 27659,
"s": 27646,
"text": "Java-HashMap"
},
{
"code": null,
"e": 27666,
"s": 27659,
"text": "Picked"
},
{
"code": null,
"e": 27690,
"s": 27666,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27695,
"s": 27690,
"text": "Java"
},
{
"code": null,
"e": 27709,
"s": 27695,
"text": "Java Programs"
},
{
"code": null,
"e": 27728,
"s": 27709,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27733,
"s": 27728,
"text": "Java"
},
{
"code": null,
"e": 27831,
"s": 27733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27846,
"s": 27831,
"text": "Stream In Java"
},
{
"code": null,
"e": 27867,
"s": 27846,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27886,
"s": 27867,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27916,
"s": 27886,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27962,
"s": 27916,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27988,
"s": 27962,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28022,
"s": 27988,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28069,
"s": 28022,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28101,
"s": 28069,
"text": "How to Iterate HashMap in Java?"
}
] |
Ruby | String inspect Method - GeeksforGeeks
|
09 Dec, 2019
inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped.
Syntax: str.inspect
Parameters:
Returns: Here, str is the given string.
Example 1:
# Ruby program to demonstrate # the inspect method # Taking a string and # using the methodputs "Sample".inspectputs "Articles".inspect
Output:
"Sample"
"Articles"
Example 2:
# Ruby program to demonstrate # the inspect method # Taking a string and # using the methodputs "Ru \n y".inspectputs "Ar\b\\bcles".inspect
Output:
"Ru \n y"
"Ar\b\\bcles"
Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
|
[
{
"code": null,
"e": 25014,
"s": 24986,
"text": "\n09 Dec, 2019"
},
{
"code": null,
"e": 25180,
"s": 25014,
"text": "inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped."
},
{
"code": null,
"e": 25200,
"s": 25180,
"text": "Syntax: str.inspect"
},
{
"code": null,
"e": 25212,
"s": 25200,
"text": "Parameters:"
},
{
"code": null,
"e": 25252,
"s": 25212,
"text": "Returns: Here, str is the given string."
},
{
"code": null,
"e": 25263,
"s": 25252,
"text": "Example 1:"
},
{
"code": "# Ruby program to demonstrate # the inspect method # Taking a string and # using the methodputs \"Sample\".inspectputs \"Articles\".inspect",
"e": 25406,
"s": 25263,
"text": null
},
{
"code": null,
"e": 25414,
"s": 25406,
"text": "Output:"
},
{
"code": null,
"e": 25435,
"s": 25414,
"text": "\"Sample\"\n\"Articles\"\n"
},
{
"code": null,
"e": 25446,
"s": 25435,
"text": "Example 2:"
},
{
"code": "# Ruby program to demonstrate # the inspect method # Taking a string and # using the methodputs \"Ru \\n y\".inspectputs \"Ar\\b\\\\bcles\".inspect",
"e": 25593,
"s": 25446,
"text": null
},
{
"code": null,
"e": 25601,
"s": 25593,
"text": "Output:"
},
{
"code": null,
"e": 25626,
"s": 25601,
"text": "\"Ru \\n y\"\n\"Ar\\b\\\\bcles\"\n"
},
{
"code": null,
"e": 25644,
"s": 25626,
"text": "Ruby String-class"
},
{
"code": null,
"e": 25657,
"s": 25644,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 25662,
"s": 25657,
"text": "Ruby"
},
{
"code": null,
"e": 25760,
"s": 25662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25791,
"s": 25760,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 25818,
"s": 25791,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 25842,
"s": 25818,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 25872,
"s": 25842,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 25898,
"s": 25872,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 25941,
"s": 25898,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 25963,
"s": 25941,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 25994,
"s": 25963,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 26012,
"s": 25994,
"text": "Ruby | Data Types"
}
] |
Microsoft Azure - Count of Azure Resources using Resource Graph Query - GeeksforGeeks
|
16 Dec, 2021
Graph Query is Azure can be easier to understand if you are familiar with Querying languages like SQL. In this article, we will keep track of the Azure resources using the Resource Query graph.
For this first open the Azure Resource Graph Explorer in Azure Portal to Run the following below Queries
1. To get the Total Count of Azure Resources from the select directory or management group or subscription scope.
KQL Graph Query: This query returns the number of Azure resources that exist in the select directory or management group or subscription scope.
Resources
| summarize count()
Output:
2. To get the Total Count of Azure Virtual Machines from a select directory or management group or subscription scope.
KQL Graph Query: This query returns the number of virtual machines that exist in the select directory or management group or subscription scope.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| count
| project TotalVMs = Count
Output:
3. To get the Count virtual machines by OS type (Windows and Linux)from select directory or management group or subscription scope.
KQL Graph Query: This query returns the number of virtual machines by OS type that exists in the select directory or management group or subscription scope.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| summarize count() by tostring(properties.storageProfile.osDisk.osType)
Output:
4. To get the Total Count of Azure Virtual Machines by Location from a select directory or management group or subscription scope.
KQL Graph Query: This query returns the number of virtual machines by the location that exists in the select directory or management group or subscription scope.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| summarize count() by location
Output:
5. To get the Total Count of Azure Virtual Machines by Select Specific Location from select directory or management group or subscription scope.
Example 1:This KQL Graph Query returns the number of virtual machines by selecting the location where it has “westeurope” that exists in the select directory or management group or subscription scope.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| where location =~ 'westeurope'
| count
Output:
Example 2: This KQL Graph Query returns the number of virtual machines by selecting the location where it has “eastus” that exist in the select directory or management group or subscription scope.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| where location =~ 'eastus'
| count
Output:
6. To get the Count Azure Key Vault Resources from the select directory or management group or subscription scope.
KQL Graph Query: This query returns the number of key vault resources that exist in the select directory or management group or subscription scope.
Resources
| where type =~ 'microsoft.keyvault/vaults'
| count
Output:
azure-virtual-machine
Cloud-Computing
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Azure - Azure Firewall Flow Logs From Select Source IP
Microsoft Azure - KQL Query to Get the VM Computer Properties
Microsoft Azure - Check Status of Azure VM using Azure PowerShell
Microsoft Azure - Find and Delete Orphaned Public IP addresses in Azure Portal
Defense in Depth Strategy in Microsoft Azure
Microsoft Azure - Graph Query to Get Properties of Azure VM Resource
Microsoft Azure - Resource Tagging and Best Practices
Microsoft Azure - Query System Event Log Data Using Azure KQL
Microsoft Azure - Find Orphaned Disks
Microsoft Azure - Rebooting an Application Gateway
|
[
{
"code": null,
"e": 27103,
"s": 27075,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 27299,
"s": 27103,
"text": "Graph Query is Azure can be easier to understand if you are familiar with Querying languages like SQL. In this article, we will keep track of the Azure resources using the Resource Query graph."
},
{
"code": null,
"e": 27404,
"s": 27299,
"text": "For this first open the Azure Resource Graph Explorer in Azure Portal to Run the following below Queries"
},
{
"code": null,
"e": 27518,
"s": 27404,
"text": "1. To get the Total Count of Azure Resources from the select directory or management group or subscription scope."
},
{
"code": null,
"e": 27662,
"s": 27518,
"text": "KQL Graph Query: This query returns the number of Azure resources that exist in the select directory or management group or subscription scope."
},
{
"code": null,
"e": 27692,
"s": 27662,
"text": "Resources\n| summarize count()"
},
{
"code": null,
"e": 27700,
"s": 27692,
"text": "Output:"
},
{
"code": null,
"e": 27819,
"s": 27700,
"text": "2. To get the Total Count of Azure Virtual Machines from a select directory or management group or subscription scope."
},
{
"code": null,
"e": 27964,
"s": 27819,
"text": "KQL Graph Query: This query returns the number of virtual machines that exist in the select directory or management group or subscription scope."
},
{
"code": null,
"e": 28061,
"s": 27964,
"text": "Resources\n| where type =~ 'Microsoft.Compute/virtualMachines'\n| count\n| project TotalVMs = Count"
},
{
"code": null,
"e": 28069,
"s": 28061,
"text": "Output:"
},
{
"code": null,
"e": 28201,
"s": 28069,
"text": "3. To get the Count virtual machines by OS type (Windows and Linux)from select directory or management group or subscription scope."
},
{
"code": null,
"e": 28359,
"s": 28201,
"text": "KQL Graph Query: This query returns the number of virtual machines by OS type that exists in the select directory or management group or subscription scope."
},
{
"code": null,
"e": 28494,
"s": 28359,
"text": "Resources\n| where type =~ 'Microsoft.Compute/virtualMachines'\n| summarize count() by tostring(properties.storageProfile.osDisk.osType)"
},
{
"code": null,
"e": 28502,
"s": 28494,
"text": "Output:"
},
{
"code": null,
"e": 28633,
"s": 28502,
"text": "4. To get the Total Count of Azure Virtual Machines by Location from a select directory or management group or subscription scope."
},
{
"code": null,
"e": 28795,
"s": 28633,
"text": "KQL Graph Query: This query returns the number of virtual machines by the location that exists in the select directory or management group or subscription scope."
},
{
"code": null,
"e": 28889,
"s": 28795,
"text": "Resources\n| where type =~ 'Microsoft.Compute/virtualMachines'\n| summarize count() by location"
},
{
"code": null,
"e": 28897,
"s": 28889,
"text": "Output:"
},
{
"code": null,
"e": 29042,
"s": 28897,
"text": "5. To get the Total Count of Azure Virtual Machines by Select Specific Location from select directory or management group or subscription scope."
},
{
"code": null,
"e": 29243,
"s": 29042,
"text": "Example 1:This KQL Graph Query returns the number of virtual machines by selecting the location where it has “westeurope” that exists in the select directory or management group or subscription scope."
},
{
"code": null,
"e": 29346,
"s": 29243,
"text": "Resources\n| where type =~ 'Microsoft.Compute/virtualMachines'\n| where location =~ 'westeurope'\n| count"
},
{
"code": null,
"e": 29354,
"s": 29346,
"text": "Output:"
},
{
"code": null,
"e": 29552,
"s": 29354,
"text": "Example 2: This KQL Graph Query returns the number of virtual machines by selecting the location where it has “eastus” that exist in the select directory or management group or subscription scope."
},
{
"code": null,
"e": 29651,
"s": 29552,
"text": "Resources\n| where type =~ 'Microsoft.Compute/virtualMachines'\n| where location =~ 'eastus'\n| count"
},
{
"code": null,
"e": 29659,
"s": 29651,
"text": "Output:"
},
{
"code": null,
"e": 29774,
"s": 29659,
"text": "6. To get the Count Azure Key Vault Resources from the select directory or management group or subscription scope."
},
{
"code": null,
"e": 29922,
"s": 29774,
"text": "KQL Graph Query: This query returns the number of key vault resources that exist in the select directory or management group or subscription scope."
},
{
"code": null,
"e": 29984,
"s": 29922,
"text": "Resources\n| where type =~ 'microsoft.keyvault/vaults'\n| count"
},
{
"code": null,
"e": 29992,
"s": 29984,
"text": "Output:"
},
{
"code": null,
"e": 30014,
"s": 29992,
"text": "azure-virtual-machine"
},
{
"code": null,
"e": 30030,
"s": 30014,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 30046,
"s": 30030,
"text": "Microsoft Azure"
},
{
"code": null,
"e": 30144,
"s": 30046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30209,
"s": 30144,
"text": "Microsoft Azure - Azure Firewall Flow Logs From Select Source IP"
},
{
"code": null,
"e": 30271,
"s": 30209,
"text": "Microsoft Azure - KQL Query to Get the VM Computer Properties"
},
{
"code": null,
"e": 30337,
"s": 30271,
"text": "Microsoft Azure - Check Status of Azure VM using Azure PowerShell"
},
{
"code": null,
"e": 30416,
"s": 30337,
"text": "Microsoft Azure - Find and Delete Orphaned Public IP addresses in Azure Portal"
},
{
"code": null,
"e": 30461,
"s": 30416,
"text": "Defense in Depth Strategy in Microsoft Azure"
},
{
"code": null,
"e": 30530,
"s": 30461,
"text": "Microsoft Azure - Graph Query to Get Properties of Azure VM Resource"
},
{
"code": null,
"e": 30584,
"s": 30530,
"text": "Microsoft Azure - Resource Tagging and Best Practices"
},
{
"code": null,
"e": 30646,
"s": 30584,
"text": "Microsoft Azure - Query System Event Log Data Using Azure KQL"
},
{
"code": null,
"e": 30684,
"s": 30646,
"text": "Microsoft Azure - Find Orphaned Disks"
}
] |
JavaScript Date getDay() Method - GeeksforGeeks
|
12 Oct, 2021
Below is the example of Date getDay() method.
Example:
javascript
<script> // Here a date has been assigned // while creating Date object var A = new Date('October 15, 1996 05:35:32'); // Day of the week from above Date Object is // being extracted using getDay() var Day = A.getDay(); // Printing day of the week document.write("Number of Day: " +Day);</script>
Output:
Number of Day: 2
The date.getDay() method is used to fetch the day of a week(0 to 6) from a given Date object.Syntax:
DateObj.getDay()
Parameter: This method does not accept any parameters.Return Values: It returns the day of the week for the given date. Day of the week will be returned in the form of integer value ranging from 0 to 6 means 0 for Sunday, 1 for Monday, and so on till 6 for Saturday.More codes for the above method are as follows:Program 1: If the date of the month is not given, by default the function considers it as the first date of the month and hence accordingly it returns the day of the week. It is an exceptional case.
javascript
<script> // Here a date has been assigned // While creating a Date object var A = new Date('July 1974'); var B = A.getDay(); // Printing day document.write("Number of Day: "+B);</script>
Output:
Number of Day: 1
Program 2: The date of the month should must lie in between 1 to 31 because none of the month have date greater than 31 that is why it returns NaN i.e, not a number because date for the month does not exist.
javascript
<script> // Here a date has been assigned // while creating Date object var A = new Date('October 35, 1996 05:35:32'); // Day of the week from above Date Object // is being extracted using getDay() var B = A.getDay(); // Printing day of the week. document.write(B);</script>
Output:
NaN
Program 3: If nothing as parameter is given, it returns current day of the current week.
javascript
<script> // Creating Date Object var A = new Date(); // day of the week from above object // is being extracted using getDay(). var B = A.getDay() // Printing day of the week. document.write(B);</script>
Output:
5
Supported Browsers: The browsers supported by JavaScript Date getDay() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
Akanksha_Rai
ysachin2314
javascript-date
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 26593,
"s": 26545,
"text": "Below is the example of Date getDay() method. "
},
{
"code": null,
"e": 26604,
"s": 26593,
"text": "Example: "
},
{
"code": null,
"e": 26615,
"s": 26604,
"text": "javascript"
},
{
"code": "<script> // Here a date has been assigned // while creating Date object var A = new Date('October 15, 1996 05:35:32'); // Day of the week from above Date Object is // being extracted using getDay() var Day = A.getDay(); // Printing day of the week document.write(\"Number of Day: \" +Day);</script> ",
"e": 26957,
"s": 26615,
"text": null
},
{
"code": null,
"e": 26969,
"s": 26959,
"text": "Output: "
},
{
"code": null,
"e": 26986,
"s": 26969,
"text": "Number of Day: 2"
},
{
"code": null,
"e": 27089,
"s": 26986,
"text": "The date.getDay() method is used to fetch the day of a week(0 to 6) from a given Date object.Syntax: "
},
{
"code": null,
"e": 27106,
"s": 27089,
"text": "DateObj.getDay()"
},
{
"code": null,
"e": 27620,
"s": 27106,
"text": "Parameter: This method does not accept any parameters.Return Values: It returns the day of the week for the given date. Day of the week will be returned in the form of integer value ranging from 0 to 6 means 0 for Sunday, 1 for Monday, and so on till 6 for Saturday.More codes for the above method are as follows:Program 1: If the date of the month is not given, by default the function considers it as the first date of the month and hence accordingly it returns the day of the week. It is an exceptional case. "
},
{
"code": null,
"e": 27631,
"s": 27620,
"text": "javascript"
},
{
"code": "<script> // Here a date has been assigned // While creating a Date object var A = new Date('July 1974'); var B = A.getDay(); // Printing day document.write(\"Number of Day: \"+B);</script> ",
"e": 27847,
"s": 27631,
"text": null
},
{
"code": null,
"e": 27857,
"s": 27847,
"text": "Output: "
},
{
"code": null,
"e": 27874,
"s": 27857,
"text": "Number of Day: 1"
},
{
"code": null,
"e": 28084,
"s": 27874,
"text": "Program 2: The date of the month should must lie in between 1 to 31 because none of the month have date greater than 31 that is why it returns NaN i.e, not a number because date for the month does not exist. "
},
{
"code": null,
"e": 28095,
"s": 28084,
"text": "javascript"
},
{
"code": "<script> // Here a date has been assigned // while creating Date object var A = new Date('October 35, 1996 05:35:32'); // Day of the week from above Date Object // is being extracted using getDay() var B = A.getDay(); // Printing day of the week. document.write(B);</script>",
"e": 28380,
"s": 28095,
"text": null
},
{
"code": null,
"e": 28390,
"s": 28380,
"text": "Output: "
},
{
"code": null,
"e": 28394,
"s": 28390,
"text": "NaN"
},
{
"code": null,
"e": 28485,
"s": 28394,
"text": "Program 3: If nothing as parameter is given, it returns current day of the current week. "
},
{
"code": null,
"e": 28496,
"s": 28485,
"text": "javascript"
},
{
"code": "<script> // Creating Date Object var A = new Date(); // day of the week from above object // is being extracted using getDay(). var B = A.getDay() // Printing day of the week. document.write(B);</script>",
"e": 28709,
"s": 28496,
"text": null
},
{
"code": null,
"e": 28719,
"s": 28709,
"text": "Output: "
},
{
"code": null,
"e": 28721,
"s": 28719,
"text": "5"
},
{
"code": null,
"e": 28819,
"s": 28721,
"text": "Supported Browsers: The browsers supported by JavaScript Date getDay() method are listed below: "
},
{
"code": null,
"e": 28845,
"s": 28819,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 28863,
"s": 28845,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 28883,
"s": 28863,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 28913,
"s": 28883,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 28931,
"s": 28913,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 28950,
"s": 28931,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 28965,
"s": 28952,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28977,
"s": 28965,
"text": "ysachin2314"
},
{
"code": null,
"e": 28993,
"s": 28977,
"text": "javascript-date"
},
{
"code": null,
"e": 29014,
"s": 28993,
"text": "javascript-functions"
},
{
"code": null,
"e": 29025,
"s": 29014,
"text": "JavaScript"
},
{
"code": null,
"e": 29042,
"s": 29025,
"text": "Web Technologies"
},
{
"code": null,
"e": 29140,
"s": 29042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29180,
"s": 29140,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29241,
"s": 29180,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29282,
"s": 29241,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29304,
"s": 29282,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29358,
"s": 29304,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29398,
"s": 29358,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29431,
"s": 29398,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29474,
"s": 29431,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29536,
"s": 29474,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Cards in React-Bootstrap - GeeksforGeeks
|
16 Feb, 2021
Introduction: React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap. Cards are a type of section or containers which consists of information in a structured and organized way.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.
Properties: The Card component has many properties that we can use to organize data. In below table, the properties are explained
Title: It acts as a title for the card.
SubTitle: It acts as a subtitle for the mentioned title.
Text: In this section, we will mention all the necessary data.
Link: This property is used to add the links for our cards.
npm install react-bootstrap bootstrap
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import Card from "react-bootstrap/Card";import React from "react"; export default function App() { return ( <> <Card style={{ width: "22rem" }}> <Card.Body> <Card.Title style={{ color: "green" }}>GEEKSFORGEEKS</Card.Title> <Card.Subtitle className="mb-2 text-muted"> One Stop For all CS subjects </Card.Subtitle> <Card.Text> GeeksforGeeks provides a platform for all the students to study about all the subjects in CSE. </Card.Text> <Card.Link href="#"> For Students</Card.Link> </Card.Body> </Card> </> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Picked
React-Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to redirect to another page in ReactJS ?
|
[
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 26458,
"s": 26169,
"text": "Introduction: React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap. Cards are a type of section or containers which consists of information in a structured and organized way. "
},
{
"code": null,
"e": 26508,
"s": 26458,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26572,
"s": 26508,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 26604,
"s": 26572,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26704,
"s": 26604,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 26718,
"s": 26704,
"text": "cd foldername"
},
{
"code": null,
"e": 26824,
"s": 26718,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command."
},
{
"code": null,
"e": 26954,
"s": 26824,
"text": "Properties: The Card component has many properties that we can use to organize data. In below table, the properties are explained"
},
{
"code": null,
"e": 26994,
"s": 26954,
"text": "Title: It acts as a title for the card."
},
{
"code": null,
"e": 27051,
"s": 26994,
"text": "SubTitle: It acts as a subtitle for the mentioned title."
},
{
"code": null,
"e": 27114,
"s": 27051,
"text": "Text: In this section, we will mention all the necessary data."
},
{
"code": null,
"e": 27174,
"s": 27114,
"text": "Link: This property is used to add the links for our cards."
},
{
"code": null,
"e": 27212,
"s": 27174,
"text": "npm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 27264,
"s": 27212,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27282,
"s": 27264,
"text": "Project Structure"
},
{
"code": null,
"e": 27411,
"s": 27282,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27422,
"s": 27411,
"text": "Javascript"
},
{
"code": "import Card from \"react-bootstrap/Card\";import React from \"react\"; export default function App() { return ( <> <Card style={{ width: \"22rem\" }}> <Card.Body> <Card.Title style={{ color: \"green\" }}>GEEKSFORGEEKS</Card.Title> <Card.Subtitle className=\"mb-2 text-muted\"> One Stop For all CS subjects </Card.Subtitle> <Card.Text> GeeksforGeeks provides a platform for all the students to study about all the subjects in CSE. </Card.Text> <Card.Link href=\"#\"> For Students</Card.Link> </Card.Body> </Card> </> );}",
"e": 28050,
"s": 27422,
"text": null
},
{
"code": null,
"e": 28163,
"s": 28050,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28173,
"s": 28163,
"text": "npm start"
},
{
"code": null,
"e": 28272,
"s": 28173,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 28279,
"s": 28272,
"text": "Picked"
},
{
"code": null,
"e": 28295,
"s": 28279,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 28312,
"s": 28295,
"text": "Web Technologies"
},
{
"code": null,
"e": 28410,
"s": 28312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28450,
"s": 28410,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28495,
"s": 28450,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28538,
"s": 28495,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28599,
"s": 28538,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28671,
"s": 28599,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28726,
"s": 28671,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 28771,
"s": 28726,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 28812,
"s": 28771,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28836,
"s": 28812,
"text": "REST API (Introduction)"
}
] |
PositiveIntegerField - Django Models - GeeksforGeeks
|
12 Feb, 2020
PositiveIntegerField is a integer number represented in Python by a int instance. This field is like a IntegerField but must be either positive or zero (0). The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from 0 to 2147483647 are safe in all databases supported by Django.It uses MinValueValidator and MaxValueValidator to validate the input based on the values that the default database supports.
Syntax:
field_name = models.PositiveIntegerField(**options)
Illustration of PositiveIntegerField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.PositiveIntegerField()
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.PositiveIntegerField()), ], ), ]
Now run,
Python manage.py migrate
Thus, an geeks_field PositiveIntegerField is created when you run migrations on the project. It is a field to store positive integer numbers.
PositiveIntegerField is used for storing a integer number represented in Python by a int instance. To know more about int, visit Python | int() function. Let’s try to save a positive number in PositiveIntegerField.
# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# intd = int(2189) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()
Now let’s check it in admin server. We have created an instance of GeeksModel.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to PositiveIntegerField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an PositiveIntegerField can use.
NaveenArora
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sum() function in Python
Python String | replace()
Defaultdict in Python
Python Dictionary
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Stack in Python
Bar Plot in Matplotlib
|
[
{
"code": null,
"e": 25559,
"s": 25531,
"text": "\n12 Feb, 2020"
},
{
"code": null,
"e": 26031,
"s": 25559,
"text": "PositiveIntegerField is a integer number represented in Python by a int instance. This field is like a IntegerField but must be either positive or zero (0). The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from 0 to 2147483647 are safe in all databases supported by Django.It uses MinValueValidator and MaxValueValidator to validate the input based on the values that the default database supports."
},
{
"code": null,
"e": 26039,
"s": 26031,
"text": "Syntax:"
},
{
"code": null,
"e": 26091,
"s": 26039,
"text": "field_name = models.PositiveIntegerField(**options)"
},
{
"code": null,
"e": 26212,
"s": 26091,
"text": "Illustration of PositiveIntegerField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 26299,
"s": 26212,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 26350,
"s": 26299,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 26383,
"s": 26350,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 26442,
"s": 26383,
"text": "Enter the following code into models.py file of geeks app."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.PositiveIntegerField()",
"e": 26604,
"s": 26442,
"text": null
},
{
"code": null,
"e": 26640,
"s": 26604,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 26878,
"s": 26640,
"text": null
},
{
"code": null,
"e": 26936,
"s": 26878,
"text": "Now when we run makemigrations command from the terminal,"
},
{
"code": null,
"e": 26968,
"s": 26936,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 27068,
"s": 26968,
"text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py"
},
{
"code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.PositiveIntegerField()), ], ), ]",
"e": 27683,
"s": 27068,
"text": null
},
{
"code": null,
"e": 27692,
"s": 27683,
"text": "Now run,"
},
{
"code": null,
"e": 27717,
"s": 27692,
"text": "Python manage.py migrate"
},
{
"code": null,
"e": 27859,
"s": 27717,
"text": "Thus, an geeks_field PositiveIntegerField is created when you run migrations on the project. It is a field to store positive integer numbers."
},
{
"code": null,
"e": 28074,
"s": 27859,
"text": "PositiveIntegerField is used for storing a integer number represented in Python by a int instance. To know more about int, visit Python | int() function. Let’s try to save a positive number in PositiveIntegerField."
},
{
"code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# intd = int(2189) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()",
"e": 28305,
"s": 28074,
"text": null
},
{
"code": null,
"e": 28384,
"s": 28305,
"text": "Now let’s check it in admin server. We have created an instance of GeeksModel."
},
{
"code": null,
"e": 28752,
"s": 28384,
"text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to PositiveIntegerField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an PositiveIntegerField can use."
},
{
"code": null,
"e": 28764,
"s": 28752,
"text": "NaveenArora"
},
{
"code": null,
"e": 28778,
"s": 28764,
"text": "Django-models"
},
{
"code": null,
"e": 28792,
"s": 28778,
"text": "Python Django"
},
{
"code": null,
"e": 28799,
"s": 28792,
"text": "Python"
},
{
"code": null,
"e": 28897,
"s": 28799,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28922,
"s": 28897,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28948,
"s": 28922,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28970,
"s": 28948,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28988,
"s": 28970,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29020,
"s": 28988,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29036,
"s": 29020,
"text": "Deque in Python"
},
{
"code": null,
"e": 29078,
"s": 29036,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29107,
"s": 29078,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29123,
"s": 29107,
"text": "Stack in Python"
}
] |
Getting Started With ImageIO Library in Python - GeeksforGeeks
|
20 Aug, 2020
Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, volumetric data, and scientific formats. It is cross-platform.
This module does not come built-in with Python. To install it type the below command in the terminal.
pip install imageio
Python 3.5+
Numpy
Pillow
For accessing input images files click here. Let’s see the code for some working of imageio library:
1) Read an image: For reading an image we have to used imageio.imread() method.
Syntax: imageio.imread(“filename or path”)
Parameter:
filename/path: Absolute or Relative path of the image file.
Return: returns a numpy array, which comes with a dict of meta data at its ‘meta’ attribute.
Example:
Python3
# import libraryimport imageio # read an imageimage = imageio.imread('testa.png') # print shape of the imageprint(image.shape)
Output:
(134, 151, 4)
2) Reading GIF file: For reading a GIF file we have to used imageio.get_reader() method.
Syntax: imageio.get_reader(filename, format, mode)
Parameters:
path/filename: FileName of required image/file/gif .
format: str, The format to used to read the file, By default imageio select the appropriate for you ,based on the filename and its contents.
mode: {‘i’, ‘I’, ‘v’, ‘V’, ‘?’}Used to give the reader a hint on what the user expects (default “?”):‘i’ for an imageI’ for multiple images‘v’ for a volume‘V’ for multiple volumes?’ for don’t care
Used to give the reader a hint on what the user expects (default “?”):
‘i’ for an image
I’ for multiple images
‘v’ for a volume
‘V’ for multiple volumes
?’ for don’t care
Returns: Reader`object which can be used to read data and meta-data from the specified file.
Example:
Python3
# import libraryimport imageio # create an image objectimage = imageio.get_reader('test.gif') # iterating through matrix:for i in image : # Each frame is a numpy matrix print(i.shape)
Output:
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
(300, 354, 4)
3) Creating Image file: For creating an image file we have to used imageio.imwrite() method.
Syntax: imageio.imwrite(filename,numPy_ndarray, format=None)
Parameters:
filename: Path / Name of file to be saved as
numpy_ndarray: The image data. Must be NxM, NxMx3 or NxMx4.
format: str, The format to used to read the file. By default, imageio selects, the appropriate for you, based on the filename and its contents.
Example:
Python3
# import required librariesimport imageioimport numpy as np rows, cols = (5, 5) # create numpy 2-d arrayarr = np.zeros((rows, cols)) # create an imageimage = imageio.imwrite('image_writing.png', arr)
Output:
image_writing.png.png
As Data-values were zeros so this is empty image with 68 bytes size.
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 25758,
"s": 25562,
"text": "Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, volumetric data, and scientific formats. It is cross-platform."
},
{
"code": null,
"e": 25860,
"s": 25758,
"text": "This module does not come built-in with Python. To install it type the below command in the terminal."
},
{
"code": null,
"e": 25880,
"s": 25860,
"text": "pip install imageio"
},
{
"code": null,
"e": 25892,
"s": 25880,
"text": "Python 3.5+"
},
{
"code": null,
"e": 25899,
"s": 25892,
"text": "Numpy "
},
{
"code": null,
"e": 25907,
"s": 25899,
"text": "Pillow "
},
{
"code": null,
"e": 26008,
"s": 25907,
"text": "For accessing input images files click here. Let’s see the code for some working of imageio library:"
},
{
"code": null,
"e": 26088,
"s": 26008,
"text": "1) Read an image: For reading an image we have to used imageio.imread() method."
},
{
"code": null,
"e": 26131,
"s": 26088,
"text": "Syntax: imageio.imread(“filename or path”)"
},
{
"code": null,
"e": 26142,
"s": 26131,
"text": "Parameter:"
},
{
"code": null,
"e": 26203,
"s": 26142,
"text": " filename/path: Absolute or Relative path of the image file."
},
{
"code": null,
"e": 26296,
"s": 26203,
"text": "Return: returns a numpy array, which comes with a dict of meta data at its ‘meta’ attribute."
},
{
"code": null,
"e": 26305,
"s": 26296,
"text": "Example:"
},
{
"code": null,
"e": 26313,
"s": 26305,
"text": "Python3"
},
{
"code": "# import libraryimport imageio # read an imageimage = imageio.imread('testa.png') # print shape of the imageprint(image.shape) ",
"e": 26443,
"s": 26313,
"text": null
},
{
"code": null,
"e": 26451,
"s": 26443,
"text": "Output:"
},
{
"code": null,
"e": 26465,
"s": 26451,
"text": "(134, 151, 4)"
},
{
"code": null,
"e": 26554,
"s": 26465,
"text": "2) Reading GIF file: For reading a GIF file we have to used imageio.get_reader() method."
},
{
"code": null,
"e": 26605,
"s": 26554,
"text": "Syntax: imageio.get_reader(filename, format, mode)"
},
{
"code": null,
"e": 26617,
"s": 26605,
"text": "Parameters:"
},
{
"code": null,
"e": 26670,
"s": 26617,
"text": "path/filename: FileName of required image/file/gif ."
},
{
"code": null,
"e": 26811,
"s": 26670,
"text": "format: str, The format to used to read the file, By default imageio select the appropriate for you ,based on the filename and its contents."
},
{
"code": null,
"e": 27013,
"s": 26811,
"text": " mode: {‘i’, ‘I’, ‘v’, ‘V’, ‘?’}Used to give the reader a hint on what the user expects (default “?”):‘i’ for an imageI’ for multiple images‘v’ for a volume‘V’ for multiple volumes?’ for don’t care "
},
{
"code": null,
"e": 27084,
"s": 27013,
"text": "Used to give the reader a hint on what the user expects (default “?”):"
},
{
"code": null,
"e": 27101,
"s": 27084,
"text": "‘i’ for an image"
},
{
"code": null,
"e": 27124,
"s": 27101,
"text": "I’ for multiple images"
},
{
"code": null,
"e": 27141,
"s": 27124,
"text": "‘v’ for a volume"
},
{
"code": null,
"e": 27166,
"s": 27141,
"text": "‘V’ for multiple volumes"
},
{
"code": null,
"e": 27188,
"s": 27166,
"text": "?’ for don’t care "
},
{
"code": null,
"e": 27281,
"s": 27188,
"text": "Returns: Reader`object which can be used to read data and meta-data from the specified file."
},
{
"code": null,
"e": 27290,
"s": 27281,
"text": "Example:"
},
{
"code": null,
"e": 27298,
"s": 27290,
"text": "Python3"
},
{
"code": "# import libraryimport imageio # create an image objectimage = imageio.get_reader('test.gif') # iterating through matrix:for i in image : # Each frame is a numpy matrix print(i.shape)",
"e": 27490,
"s": 27298,
"text": null
},
{
"code": null,
"e": 27498,
"s": 27490,
"text": "Output:"
},
{
"code": null,
"e": 27722,
"s": 27498,
"text": "(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)\n(300, 354, 4)"
},
{
"code": null,
"e": 27815,
"s": 27722,
"text": "3) Creating Image file: For creating an image file we have to used imageio.imwrite() method."
},
{
"code": null,
"e": 27877,
"s": 27815,
"text": "Syntax: imageio.imwrite(filename,numPy_ndarray, format=None) "
},
{
"code": null,
"e": 27889,
"s": 27877,
"text": "Parameters:"
},
{
"code": null,
"e": 27934,
"s": 27889,
"text": "filename: Path / Name of file to be saved as"
},
{
"code": null,
"e": 27994,
"s": 27934,
"text": "numpy_ndarray: The image data. Must be NxM, NxMx3 or NxMx4."
},
{
"code": null,
"e": 28138,
"s": 27994,
"text": "format: str, The format to used to read the file. By default, imageio selects, the appropriate for you, based on the filename and its contents."
},
{
"code": null,
"e": 28147,
"s": 28138,
"text": "Example:"
},
{
"code": null,
"e": 28155,
"s": 28147,
"text": "Python3"
},
{
"code": "# import required librariesimport imageioimport numpy as np rows, cols = (5, 5) # create numpy 2-d arrayarr = np.zeros((rows, cols)) # create an imageimage = imageio.imwrite('image_writing.png', arr)",
"e": 28382,
"s": 28155,
"text": null
},
{
"code": null,
"e": 28390,
"s": 28382,
"text": "Output:"
},
{
"code": null,
"e": 28412,
"s": 28390,
"text": "image_writing.png.png"
},
{
"code": null,
"e": 28481,
"s": 28412,
"text": "As Data-values were zeros so this is empty image with 68 bytes size."
},
{
"code": null,
"e": 28496,
"s": 28481,
"text": "python-modules"
},
{
"code": null,
"e": 28503,
"s": 28496,
"text": "Python"
},
{
"code": null,
"e": 28601,
"s": 28503,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28633,
"s": 28601,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28675,
"s": 28633,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28717,
"s": 28675,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28744,
"s": 28717,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28800,
"s": 28744,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28822,
"s": 28800,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28861,
"s": 28822,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28892,
"s": 28861,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28921,
"s": 28892,
"text": "Create a directory in Python"
}
] |
HTML | <input> Hidden attribute - GeeksforGeeks
|
28 Oct, 2020
The HTML input hidden attribute is used to define the visibility of Input field elements. It contains a boolean value. If this attribute is used then browsers will not display elements that have the hidden attribute specified. The hidden attribute can be seen using some condition or JavaScript used to see the hidden content.
Syntax:
<input hidden>
Example:
<!DOCTYPE html><html> <head> <title>input hidden attribute</title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <input>hidden attribute</h2> <!-- hidden attribute --> <input type="text" hidden> </body> </html>
Output:
Supported Browsers: The browsers supported by <input> Hidden attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
arorakashish0911
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26039,
"s": 26011,
"text": "\n28 Oct, 2020"
},
{
"code": null,
"e": 26366,
"s": 26039,
"text": "The HTML input hidden attribute is used to define the visibility of Input field elements. It contains a boolean value. If this attribute is used then browsers will not display elements that have the hidden attribute specified. The hidden attribute can be seen using some condition or JavaScript used to see the hidden content."
},
{
"code": null,
"e": 26374,
"s": 26366,
"text": "Syntax:"
},
{
"code": null,
"e": 26389,
"s": 26374,
"text": "<input hidden>"
},
{
"code": null,
"e": 26398,
"s": 26389,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>input hidden attribute</title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <input>hidden attribute</h2> <!-- hidden attribute --> <input type=\"text\" hidden> </body> </html>",
"e": 26763,
"s": 26398,
"text": null
},
{
"code": null,
"e": 26771,
"s": 26763,
"text": "Output:"
},
{
"code": null,
"e": 26860,
"s": 26771,
"text": "Supported Browsers: The browsers supported by <input> Hidden attribute are listed below:"
},
{
"code": null,
"e": 26874,
"s": 26860,
"text": "Google Chrome"
},
{
"code": null,
"e": 26892,
"s": 26874,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26900,
"s": 26892,
"text": "Firefox"
},
{
"code": null,
"e": 26913,
"s": 26900,
"text": "Apple Safari"
},
{
"code": null,
"e": 26919,
"s": 26913,
"text": "Opera"
},
{
"code": null,
"e": 27056,
"s": 26919,
"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": 27073,
"s": 27056,
"text": "arorakashish0911"
},
{
"code": null,
"e": 27089,
"s": 27073,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 27094,
"s": 27089,
"text": "HTML"
},
{
"code": null,
"e": 27111,
"s": 27094,
"text": "Web Technologies"
},
{
"code": null,
"e": 27116,
"s": 27111,
"text": "HTML"
},
{
"code": null,
"e": 27214,
"s": 27116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27262,
"s": 27214,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27312,
"s": 27262,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27336,
"s": 27312,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27386,
"s": 27336,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27423,
"s": 27386,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27463,
"s": 27423,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27496,
"s": 27463,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27541,
"s": 27496,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27584,
"s": 27541,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Program to find Sum of a Series a^1/1! + a^2/2! + a^3/3! + a^4/4! +.......+ a^n/n! - GeeksforGeeks
|
02 Nov, 2021
Given two values ‘a’ and ‘n’, find sum of series a^1/1! + a^2/2! + a^3/3! + a^4/4! +.......+ a^n/n!.Examples :
Input : a = 2 and n = 5
Output : 6.26667
We get result by adding
2^1/1! + 2^2/2! + 2^3/3! + 2^4/4! +
2^5/5!
= 2/1 + 4/2 + 8/6 + 16/24 + 32/120
= 6.26667
A simple solution is to one by one compute values of individual terms and keep adding them to result.We can find solution with only one loop. The idea is to just use previous values and multiply by (a/i) where i is the no of term which we need to find.
for finding 1st term:- a/1
for finding 2nd term:- (1st term) * a/2
for finding 3rd term:- (2nd term) * a/3
.
.
.
for finding nth term:- ((n-1)th term) * a/n
Illustration:
Input: a = 2 and n = 5
By multiplying Each term by 2/i
1st term :- 2/1 = 2
2nd term :- (1st term) * 2/2 =(2)*1 = 2
3rd term :- (2nd term) * 2/3 = 4/3
4th term :- (3rd term) * 2/4 = 2/3
5th term :- (4th term) * 2/5 = 4/15
=> 2 + 2 + 4/3 + 2/3 + 4/15
Output: sum = 6.26667
Complexity:O(n)
CPP
Java
Python3
C#
PHP
Javascript
/*CPP program to print the sum of series */#include<bits/stdc++.h>using namespace std; /*function to calculate sum of given series*/double sumOfSeries(double a,double num){ double res = 0,prev=1; for (int i = 1; i <= num; i++) { /*multiply (a/i) to previous term*/ prev *= (a/i); /*store result in res*/ res = res + prev; } return(res);} /* Driver Function */int main(){ double n = 5, a=2; cout << sumOfSeries(a,n); return 0;}
// Java program to print the// sum of seriesimport java.io.*; class GFG{ public static void main (String[] args) { double n = 5, a = 2; System.out.println(sumOfSeries(a, n)); } // function to calculate sum of given series static double sumOfSeries(double a,double n) { double res = 0, prev = 1; for (int i = 1; i <= n; i++) { // multiply (a/i) to previous term prev *= (a / i); // store result in res res = res + prev; } return(res); }} // This code is Contributed by Azkia Anam.
# Python program to print# the sum of series.# function to calculate# sum of given series. from __future__ import division def sumOfSeries(a,num): res = 0 prev=1 for i in range(1, n+1): # multiply (a/i) to # previous term prev *= (a/i) # store result in res res = res + prev return res # Driver coden = 5a = 2print(round(sumOfSeries(a,n),4)) # This Code is Contributed# by Azkia Anam.
// C# program to print the// sum of seriesusing System; class GFG{ public static void Main () { double n = 5, a = 2; Console.WriteLine(sumOfSeries(a, n)); } // Function to calculate sum of given series static float sumOfSeries(double a, double n) { double res = 0, prev = 1; for (int i = 1; i <= n; i++) { // multiply (a/i) to previous term prev *= (a / i); // store result in res res = res + prev; } return(float)(res); }} // This code is Contributed by vt_m.
<?php// PHP program to print// the sum of series // Function to calculate// sum of given seriesfunction sumOfSeries($a, $num){ $res = 0; $prev = 1; for ($i = 1; $i <= $num; $i++) { // multiply (a/i) to // previous term $prev *= ($a / $i); // store result in res $res = $res + $prev; } return ($res);} // Driver Code$n = 5; $a = 2;echo(sumOfSeries($a, $n)); // This code is contributed by Ajit.?>
<script>/* JavaScript program to print the sum of series */ /*function to calculate sum of given series*/function sumOfSeries(a, num){ let res = 0, prev = 1; for (let i = 1; i <= num; i++) { /*multiply (a/i) to previous term*/ prev *= (a/i); /*store result in res*/ res = res + prev; } return(res);} /* Driver Function */ let n = 5, a=2; document.write(sumOfSeries(a,n)); // This code is contributed by Surbhi Tyagi.</script>
Output :
6.26667
Time Complexity: O(n)
Auxiliary Space: O(1)
This article is contributed by R_Raj. 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.
jit_t
arorakashish0911
surbhityagi15
subhammahato348
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Print all possible combinations of r elements in a given array of size n
Segment Tree | Set 1 (Sum of given range)
The Knight's tour problem | Backtracking-1
Product of Array except itself
Write a program to reverse digits of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Ugly Numbers
Program to multiply two matrices
|
[
{
"code": null,
"e": 26583,
"s": 26555,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 26696,
"s": 26583,
"text": "Given two values ‘a’ and ‘n’, find sum of series a^1/1! + a^2/2! + a^3/3! + a^4/4! +.......+ a^n/n!.Examples : "
},
{
"code": null,
"e": 26853,
"s": 26696,
"text": "Input : a = 2 and n = 5\nOutput : 6.26667\nWe get result by adding \n2^1/1! + 2^2/2! + 2^3/3! + 2^4/4! +\n2^5/5! \n= 2/1 + 4/2 + 8/6 + 16/24 + 32/120\n= 6.26667"
},
{
"code": null,
"e": 27109,
"s": 26855,
"text": "A simple solution is to one by one compute values of individual terms and keep adding them to result.We can find solution with only one loop. The idea is to just use previous values and multiply by (a/i) where i is the no of term which we need to find. "
},
{
"code": null,
"e": 27270,
"s": 27109,
"text": "for finding 1st term:- a/1\nfor finding 2nd term:- (1st term) * a/2\nfor finding 3rd term:- (2nd term) * a/3\n.\n.\n.\nfor finding nth term:- ((n-1)th term) * a/n"
},
{
"code": null,
"e": 27286,
"s": 27270,
"text": "Illustration: "
},
{
"code": null,
"e": 27580,
"s": 27286,
"text": "Input: a = 2 and n = 5\nBy multiplying Each term by 2/i\n 1st term :- 2/1 = 2\n 2nd term :- (1st term) * 2/2 =(2)*1 = 2\n 3rd term :- (2nd term) * 2/3 = 4/3\n 4th term :- (3rd term) * 2/4 = 2/3\n 5th term :- (4th term) * 2/5 = 4/15\n=> 2 + 2 + 4/3 + 2/3 + 4/15\nOutput: sum = 6.26667"
},
{
"code": null,
"e": 27598,
"s": 27580,
"text": "Complexity:O(n) "
},
{
"code": null,
"e": 27602,
"s": 27598,
"text": "CPP"
},
{
"code": null,
"e": 27607,
"s": 27602,
"text": "Java"
},
{
"code": null,
"e": 27615,
"s": 27607,
"text": "Python3"
},
{
"code": null,
"e": 27618,
"s": 27615,
"text": "C#"
},
{
"code": null,
"e": 27622,
"s": 27618,
"text": "PHP"
},
{
"code": null,
"e": 27633,
"s": 27622,
"text": "Javascript"
},
{
"code": "/*CPP program to print the sum of series */#include<bits/stdc++.h>using namespace std; /*function to calculate sum of given series*/double sumOfSeries(double a,double num){ double res = 0,prev=1; for (int i = 1; i <= num; i++) { /*multiply (a/i) to previous term*/ prev *= (a/i); /*store result in res*/ res = res + prev; } return(res);} /* Driver Function */int main(){ double n = 5, a=2; cout << sumOfSeries(a,n); return 0;}",
"e": 28113,
"s": 27633,
"text": null
},
{
"code": "// Java program to print the// sum of seriesimport java.io.*; class GFG{ public static void main (String[] args) { double n = 5, a = 2; System.out.println(sumOfSeries(a, n)); } // function to calculate sum of given series static double sumOfSeries(double a,double n) { double res = 0, prev = 1; for (int i = 1; i <= n; i++) { // multiply (a/i) to previous term prev *= (a / i); // store result in res res = res + prev; } return(res); }} // This code is Contributed by Azkia Anam.",
"e": 28757,
"s": 28113,
"text": null
},
{
"code": "# Python program to print# the sum of series.# function to calculate# sum of given series. from __future__ import division def sumOfSeries(a,num): res = 0 prev=1 for i in range(1, n+1): # multiply (a/i) to # previous term prev *= (a/i) # store result in res res = res + prev return res # Driver coden = 5a = 2print(round(sumOfSeries(a,n),4)) # This Code is Contributed# by Azkia Anam.",
"e": 29191,
"s": 28757,
"text": null
},
{
"code": "// C# program to print the// sum of seriesusing System; class GFG{ public static void Main () { double n = 5, a = 2; Console.WriteLine(sumOfSeries(a, n)); } // Function to calculate sum of given series static float sumOfSeries(double a, double n) { double res = 0, prev = 1; for (int i = 1; i <= n; i++) { // multiply (a/i) to previous term prev *= (a / i); // store result in res res = res + prev; } return(float)(res); }} // This code is Contributed by vt_m.",
"e": 29816,
"s": 29191,
"text": null
},
{
"code": "<?php// PHP program to print// the sum of series // Function to calculate// sum of given seriesfunction sumOfSeries($a, $num){ $res = 0; $prev = 1; for ($i = 1; $i <= $num; $i++) { // multiply (a/i) to // previous term $prev *= ($a / $i); // store result in res $res = $res + $prev; } return ($res);} // Driver Code$n = 5; $a = 2;echo(sumOfSeries($a, $n)); // This code is contributed by Ajit.?>",
"e": 30263,
"s": 29816,
"text": null
},
{
"code": "<script>/* JavaScript program to print the sum of series */ /*function to calculate sum of given series*/function sumOfSeries(a, num){ let res = 0, prev = 1; for (let i = 1; i <= num; i++) { /*multiply (a/i) to previous term*/ prev *= (a/i); /*store result in res*/ res = res + prev; } return(res);} /* Driver Function */ let n = 5, a=2; document.write(sumOfSeries(a,n)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 30744,
"s": 30263,
"text": null
},
{
"code": null,
"e": 30755,
"s": 30744,
"text": "Output : "
},
{
"code": null,
"e": 30763,
"s": 30755,
"text": "6.26667"
},
{
"code": null,
"e": 30785,
"s": 30763,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 30807,
"s": 30785,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31221,
"s": 30807,
"text": "This article is contributed by R_Raj. 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": 31227,
"s": 31221,
"text": "jit_t"
},
{
"code": null,
"e": 31244,
"s": 31227,
"text": "arorakashish0911"
},
{
"code": null,
"e": 31258,
"s": 31244,
"text": "surbhityagi15"
},
{
"code": null,
"e": 31274,
"s": 31258,
"text": "subhammahato348"
},
{
"code": null,
"e": 31281,
"s": 31274,
"text": "series"
},
{
"code": null,
"e": 31294,
"s": 31281,
"text": "Mathematical"
},
{
"code": null,
"e": 31307,
"s": 31294,
"text": "Mathematical"
},
{
"code": null,
"e": 31314,
"s": 31307,
"text": "series"
},
{
"code": null,
"e": 31412,
"s": 31314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31455,
"s": 31412,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31528,
"s": 31455,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 31570,
"s": 31528,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 31613,
"s": 31570,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 31644,
"s": 31613,
"text": "Product of Array except itself"
},
{
"code": null,
"e": 31690,
"s": 31644,
"text": "Write a program to reverse digits of a number"
},
{
"code": null,
"e": 31743,
"s": 31690,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 31792,
"s": 31743,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31805,
"s": 31792,
"text": "Ugly Numbers"
}
] |
GUI chat application using Tkinter in Python - GeeksforGeeks
|
01 Oct, 2021
Prerequisites: Tkinter, Socket Programming, and Multithreading
This is a simple GUI (Graphical User Interface) chat application where multiple users can connect with each other in a client-server architecture i.e the clients will interact with the help of the server.
Server Side Script: This script file name is ‘client.py'(say).Since only the clients will interact the server script does not have a GUI
Python3
# import socket libraryimport socket # import threading libraryimport threading # Choose a port that is freePORT = 5000 # An IPv4 address is obtained# for the server. SERVER = socket.gethostbyname(socket.gethostname()) # Address is stored as a tupleADDRESS = (SERVER, PORT) # the format in which encoding# and decoding will occurFORMAT = "utf-8" # Lists that will contains# all the clients connected to# the server and their names.clients, names = [], [] # Create a new socket for# the serverserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the address of the# server to the socketserver.bind(ADDRESS) # function to start the connectiondef startChat(): print("server is working on " + SERVER) # listening for connections server.listen() while True: # accept connections and returns # a new connection to the client # and the address bound to it conn, addr = server.accept() conn.send("NAME".encode(FORMAT)) # 1024 represents the max amount # of data that can be received (bytes) name = conn.recv(1024).decode(FORMAT) # append the name and client # to the respective list names.append(name) clients.append(conn) print(f"Name is :{name}") # broadcast message broadcastMessage(f"{name} has joined the chat!".encode(FORMAT)) conn.send('Connection successful!'.encode(FORMAT)) # Start the handling thread thread = threading.Thread(target = handle, args = (conn, addr)) thread.start() # no. of clients connected # to the server print(f"active connections {threading.activeCount()-1}") # method to handle the# incoming messagesdef handle(conn, addr): print(f"new connection {addr}") connected = True while connected: # receive message message = conn.recv(1024) # broadcast message broadcastMessage(message) # close the connection conn.close() # method for broadcasting# messages to the each clientsdef broadcastMessage(message): for client in clients: client.send(message) # call the method to# begin the communicationstartChat()
Client-Side Script:
Python3
# import all the required modulesimport socketimport threadingfrom tkinter import *from tkinter import fontfrom tkinter import ttk # import all functions /# everything from chat.py filefrom chat import * PORT = 5050SERVER = "192.168.0.103"ADDRESS = (SERVER, PORT)FORMAT = "utf-8" # Create a new client socket# and connect to the serverclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.connect(ADDRESS) # GUI class for the chatclass GUI: # constructor method def __init__(self): # chat window which is currently hidden self.Window = Tk() self.Window.withdraw() # login window self.login = Toplevel() # set the title self.login.title("Login") self.login.resizable(width = False, height = False) self.login.configure(width = 400, height = 300) # create a Label self.pls = Label(self.login, text = "Please login to continue", justify = CENTER, font = "Helvetica 14 bold") self.pls.place(relheight = 0.15, relx = 0.2, rely = 0.07) # create a Label self.labelName = Label(self.login, text = "Name: ", font = "Helvetica 12") self.labelName.place(relheight = 0.2, relx = 0.1, rely = 0.2) # create a entry box for # tyoing the message self.entryName = Entry(self.login, font = "Helvetica 14") self.entryName.place(relwidth = 0.4, relheight = 0.12, relx = 0.35, rely = 0.2) # set the focus of the cursor self.entryName.focus() # create a Continue Button # along with action self.go = Button(self.login, text = "CONTINUE", font = "Helvetica 14 bold", command = lambda: self.goAhead(self.entryName.get())) self.go.place(relx = 0.4, rely = 0.55) self.Window.mainloop() def goAhead(self, name): self.login.destroy() self.layout(name) # the thread to receive messages rcv = threading.Thread(target=self.receive) rcv.start() # The main layout of the chat def layout(self,name): self.name = name # to show chat window self.Window.deiconify() self.Window.title("CHATROOM") self.Window.resizable(width = False, height = False) self.Window.configure(width = 470, height = 550, bg = "#17202A") self.labelHead = Label(self.Window, bg = "#17202A", fg = "#EAECEE", text = self.name , font = "Helvetica 13 bold", pady = 5) self.labelHead.place(relwidth = 1) self.line = Label(self.Window, width = 450, bg = "#ABB2B9") self.line.place(relwidth = 1, rely = 0.07, relheight = 0.012) self.textCons = Text(self.Window, width = 20, height = 2, bg = "#17202A", fg = "#EAECEE", font = "Helvetica 14", padx = 5, pady = 5) self.textCons.place(relheight = 0.745, relwidth = 1, rely = 0.08) self.labelBottom = Label(self.Window, bg = "#ABB2B9", height = 80) self.labelBottom.place(relwidth = 1, rely = 0.825) self.entryMsg = Entry(self.labelBottom, bg = "#2C3E50", fg = "#EAECEE", font = "Helvetica 13") # place the given widget # into the gui window self.entryMsg.place(relwidth = 0.74, relheight = 0.06, rely = 0.008, relx = 0.011) self.entryMsg.focus() # create a Send Button self.buttonMsg = Button(self.labelBottom, text = "Send", font = "Helvetica 10 bold", width = 20, bg = "#ABB2B9", command = lambda : self.sendButton(self.entryMsg.get())) self.buttonMsg.place(relx = 0.77, rely = 0.008, relheight = 0.06, relwidth = 0.22) self.textCons.config(cursor = "arrow") # create a scroll bar scrollbar = Scrollbar(self.textCons) # place the scroll bar # into the gui window scrollbar.place(relheight = 1, relx = 0.974) scrollbar.config(command = self.textCons.yview) self.textCons.config(state = DISABLED) # function to basically start the thread for sending messages def sendButton(self, msg): self.textCons.config(state = DISABLED) self.msg=msg self.entryMsg.delete(0, END) snd= threading.Thread(target = self.sendMessage) snd.start() # function to receive messages def receive(self): while True: try: message = client.recv(1024).decode(FORMAT) # if the messages from the server is NAME send the client's name if message == 'NAME': client.send(self.name.encode(FORMAT)) else: # insert messages to text box self.textCons.config(state = NORMAL) self.textCons.insert(END, message+"\n\n") self.textCons.config(state = DISABLED) self.textCons.see(END) except: # an error will be printed on the command line or console if there's an error print("An error occured!") client.close() break # function to send messages def sendMessage(self): self.textCons.config(state=DISABLED) while True: message = (f"{self.name}: {self.msg}") client.send(message.encode(FORMAT)) break # create a GUI class objectg = GUI()
OUTPUT :
Login Window :
CLIENT 1 :
CLIENT 2 :
CLIENT 3 :
SERVER :
kalrap615
varshagumber28
simranarora5sos
Python Tkinter-exercises
Python-gui
Python-socket
Python-tkinter
Project
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Swing | Simple User Registration Form
Banking Transaction System using Java
Face Detection using Python and OpenCV with webcam
Program for Employee Management System
Snake Game in C
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 26130,
"s": 26067,
"text": "Prerequisites: Tkinter, Socket Programming, and Multithreading"
},
{
"code": null,
"e": 26335,
"s": 26130,
"text": "This is a simple GUI (Graphical User Interface) chat application where multiple users can connect with each other in a client-server architecture i.e the clients will interact with the help of the server."
},
{
"code": null,
"e": 26473,
"s": 26335,
"text": "Server Side Script: This script file name is ‘client.py'(say).Since only the clients will interact the server script does not have a GUI"
},
{
"code": null,
"e": 26481,
"s": 26473,
"text": "Python3"
},
{
"code": "# import socket libraryimport socket # import threading libraryimport threading # Choose a port that is freePORT = 5000 # An IPv4 address is obtained# for the server. SERVER = socket.gethostbyname(socket.gethostname()) # Address is stored as a tupleADDRESS = (SERVER, PORT) # the format in which encoding# and decoding will occurFORMAT = \"utf-8\" # Lists that will contains# all the clients connected to# the server and their names.clients, names = [], [] # Create a new socket for# the serverserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the address of the# server to the socketserver.bind(ADDRESS) # function to start the connectiondef startChat(): print(\"server is working on \" + SERVER) # listening for connections server.listen() while True: # accept connections and returns # a new connection to the client # and the address bound to it conn, addr = server.accept() conn.send(\"NAME\".encode(FORMAT)) # 1024 represents the max amount # of data that can be received (bytes) name = conn.recv(1024).decode(FORMAT) # append the name and client # to the respective list names.append(name) clients.append(conn) print(f\"Name is :{name}\") # broadcast message broadcastMessage(f\"{name} has joined the chat!\".encode(FORMAT)) conn.send('Connection successful!'.encode(FORMAT)) # Start the handling thread thread = threading.Thread(target = handle, args = (conn, addr)) thread.start() # no. of clients connected # to the server print(f\"active connections {threading.activeCount()-1}\") # method to handle the# incoming messagesdef handle(conn, addr): print(f\"new connection {addr}\") connected = True while connected: # receive message message = conn.recv(1024) # broadcast message broadcastMessage(message) # close the connection conn.close() # method for broadcasting# messages to the each clientsdef broadcastMessage(message): for client in clients: client.send(message) # call the method to# begin the communicationstartChat()",
"e": 28806,
"s": 26481,
"text": null
},
{
"code": null,
"e": 28827,
"s": 28806,
"text": "Client-Side Script: "
},
{
"code": null,
"e": 28835,
"s": 28827,
"text": "Python3"
},
{
"code": "# import all the required modulesimport socketimport threadingfrom tkinter import *from tkinter import fontfrom tkinter import ttk # import all functions /# everything from chat.py filefrom chat import * PORT = 5050SERVER = \"192.168.0.103\"ADDRESS = (SERVER, PORT)FORMAT = \"utf-8\" # Create a new client socket# and connect to the serverclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.connect(ADDRESS) # GUI class for the chatclass GUI: # constructor method def __init__(self): # chat window which is currently hidden self.Window = Tk() self.Window.withdraw() # login window self.login = Toplevel() # set the title self.login.title(\"Login\") self.login.resizable(width = False, height = False) self.login.configure(width = 400, height = 300) # create a Label self.pls = Label(self.login, text = \"Please login to continue\", justify = CENTER, font = \"Helvetica 14 bold\") self.pls.place(relheight = 0.15, relx = 0.2, rely = 0.07) # create a Label self.labelName = Label(self.login, text = \"Name: \", font = \"Helvetica 12\") self.labelName.place(relheight = 0.2, relx = 0.1, rely = 0.2) # create a entry box for # tyoing the message self.entryName = Entry(self.login, font = \"Helvetica 14\") self.entryName.place(relwidth = 0.4, relheight = 0.12, relx = 0.35, rely = 0.2) # set the focus of the cursor self.entryName.focus() # create a Continue Button # along with action self.go = Button(self.login, text = \"CONTINUE\", font = \"Helvetica 14 bold\", command = lambda: self.goAhead(self.entryName.get())) self.go.place(relx = 0.4, rely = 0.55) self.Window.mainloop() def goAhead(self, name): self.login.destroy() self.layout(name) # the thread to receive messages rcv = threading.Thread(target=self.receive) rcv.start() # The main layout of the chat def layout(self,name): self.name = name # to show chat window self.Window.deiconify() self.Window.title(\"CHATROOM\") self.Window.resizable(width = False, height = False) self.Window.configure(width = 470, height = 550, bg = \"#17202A\") self.labelHead = Label(self.Window, bg = \"#17202A\", fg = \"#EAECEE\", text = self.name , font = \"Helvetica 13 bold\", pady = 5) self.labelHead.place(relwidth = 1) self.line = Label(self.Window, width = 450, bg = \"#ABB2B9\") self.line.place(relwidth = 1, rely = 0.07, relheight = 0.012) self.textCons = Text(self.Window, width = 20, height = 2, bg = \"#17202A\", fg = \"#EAECEE\", font = \"Helvetica 14\", padx = 5, pady = 5) self.textCons.place(relheight = 0.745, relwidth = 1, rely = 0.08) self.labelBottom = Label(self.Window, bg = \"#ABB2B9\", height = 80) self.labelBottom.place(relwidth = 1, rely = 0.825) self.entryMsg = Entry(self.labelBottom, bg = \"#2C3E50\", fg = \"#EAECEE\", font = \"Helvetica 13\") # place the given widget # into the gui window self.entryMsg.place(relwidth = 0.74, relheight = 0.06, rely = 0.008, relx = 0.011) self.entryMsg.focus() # create a Send Button self.buttonMsg = Button(self.labelBottom, text = \"Send\", font = \"Helvetica 10 bold\", width = 20, bg = \"#ABB2B9\", command = lambda : self.sendButton(self.entryMsg.get())) self.buttonMsg.place(relx = 0.77, rely = 0.008, relheight = 0.06, relwidth = 0.22) self.textCons.config(cursor = \"arrow\") # create a scroll bar scrollbar = Scrollbar(self.textCons) # place the scroll bar # into the gui window scrollbar.place(relheight = 1, relx = 0.974) scrollbar.config(command = self.textCons.yview) self.textCons.config(state = DISABLED) # function to basically start the thread for sending messages def sendButton(self, msg): self.textCons.config(state = DISABLED) self.msg=msg self.entryMsg.delete(0, END) snd= threading.Thread(target = self.sendMessage) snd.start() # function to receive messages def receive(self): while True: try: message = client.recv(1024).decode(FORMAT) # if the messages from the server is NAME send the client's name if message == 'NAME': client.send(self.name.encode(FORMAT)) else: # insert messages to text box self.textCons.config(state = NORMAL) self.textCons.insert(END, message+\"\\n\\n\") self.textCons.config(state = DISABLED) self.textCons.see(END) except: # an error will be printed on the command line or console if there's an error print(\"An error occured!\") client.close() break # function to send messages def sendMessage(self): self.textCons.config(state=DISABLED) while True: message = (f\"{self.name}: {self.msg}\") client.send(message.encode(FORMAT)) break # create a GUI class objectg = GUI()",
"e": 35970,
"s": 28835,
"text": null
},
{
"code": null,
"e": 35980,
"s": 35970,
"text": "OUTPUT : "
},
{
"code": null,
"e": 35996,
"s": 35980,
"text": "Login Window : "
},
{
"code": null,
"e": 36008,
"s": 35996,
"text": "CLIENT 1 : "
},
{
"code": null,
"e": 36019,
"s": 36008,
"text": "CLIENT 2 :"
},
{
"code": null,
"e": 36031,
"s": 36019,
"text": " CLIENT 3 :"
},
{
"code": null,
"e": 36041,
"s": 36031,
"text": " SERVER :"
},
{
"code": null,
"e": 36053,
"s": 36043,
"text": "kalrap615"
},
{
"code": null,
"e": 36068,
"s": 36053,
"text": "varshagumber28"
},
{
"code": null,
"e": 36084,
"s": 36068,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36109,
"s": 36084,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 36120,
"s": 36109,
"text": "Python-gui"
},
{
"code": null,
"e": 36134,
"s": 36120,
"text": "Python-socket"
},
{
"code": null,
"e": 36149,
"s": 36134,
"text": "Python-tkinter"
},
{
"code": null,
"e": 36157,
"s": 36149,
"text": "Project"
},
{
"code": null,
"e": 36164,
"s": 36157,
"text": "Python"
},
{
"code": null,
"e": 36180,
"s": 36164,
"text": "Python Programs"
},
{
"code": null,
"e": 36278,
"s": 36180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36321,
"s": 36278,
"text": "Java Swing | Simple User Registration Form"
},
{
"code": null,
"e": 36359,
"s": 36321,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 36410,
"s": 36359,
"text": "Face Detection using Python and OpenCV with webcam"
},
{
"code": null,
"e": 36449,
"s": 36410,
"text": "Program for Employee Management System"
},
{
"code": null,
"e": 36465,
"s": 36449,
"text": "Snake Game in C"
},
{
"code": null,
"e": 36493,
"s": 36465,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 36543,
"s": 36493,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 36565,
"s": 36543,
"text": "Python map() function"
}
] |
Saving Metadata with DataFrames. Saving metadata with DataFrames using... | by Darren Smith | Towards Data Science
|
Metadata is important — okay, perhaps not exactly a life & death issue for most Python data engineers, but its power and utility should not be overlooked. It enriches data with essential context, such as when, where and how it was created. Collection and storage of metadata should be considered a key feature to include in data processing applications.
But how best to do this? If using the popular data analysis toolkit Pandas, how can metadata be stored with the ubiquitous DataFrame?
Unfortunately Pandas doesn’t have great support for metadata. There’s no conventional way to attach metadata to a DataFrame, or for portable storage of combined data & metadata.
The essential challenge is information coupling; how to ensure data & metadata remain linked together, not only during a single Python session, but also as they get persisted and passed from one system to the next. This latter question is our focus here; how can data & metadata be stored together in a portable and durable format?
Naively we might try to save DataFrames as “pickle” files, perhaps adding metadata as a custom attribute or using the experimental attrs. This feels natural, straightforward and initially appears to work. But this approach has serious drawbacks. Pickles can be very specific to the particular version of Python and Pandas used to create them, rendering them unusable by different versions. They are not readily portable to non-Python programs, nor particularly optimised for performance.
Parquet & Arrow approach
We will take a step-by-step look at an alternative approach, based on Parquet and Arrow, which allows a DataFrame and metadata to be persisted together in a single, portable file. Before proceeding to the details, a brief overview of Parquet and Arrow is in order, because these are relatively less familiar technologies.
Apache Parquet is a file format. It has the aim of efficient storage of tabular data. Unlike CSV, in which data is written row by row, Parquet stores data column by column. This approach benefits compression and read/write/query performance. Pandas has supported Parquet since version 0.21, so the familiar DataFrame methods to_csv and to_pickle are now joined by to_parquet. Parquet files typically have extension “.parquet”. A feature relevant to the present discussion is that Parquet supports the inclusion of file-level metadata.
While Parquet describes how data is arranged within files, Apache Arrow is concerned with its layout in memory. Arrow is a cross-language specification that describes how to store columnar data in memory. It serves as the internals of data processing applications & libraries, allowing them to efficiently work with and share large tabular datasets. It has many features, but two of interest here are its ability to convert to and from various Python types (DataFrames, dicts, Numpy arrays etc.), and its support for reading & writing Parquet files.
In the following solution we will first use Arrow to convert a DataFrame to an Arrow table and then attach metadata. This enriched table will then be saved as a Parquet file. Additionally we will see how to restore the DataFrame and metadata from the saved file.
But hang on, why don’t we just call the DataFrame’s to_parquet method to write a Parquet file directly? Well as of Pandas 1.1.4, this method doesn’t support custom metadata, hence we employ a work-around of going via Arrow.
Step-by-step code solution
The code that follows is written using Python 3.6.3, Pandas 0.23.0 and Arrow 2.0.0, all running on Ubuntu 18.04. The complete code can be found on github.
Let’s begin with the imports. We require Pandas, PyArrow (Python bindings for Arrow), Parquet and also JSON (which is used to serialise the metadata).
import pandas as pdimport pyarrow as paimport pyarrow.parquet as pqimport json
We introduce some data we wish to persist. This example imagines a weather IoT device recording a single data item, which is end-of-day values for two time-series variables, max-temperature and rainfall.
df = pd.DataFrame( { 'temp': [12.1, 11, 13, 10, 10], 'rain': [9.2, 10.0, 2.2, 0.2, 0.4] }, index=pd.DatetimeIndex(['2020-10-12', '2020-10-13', '2020-10-14', '2020-10-15', '2020-10-16'], name='date'))
We also introduce some custom metadata. There is no universal format for metadata; typically it’s just key-value pairs, stored as a dict, with optional nesting of further dicts and lists. One caveat is that the value types can serialise to JSON.
custom_meta_content = { 'user': 'Wáng Fān', 'coord': '55.9533° N, 3.1883° W', 'time': '2020-10-17T03:59:59+0000' # ISO-8601}
We require a metadata namespace key. As we will shortly see, the custom metadata will be inserted into a global metadata dict owned by an Arrow table, so we require a unique key to separate our custom metadata from other metadata which may already exist or be inserted later. A good choice is application or organisation name.
custom_meta_key = 'weatherapp.iot'
As noted earlier, our approach is to convert the DataFrame to an Arrow table. We use PyArrow to do this:
table = pa.Table.from_pandas(df)
Out of interest we can inspect this table’s metadata property (a dict instance) to see what it holds by default:
print(table.schema.metadata)
This shows some initial metadata. This has been created by Pandas and inserted with the key b'pandas'. Pandas adds its own metadata so that it can convert from an Arrow table back to a DataFrame.
Now to the add custom metadata to this table. This is not immediately possible because Arrow tables are immutable. Instead we construct a new Arrow table which is a copy of the original but with the metadata replaced; the replacement metadata will be a combination of the existing metadata and the custom metadata.
First to construct the combined metadata. This is a simple merge of the existing table metadata and the custom metadata. There are a few caveats to get this right. The metadata content must be JSON serialisable and encoded as bytes; the metadata key must also be encoded as bytes:
custom_meta_json = json.dumps(custom_meta_content)existing_meta = table.schema.metadatacombined_meta = { custom_meta_key.encode() : custom_meta_json.encode(), **existing_meta}
Next the Arrow table is shallow copied. The copy has the original table metadata replaced by the combined metadata:
table = table.replace_schema_metadata(combined_meta)
The original table has been discarded; only the copy is retained, and is referenced by the reused variable table. This table now contains both the custom metadata and the Pandas metadata. This can be verified with:
print(table.schema.metadata)
Saving to Parquet is straightforward. In this example we request compression, which compresses columns internally:
pq.write_table(table, 'example.parquet', compression='GZIP')
Reverse process
The DataFrame & metadata are now coupled together in single Parquet file, providing portability across programming languages and different versions of Python & Pandas. But how do we load this file to recover both the DataFrame and the metadata?
This reverse task is a lot less fuss. First read the Parquet file into an Arrow table.
restored_table = pq.read_table('example.parquet')
The DataFrame is obtained via a call of the table’s to_pandas conversion method. This operation uses the Pandas metadata to reconstruct the DataFrame, but this is under the hood details that we don’t need to worry about:
restored_df = restored_table.to_pandas()
The custom metadata is accessible via the Arrow table’s metadata object, by providing the custom metadata key used earlier (taking care to once again encode the key as bytes):
restored_meta_json = restored_table.schema.metadata[custom_meta_key.encode()]
This returns the metadata as a JSON string. The final step is to deserialise:
restored_meta = json.loads(restored_meta_json)
The metadata has been restored (in addition to the DataFrame); it is just a plain dict of key-value pairs, exactly as we originally created.
Summary
Metadata should be an important consideration of any data collection and processing system, but how it can be captured and stored is often overlooked.
Pandas lacks a dedicated mechanism for saving metadata to a DataFrame. However we have seen that recent libraries, such as Arrow and Parquet, do provide direct support for persisting DataFrames and metadata together in highly portable and performant files
Having a simple & conventional approach to couple data & metadata is the first step to its wider integration into our applications.
|
[
{
"code": null,
"e": 526,
"s": 172,
"text": "Metadata is important — okay, perhaps not exactly a life & death issue for most Python data engineers, but its power and utility should not be overlooked. It enriches data with essential context, such as when, where and how it was created. Collection and storage of metadata should be considered a key feature to include in data processing applications."
},
{
"code": null,
"e": 660,
"s": 526,
"text": "But how best to do this? If using the popular data analysis toolkit Pandas, how can metadata be stored with the ubiquitous DataFrame?"
},
{
"code": null,
"e": 838,
"s": 660,
"text": "Unfortunately Pandas doesn’t have great support for metadata. There’s no conventional way to attach metadata to a DataFrame, or for portable storage of combined data & metadata."
},
{
"code": null,
"e": 1170,
"s": 838,
"text": "The essential challenge is information coupling; how to ensure data & metadata remain linked together, not only during a single Python session, but also as they get persisted and passed from one system to the next. This latter question is our focus here; how can data & metadata be stored together in a portable and durable format?"
},
{
"code": null,
"e": 1658,
"s": 1170,
"text": "Naively we might try to save DataFrames as “pickle” files, perhaps adding metadata as a custom attribute or using the experimental attrs. This feels natural, straightforward and initially appears to work. But this approach has serious drawbacks. Pickles can be very specific to the particular version of Python and Pandas used to create them, rendering them unusable by different versions. They are not readily portable to non-Python programs, nor particularly optimised for performance."
},
{
"code": null,
"e": 1683,
"s": 1658,
"text": "Parquet & Arrow approach"
},
{
"code": null,
"e": 2005,
"s": 1683,
"text": "We will take a step-by-step look at an alternative approach, based on Parquet and Arrow, which allows a DataFrame and metadata to be persisted together in a single, portable file. Before proceeding to the details, a brief overview of Parquet and Arrow is in order, because these are relatively less familiar technologies."
},
{
"code": null,
"e": 2540,
"s": 2005,
"text": "Apache Parquet is a file format. It has the aim of efficient storage of tabular data. Unlike CSV, in which data is written row by row, Parquet stores data column by column. This approach benefits compression and read/write/query performance. Pandas has supported Parquet since version 0.21, so the familiar DataFrame methods to_csv and to_pickle are now joined by to_parquet. Parquet files typically have extension “.parquet”. A feature relevant to the present discussion is that Parquet supports the inclusion of file-level metadata."
},
{
"code": null,
"e": 3090,
"s": 2540,
"text": "While Parquet describes how data is arranged within files, Apache Arrow is concerned with its layout in memory. Arrow is a cross-language specification that describes how to store columnar data in memory. It serves as the internals of data processing applications & libraries, allowing them to efficiently work with and share large tabular datasets. It has many features, but two of interest here are its ability to convert to and from various Python types (DataFrames, dicts, Numpy arrays etc.), and its support for reading & writing Parquet files."
},
{
"code": null,
"e": 3353,
"s": 3090,
"text": "In the following solution we will first use Arrow to convert a DataFrame to an Arrow table and then attach metadata. This enriched table will then be saved as a Parquet file. Additionally we will see how to restore the DataFrame and metadata from the saved file."
},
{
"code": null,
"e": 3577,
"s": 3353,
"text": "But hang on, why don’t we just call the DataFrame’s to_parquet method to write a Parquet file directly? Well as of Pandas 1.1.4, this method doesn’t support custom metadata, hence we employ a work-around of going via Arrow."
},
{
"code": null,
"e": 3604,
"s": 3577,
"text": "Step-by-step code solution"
},
{
"code": null,
"e": 3759,
"s": 3604,
"text": "The code that follows is written using Python 3.6.3, Pandas 0.23.0 and Arrow 2.0.0, all running on Ubuntu 18.04. The complete code can be found on github."
},
{
"code": null,
"e": 3910,
"s": 3759,
"text": "Let’s begin with the imports. We require Pandas, PyArrow (Python bindings for Arrow), Parquet and also JSON (which is used to serialise the metadata)."
},
{
"code": null,
"e": 3989,
"s": 3910,
"text": "import pandas as pdimport pyarrow as paimport pyarrow.parquet as pqimport json"
},
{
"code": null,
"e": 4193,
"s": 3989,
"text": "We introduce some data we wish to persist. This example imagines a weather IoT device recording a single data item, which is end-of-day values for two time-series variables, max-temperature and rainfall."
},
{
"code": null,
"e": 4534,
"s": 4193,
"text": "df = pd.DataFrame( { 'temp': [12.1, 11, 13, 10, 10], 'rain': [9.2, 10.0, 2.2, 0.2, 0.4] }, index=pd.DatetimeIndex(['2020-10-12', '2020-10-13', '2020-10-14', '2020-10-15', '2020-10-16'], name='date'))"
},
{
"code": null,
"e": 4780,
"s": 4534,
"text": "We also introduce some custom metadata. There is no universal format for metadata; typically it’s just key-value pairs, stored as a dict, with optional nesting of further dicts and lists. One caveat is that the value types can serialise to JSON."
},
{
"code": null,
"e": 4917,
"s": 4780,
"text": "custom_meta_content = { 'user': 'Wáng Fān', 'coord': '55.9533° N, 3.1883° W', 'time': '2020-10-17T03:59:59+0000' # ISO-8601}"
},
{
"code": null,
"e": 5244,
"s": 4917,
"text": "We require a metadata namespace key. As we will shortly see, the custom metadata will be inserted into a global metadata dict owned by an Arrow table, so we require a unique key to separate our custom metadata from other metadata which may already exist or be inserted later. A good choice is application or organisation name."
},
{
"code": null,
"e": 5279,
"s": 5244,
"text": "custom_meta_key = 'weatherapp.iot'"
},
{
"code": null,
"e": 5384,
"s": 5279,
"text": "As noted earlier, our approach is to convert the DataFrame to an Arrow table. We use PyArrow to do this:"
},
{
"code": null,
"e": 5417,
"s": 5384,
"text": "table = pa.Table.from_pandas(df)"
},
{
"code": null,
"e": 5530,
"s": 5417,
"text": "Out of interest we can inspect this table’s metadata property (a dict instance) to see what it holds by default:"
},
{
"code": null,
"e": 5559,
"s": 5530,
"text": "print(table.schema.metadata)"
},
{
"code": null,
"e": 5755,
"s": 5559,
"text": "This shows some initial metadata. This has been created by Pandas and inserted with the key b'pandas'. Pandas adds its own metadata so that it can convert from an Arrow table back to a DataFrame."
},
{
"code": null,
"e": 6070,
"s": 5755,
"text": "Now to the add custom metadata to this table. This is not immediately possible because Arrow tables are immutable. Instead we construct a new Arrow table which is a copy of the original but with the metadata replaced; the replacement metadata will be a combination of the existing metadata and the custom metadata."
},
{
"code": null,
"e": 6351,
"s": 6070,
"text": "First to construct the combined metadata. This is a simple merge of the existing table metadata and the custom metadata. There are a few caveats to get this right. The metadata content must be JSON serialisable and encoded as bytes; the metadata key must also be encoded as bytes:"
},
{
"code": null,
"e": 6533,
"s": 6351,
"text": "custom_meta_json = json.dumps(custom_meta_content)existing_meta = table.schema.metadatacombined_meta = { custom_meta_key.encode() : custom_meta_json.encode(), **existing_meta}"
},
{
"code": null,
"e": 6649,
"s": 6533,
"text": "Next the Arrow table is shallow copied. The copy has the original table metadata replaced by the combined metadata:"
},
{
"code": null,
"e": 6702,
"s": 6649,
"text": "table = table.replace_schema_metadata(combined_meta)"
},
{
"code": null,
"e": 6917,
"s": 6702,
"text": "The original table has been discarded; only the copy is retained, and is referenced by the reused variable table. This table now contains both the custom metadata and the Pandas metadata. This can be verified with:"
},
{
"code": null,
"e": 6946,
"s": 6917,
"text": "print(table.schema.metadata)"
},
{
"code": null,
"e": 7061,
"s": 6946,
"text": "Saving to Parquet is straightforward. In this example we request compression, which compresses columns internally:"
},
{
"code": null,
"e": 7122,
"s": 7061,
"text": "pq.write_table(table, 'example.parquet', compression='GZIP')"
},
{
"code": null,
"e": 7138,
"s": 7122,
"text": "Reverse process"
},
{
"code": null,
"e": 7383,
"s": 7138,
"text": "The DataFrame & metadata are now coupled together in single Parquet file, providing portability across programming languages and different versions of Python & Pandas. But how do we load this file to recover both the DataFrame and the metadata?"
},
{
"code": null,
"e": 7470,
"s": 7383,
"text": "This reverse task is a lot less fuss. First read the Parquet file into an Arrow table."
},
{
"code": null,
"e": 7520,
"s": 7470,
"text": "restored_table = pq.read_table('example.parquet')"
},
{
"code": null,
"e": 7741,
"s": 7520,
"text": "The DataFrame is obtained via a call of the table’s to_pandas conversion method. This operation uses the Pandas metadata to reconstruct the DataFrame, but this is under the hood details that we don’t need to worry about:"
},
{
"code": null,
"e": 7782,
"s": 7741,
"text": "restored_df = restored_table.to_pandas()"
},
{
"code": null,
"e": 7958,
"s": 7782,
"text": "The custom metadata is accessible via the Arrow table’s metadata object, by providing the custom metadata key used earlier (taking care to once again encode the key as bytes):"
},
{
"code": null,
"e": 8036,
"s": 7958,
"text": "restored_meta_json = restored_table.schema.metadata[custom_meta_key.encode()]"
},
{
"code": null,
"e": 8114,
"s": 8036,
"text": "This returns the metadata as a JSON string. The final step is to deserialise:"
},
{
"code": null,
"e": 8161,
"s": 8114,
"text": "restored_meta = json.loads(restored_meta_json)"
},
{
"code": null,
"e": 8302,
"s": 8161,
"text": "The metadata has been restored (in addition to the DataFrame); it is just a plain dict of key-value pairs, exactly as we originally created."
},
{
"code": null,
"e": 8310,
"s": 8302,
"text": "Summary"
},
{
"code": null,
"e": 8461,
"s": 8310,
"text": "Metadata should be an important consideration of any data collection and processing system, but how it can be captured and stored is often overlooked."
},
{
"code": null,
"e": 8717,
"s": 8461,
"text": "Pandas lacks a dedicated mechanism for saving metadata to a DataFrame. However we have seen that recent libraries, such as Arrow and Parquet, do provide direct support for persisting DataFrames and metadata together in highly portable and performant files"
}
] |
C# int.Parse Method
|
Convert a string representation of number to an integer, using the int.Parse method in C#. If the string cannot be converted, then the int.Parse method returns an exception
Let’s say you have a string representation of a number.
string myStr = "200";
Now to convert it to an integer, use the int.Parse(). It will get converted.
int.Parse(myStr);
Live Demo
using System.IO;
using System;
class Program {
static void Main() {
int res;
string myStr = "200";
res = int.Parse(myStr);
Console.WriteLine("String is a numeric representation: "+res);
}
}
String is a numeric representation: 200
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "Convert a string representation of number to an integer, using the int.Parse method in C#. If the string cannot be converted, then the int.Parse method returns an exception"
},
{
"code": null,
"e": 1291,
"s": 1235,
"text": "Let’s say you have a string representation of a number."
},
{
"code": null,
"e": 1313,
"s": 1291,
"text": "string myStr = \"200\";"
},
{
"code": null,
"e": 1390,
"s": 1313,
"text": "Now to convert it to an integer, use the int.Parse(). It will get converted."
},
{
"code": null,
"e": 1408,
"s": 1390,
"text": "int.Parse(myStr);"
},
{
"code": null,
"e": 1419,
"s": 1408,
"text": " Live Demo"
},
{
"code": null,
"e": 1639,
"s": 1419,
"text": "using System.IO;\nusing System;\nclass Program {\n static void Main() {\n int res;\n string myStr = \"200\";\n res = int.Parse(myStr);\n Console.WriteLine(\"String is a numeric representation: \"+res);\n }\n}"
},
{
"code": null,
"e": 1679,
"s": 1639,
"text": "String is a numeric representation: 200"
}
] |
How to change notification background colour in Android?
|
This example demonstrate about How can I marquee the text content in Android Notification.
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" >
<Button
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :layout_centerInParent = "true"
android :layout_margin = "16dp"
android :onClick = "createNotification"
android :text = "create notification" />
</RelativeLayout>
Step 3 − Add the following code to res/layout/custom_notification_layout.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android :id = "@+id/layout"
android :layout_width = "fill_parent"
android :layout_height = "64dp"
android :background = "@color/colorAccent"
android :padding = "10dp" >
<ImageView
android :id = "@+id/image"
android :layout_width = "wrap_content"
android :layout_height = "fill_parent"
android :layout_alignParentStart = "true"
android :layout_marginEnd = "10dp"
android :contentDescription = "@string/app_name"
android :src = "@mipmap/ic_launcher" />
<TextView
android :id = "@+id/title"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_toEndOf = "@id/image"
android :text = "Testing"
android :textColor = "#000"
android :textSize = "13sp" />
<TextView
android :id = "@+id/text"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_below = "@id/title"
android :layout_toEndOf = "@id/image"
android :ellipsize = "marquee"
android :singleLine = "true"
android :text = "Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into
electronic typesetting, remaining essentially unchanged. It was popularised in the
1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
recently with desktop publishing software like Aldus PageMaker including versions of
Lorem Ipsum. "
android :textColor = "#000"
android :textSize = "13sp" />
</RelativeLayout>
Step 4 − Add the following code to src/MainActivity.
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.RemoteViews ;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
}
public void createNotification (View view) {
RemoteViews contentView = new RemoteViews(getPackageName() , R.layout. custom_notification_layout ) ;
NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
mBuilder.setContent(contentView) ;
mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
mBuilder.setAutoCancel( true ) ;
if (android.os.Build.VERSION. SDK_INT > = android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () ,
mBuilder.build()) ;
}
}
Step 5 − 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 = "app.tutorialspoint.com.notifyme" >
<uses-permission android :name = "android.permission.VIBRATE" />
<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 Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "This example demonstrate about How can I marquee the text content in Android Notification."
},
{
"code": null,
"e": 1282,
"s": 1153,
"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": 1347,
"s": 1282,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1943,
"s": 1347,
"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 <Button\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_centerInParent = \"true\"\n android :layout_margin = \"16dp\"\n android :onClick = \"createNotification\"\n android :text = \"create notification\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2021,
"s": 1943,
"text": "Step 3 − Add the following code to res/layout/custom_notification_layout.xml."
},
{
"code": null,
"e": 3977,
"s": 2021,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n android :id = \"@+id/layout\"\n android :layout_width = \"fill_parent\"\n android :layout_height = \"64dp\"\n android :background = \"@color/colorAccent\"\n android :padding = \"10dp\" >\n <ImageView\n android :id = \"@+id/image\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"fill_parent\"\n android :layout_alignParentStart = \"true\"\n android :layout_marginEnd = \"10dp\"\n android :contentDescription = \"@string/app_name\"\n android :src = \"@mipmap/ic_launcher\" />\n <TextView\n android :id = \"@+id/title\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_toEndOf = \"@id/image\"\n android :text = \"Testing\"\n android :textColor = \"#000\"\n android :textSize = \"13sp\" />\n <TextView\n android :id = \"@+id/text\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_below = \"@id/title\"\n android :layout_toEndOf = \"@id/image\"\n android :ellipsize = \"marquee\"\n android :singleLine = \"true\"\n android :text = \"Lorem Ipsum is simply dummy text of the printing and typesetting\n industry. Lorem Ipsum has been the industry's standard dummy text ever since the\n 1500s, when an unknown printer took a galley of type and scrambled it to make a type\n specimen book. It has survived not only five centuries, but also the leap into\n electronic typesetting, remaining essentially unchanged. It was popularised in the\n 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more\n recently with desktop publishing software like Aldus PageMaker including versions of\n Lorem Ipsum. \"\n android :textColor = \"#000\"\n android :textSize = \"13sp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 4030,
"s": 3977,
"text": "Step 4 − Add the following code to src/MainActivity."
},
{
"code": null,
"e": 5897,
"s": 4030,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.RemoteViews ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void createNotification (View view) {\n RemoteViews contentView = new RemoteViews(getPackageName() , R.layout. custom_notification_layout ) ;\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContent(contentView) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT > = android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () ,\n mBuilder.build()) ;\n }\n}"
},
{
"code": null,
"e": 5952,
"s": 5897,
"text": "Step 5 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 6751,
"s": 5952,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\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": 7098,
"s": 6751,
"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": 7140,
"s": 7098,
"text": "Click here to download the project code"
}
] |
Using BigInt to calculate long factorials in JavaScript
|
We are required to write a JavaScript function that takes in a number as the only input. The function should calculate the factorial of big numbers (greater than 10) whose factorial can be accommodated in the simple let or type variables using the new bigInt variable of JavaScript. Lastly the function should convert the factorial to a string and return the string.
For example − If the input is −
const num = 45;
Then the output should be −
const output = '119622220865480194561963161495657715064383733760000000000';
The code for this will be −
const num = 45;
const longFactorial = (num) => {
var bigInt = BigInt(num);
var factorial = 1n;
for (let i = 0n; i < bigInt ; i++) {
factorial *= bigInt − i;
}
return String(factorial);
}
console.log(longFactorial(45));
And the output in the console will be −
119622220865480194561963161495657715064383733760000000000
|
[
{
"code": null,
"e": 1429,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a number as the only input. The function should calculate the factorial of big numbers (greater than 10) whose factorial can be accommodated in the simple let or type variables using the new bigInt variable of JavaScript. Lastly the function should convert the factorial to a string and return the string."
},
{
"code": null,
"e": 1461,
"s": 1429,
"text": "For example − If the input is −"
},
{
"code": null,
"e": 1477,
"s": 1461,
"text": "const num = 45;"
},
{
"code": null,
"e": 1505,
"s": 1477,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1581,
"s": 1505,
"text": "const output = '119622220865480194561963161495657715064383733760000000000';"
},
{
"code": null,
"e": 1609,
"s": 1581,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1849,
"s": 1609,
"text": "const num = 45;\nconst longFactorial = (num) => {\n var bigInt = BigInt(num);\n var factorial = 1n;\n for (let i = 0n; i < bigInt ; i++) {\n factorial *= bigInt − i;\n }\n return String(factorial);\n}\nconsole.log(longFactorial(45));"
},
{
"code": null,
"e": 1889,
"s": 1849,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 1947,
"s": 1889,
"text": "119622220865480194561963161495657715064383733760000000000"
}
] |
Understanding Feature extraction using Correlation Matrix and Scatter Plots | by Tarun Acharya | Towards Data Science
|
This article is going to deal with a very fundamental and important concept when dealing with a large number of features in a given dataset.
Any typical machine learning or deep learning model is made to provide a single output from huge amounts of data be it structured or unstructured. These factors may contribute to the required result at various coefficients and degrees. They need to be filtered out in a way based on their significance in determining the output and also considering the redundancy in these factors.
In supervised learning, we know that there is always an output variable and n input variables. To understand this concept very clearly let's take an example of a simple linear regression problem.
In a simple linear regression model, we ultimately generate an equation from the model of the form y=mx+c where x is an independent variable and y is a dependent variable. Since there is only one variable, y has to depend on the value of x. Although in real-time there might be few other ignored external factors such as air resistance while calculating the average velocity of a bus from A to B. These definitely make an impact on the output but yet has the least significance. In this case, our common sense and experience help us in picking the factor. Hence we pick acceleration given to the bus by the driver and ignore the air resistance. But what about the complex situations where we have no idea about the significance of input variables on the output. Can mathematics solve this puzzle?
Yes! Here comes the concept of correlation.
Correlation is a statistical measure that indicates the extent to which two or more variables fluctuate together. In simple terms, it tells us how much does one variable changes for a slight change in another variable. It may take positive, negative and zero values depending on the direction of the change. A high correlation value between a dependent variable and an independent variable indicates that the independent variable is of very high significance in determining the output. In a multiple regression setup where there are many factors, it is imperative to find the correlation between the dependent and all the independent variables to build a more viable model with higher accuracy. One must always remember that more number of features does not imply better accuracy. More features may lead to a decline in the accuracy if they contain any irrelevant features creating unrequired noise in our model.
Correlation between 2 variables can be found by various metrics such as Pearson r correlation, Kendall rank correlation, Spearman rank correlation, etc.
Pearson r correlation is the most widely used correlation statistic to measure the degree of the relationship between linearly related variables. The Pearson correlation between any 2 variables x,y can be found using :
Let us consider the dataset 50_Strartups on new startups in New York, California, and Florida. The variables used in the dataset are Profit, R&D spending, Administration Spending, and Marketing Spending. Here Profit is the dependent variable to be predicted.
Let us first apply linear regression for every independent variable separately to visualize the correlation with the independent variable.
From the scatter plot, we can see that R&D Spend and Profit have a very high correlation thus implying a greater significance towards predicting the output and Marketing spend having a lesser correlation with the Profit compared to R&D Spend.
But, the scatter between Administration and Profit shows that the correlation between them is very less and might end up creating noise during the prediction. Thus, we can exclude this feature in our model for a better result.
This process eliminates the insignificant and irrelevant features of our model. But, what about redundant features?
Redundant Features: Although some features are highly relevant to our target variable, they might be redundant. Any 2 independent variables are considered to be redundant if they are highly correlated. This causes unnecessary time and space wastage. Even the redundancy between 2 variables can be found using correlation.
Note: A high correlation between dependent and independent variables is desired whereas the high correlation between 2 independent variables is undesired.
The above 2 graphs show the correlation between independent variables. We can see a higher correlation in the first graph whereas very low correlation in the second. This means we can exclude any one of the 2 features in the first graph since the correlation between 2 independent variables causes redundancy. But which one to remove? The answer is straightforward. The variable with a higher correlation with the target variable stays and the other is removed.
Determining the correlation between the variables:
df = pd.DataFrame(data,columns=['R&D Spend','Administration','Marketing Spend','Profit'])corrMatrix = df.corr()print (corrMatrix)
Output: The output shows a 2*2 matrix showing the Pearson r correlation among all the variables.
Finally, comparing various multiple regression models based on their r2 scores.
From the experimented scores, we observe that:
-> Independent variables with low correlation lead to lower r2 scores. (Ex: Taking administration alone)
-> Variables with higher correlation gave us higher r2 score in our model(Ex: R&D Spend and Marketing Spend)
> Eliminating redundant variables or irrelevant variables may/may not lead to a negligible loss in our accuracy but makes it a very efficient model under many constraints.
For further reference:
|
[
{
"code": null,
"e": 313,
"s": 172,
"text": "This article is going to deal with a very fundamental and important concept when dealing with a large number of features in a given dataset."
},
{
"code": null,
"e": 695,
"s": 313,
"text": "Any typical machine learning or deep learning model is made to provide a single output from huge amounts of data be it structured or unstructured. These factors may contribute to the required result at various coefficients and degrees. They need to be filtered out in a way based on their significance in determining the output and also considering the redundancy in these factors."
},
{
"code": null,
"e": 891,
"s": 695,
"text": "In supervised learning, we know that there is always an output variable and n input variables. To understand this concept very clearly let's take an example of a simple linear regression problem."
},
{
"code": null,
"e": 1688,
"s": 891,
"text": "In a simple linear regression model, we ultimately generate an equation from the model of the form y=mx+c where x is an independent variable and y is a dependent variable. Since there is only one variable, y has to depend on the value of x. Although in real-time there might be few other ignored external factors such as air resistance while calculating the average velocity of a bus from A to B. These definitely make an impact on the output but yet has the least significance. In this case, our common sense and experience help us in picking the factor. Hence we pick acceleration given to the bus by the driver and ignore the air resistance. But what about the complex situations where we have no idea about the significance of input variables on the output. Can mathematics solve this puzzle?"
},
{
"code": null,
"e": 1732,
"s": 1688,
"text": "Yes! Here comes the concept of correlation."
},
{
"code": null,
"e": 2645,
"s": 1732,
"text": "Correlation is a statistical measure that indicates the extent to which two or more variables fluctuate together. In simple terms, it tells us how much does one variable changes for a slight change in another variable. It may take positive, negative and zero values depending on the direction of the change. A high correlation value between a dependent variable and an independent variable indicates that the independent variable is of very high significance in determining the output. In a multiple regression setup where there are many factors, it is imperative to find the correlation between the dependent and all the independent variables to build a more viable model with higher accuracy. One must always remember that more number of features does not imply better accuracy. More features may lead to a decline in the accuracy if they contain any irrelevant features creating unrequired noise in our model."
},
{
"code": null,
"e": 2798,
"s": 2645,
"text": "Correlation between 2 variables can be found by various metrics such as Pearson r correlation, Kendall rank correlation, Spearman rank correlation, etc."
},
{
"code": null,
"e": 3017,
"s": 2798,
"text": "Pearson r correlation is the most widely used correlation statistic to measure the degree of the relationship between linearly related variables. The Pearson correlation between any 2 variables x,y can be found using :"
},
{
"code": null,
"e": 3276,
"s": 3017,
"text": "Let us consider the dataset 50_Strartups on new startups in New York, California, and Florida. The variables used in the dataset are Profit, R&D spending, Administration Spending, and Marketing Spending. Here Profit is the dependent variable to be predicted."
},
{
"code": null,
"e": 3415,
"s": 3276,
"text": "Let us first apply linear regression for every independent variable separately to visualize the correlation with the independent variable."
},
{
"code": null,
"e": 3658,
"s": 3415,
"text": "From the scatter plot, we can see that R&D Spend and Profit have a very high correlation thus implying a greater significance towards predicting the output and Marketing spend having a lesser correlation with the Profit compared to R&D Spend."
},
{
"code": null,
"e": 3885,
"s": 3658,
"text": "But, the scatter between Administration and Profit shows that the correlation between them is very less and might end up creating noise during the prediction. Thus, we can exclude this feature in our model for a better result."
},
{
"code": null,
"e": 4001,
"s": 3885,
"text": "This process eliminates the insignificant and irrelevant features of our model. But, what about redundant features?"
},
{
"code": null,
"e": 4323,
"s": 4001,
"text": "Redundant Features: Although some features are highly relevant to our target variable, they might be redundant. Any 2 independent variables are considered to be redundant if they are highly correlated. This causes unnecessary time and space wastage. Even the redundancy between 2 variables can be found using correlation."
},
{
"code": null,
"e": 4478,
"s": 4323,
"text": "Note: A high correlation between dependent and independent variables is desired whereas the high correlation between 2 independent variables is undesired."
},
{
"code": null,
"e": 4940,
"s": 4478,
"text": "The above 2 graphs show the correlation between independent variables. We can see a higher correlation in the first graph whereas very low correlation in the second. This means we can exclude any one of the 2 features in the first graph since the correlation between 2 independent variables causes redundancy. But which one to remove? The answer is straightforward. The variable with a higher correlation with the target variable stays and the other is removed."
},
{
"code": null,
"e": 4991,
"s": 4940,
"text": "Determining the correlation between the variables:"
},
{
"code": null,
"e": 5121,
"s": 4991,
"text": "df = pd.DataFrame(data,columns=['R&D Spend','Administration','Marketing Spend','Profit'])corrMatrix = df.corr()print (corrMatrix)"
},
{
"code": null,
"e": 5218,
"s": 5121,
"text": "Output: The output shows a 2*2 matrix showing the Pearson r correlation among all the variables."
},
{
"code": null,
"e": 5298,
"s": 5218,
"text": "Finally, comparing various multiple regression models based on their r2 scores."
},
{
"code": null,
"e": 5345,
"s": 5298,
"text": "From the experimented scores, we observe that:"
},
{
"code": null,
"e": 5450,
"s": 5345,
"text": "-> Independent variables with low correlation lead to lower r2 scores. (Ex: Taking administration alone)"
},
{
"code": null,
"e": 5559,
"s": 5450,
"text": "-> Variables with higher correlation gave us higher r2 score in our model(Ex: R&D Spend and Marketing Spend)"
},
{
"code": null,
"e": 5731,
"s": 5559,
"text": "> Eliminating redundant variables or irrelevant variables may/may not lead to a negligible loss in our accuracy but makes it a very efficient model under many constraints."
}
] |
How to check whether a JavaScript date is valid?
|
To check whether a JavaScript date is valid or not, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var date1, date2;
date1 = new Date("2018/1/1");
if( ! isNaN ( date1.getMonth() )) {
document.write("Valid date1: "+date1);
}else{
document.write("<br>Invalid date1");
}
date2 = new Date("20181/1");
if( ! isNaN ( date2.getMonth() )) {
document.write("<br> Valid date2: "+date2);
}else{
document.write("<br>Invalid date2");
}
</script>
</body>
</html>
Valid date1: Mon Jan 01 2018 00:00:00 GMT+0530 (India Standard Time)
Valid date2: Mon Jan 01 20181 00:00:00 GMT+0530 (India Standard Time)
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To check whether a JavaScript date is valid or not, you can try to run the following code −"
},
{
"code": null,
"e": 1164,
"s": 1154,
"text": "Live Demo"
},
{
"code": null,
"e": 1714,
"s": 1164,
"text": "<!DOCTYPE html>\n<html>\n <body> \n <script>\n var date1, date2; \n date1 = new Date(\"2018/1/1\"); \n if( ! isNaN ( date1.getMonth() )) {\n document.write(\"Valid date1: \"+date1);\n }else{\n document.write(\"<br>Invalid date1\");\n }\n date2 = new Date(\"20181/1\"); \n if( ! isNaN ( date2.getMonth() )) {\n document.write(\"<br> Valid date2: \"+date2); \n }else{\n document.write(\"<br>Invalid date2\");\n } \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 1853,
"s": 1714,
"text": "Valid date1: Mon Jan 01 2018 00:00:00 GMT+0530 (India Standard Time)\nValid date2: Mon Jan 01 20181 00:00:00 GMT+0530 (India Standard Time)"
}
] |
VBA - Strings
|
Strings are a sequence of characters, which can consist of either alphabets, numbers, special characters, or all of them. A variable is said to be a string if it is enclosed within double quotes " ".
variablename = "string"
str1 = "string" ' Only Alphabets
str2 = "132.45" ' Only Numbers
str3 = "!@#$;*" ' Only Special Characters
Str4 = "Asc23@#" ' Has all the above
There are predefined VBA String functions, which help the developers to work with the strings very effectively. Following are String methods that are supported in VBA. Please click on each one of the methods to know in detail.
Returns the first occurrence of the specified substring. Search happens from the left to the right.
Returns the first occurrence of the specified substring. Search happens from the right to the left.
Returns the lower case of the specified string.
Returns the upper case of the specified string.
Returns a specific number of characters from the left side of the string.
Returns a specific number of characters from the right side of the string.
Returns a specific number of characters from a string based on the specified parameters.
Returns a string after removing the spaces on the left side of the specified string.
Returns a string after removing the spaces on the right side of the specified string.
Returns a string value after removing both the leading and the trailing blank spaces.
Returns the length of the given string.
Returns a string after replacing a string with another string.
Fills a string with the specified number of spaces.
Returns an integer value after comparing the two specified strings.
Returns a string with a specified character for specified number of times.
Returns a string after reversing the sequence of the characters of the given string.
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2135,
"s": 1935,
"text": "Strings are a sequence of characters, which can consist of either alphabets, numbers, special characters, or all of them. A variable is said to be a string if it is enclosed within double quotes \" \"."
},
{
"code": null,
"e": 2160,
"s": 2135,
"text": "variablename = \"string\"\n"
},
{
"code": null,
"e": 2309,
"s": 2160,
"text": "str1 = \"string\" ' Only Alphabets\nstr2 = \"132.45\" ' Only Numbers\nstr3 = \"!@#$;*\" ' Only Special Characters\nStr4 = \"Asc23@#\" ' Has all the above"
},
{
"code": null,
"e": 2536,
"s": 2309,
"text": "There are predefined VBA String functions, which help the developers to work with the strings very effectively. Following are String methods that are supported in VBA. Please click on each one of the methods to know in detail."
},
{
"code": null,
"e": 2636,
"s": 2536,
"text": "Returns the first occurrence of the specified substring. Search happens from the left to the right."
},
{
"code": null,
"e": 2736,
"s": 2636,
"text": "Returns the first occurrence of the specified substring. Search happens from the right to the left."
},
{
"code": null,
"e": 2784,
"s": 2736,
"text": "Returns the lower case of the specified string."
},
{
"code": null,
"e": 2832,
"s": 2784,
"text": "Returns the upper case of the specified string."
},
{
"code": null,
"e": 2906,
"s": 2832,
"text": "Returns a specific number of characters from the left side of the string."
},
{
"code": null,
"e": 2981,
"s": 2906,
"text": "Returns a specific number of characters from the right side of the string."
},
{
"code": null,
"e": 3070,
"s": 2981,
"text": "Returns a specific number of characters from a string based on the specified parameters."
},
{
"code": null,
"e": 3155,
"s": 3070,
"text": "Returns a string after removing the spaces on the left side of the specified string."
},
{
"code": null,
"e": 3241,
"s": 3155,
"text": "Returns a string after removing the spaces on the right side of the specified string."
},
{
"code": null,
"e": 3327,
"s": 3241,
"text": "Returns a string value after removing both the leading and the trailing blank spaces."
},
{
"code": null,
"e": 3367,
"s": 3327,
"text": "Returns the length of the given string."
},
{
"code": null,
"e": 3430,
"s": 3367,
"text": "Returns a string after replacing a string with another string."
},
{
"code": null,
"e": 3482,
"s": 3430,
"text": "Fills a string with the specified number of spaces."
},
{
"code": null,
"e": 3550,
"s": 3482,
"text": "Returns an integer value after comparing the two specified strings."
},
{
"code": null,
"e": 3625,
"s": 3550,
"text": "Returns a string with a specified character for specified number of times."
},
{
"code": null,
"e": 3710,
"s": 3625,
"text": "Returns a string after reversing the sequence of the characters of the given string."
},
{
"code": null,
"e": 3744,
"s": 3710,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3759,
"s": 3744,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3792,
"s": 3759,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3807,
"s": 3792,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3842,
"s": 3807,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3860,
"s": 3842,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3893,
"s": 3860,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3911,
"s": 3893,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3944,
"s": 3911,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3959,
"s": 3944,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3995,
"s": 3959,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 4023,
"s": 3995,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4030,
"s": 4023,
"text": " Print"
},
{
"code": null,
"e": 4041,
"s": 4030,
"text": " Add Notes"
}
] |
Spring Boot SOAP Consumer Example | Spring Boot SOAP Client
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see how to implement a simple Spring Boot SOAP Consumer Example.
As part of this example, I am going to consume a SOAP web service; you can follow our previous tutorials to get it.
To run the Spring Boot SOAP client – Initially, you should have your running SOAP web service on your local or remote machine.
If you do not have in your local, you can follow our previous article on Spring boot SOAP web service.
Take the WSDL file handy to build java classes
Spring Boot Starter Web Service 2.1.6 RELEASE
Java 8
Maven
Maven Javb2 plugin
Create a Spring boot application with the following structure.
This application requires a single dependency – spring-boot-starter-web-service
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
</dependencies>
Add the below maven jaxb2 plugin in pom.xml to generate the java binding classes using WSDL file.
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.13.2</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<generatePackage>com.onlinetutorialspoint.soap.bindings</generatePackage>
<generateDirectory>${project.basedir}/src/main/java</generateDirectory>
<schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>
<schemaIncludes>
<include>*.wsdl</include>
</schemaIncludes>
</configuration>
</plugin>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>Spring-Boot-SOAP-Consumer-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-Boot-SOAP-Consumer-Example</name>
<description>Spring Boot SOAP Consumer Example</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.13.2</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<generatePackage>com.onlinetutorialspoint.soap.bindings</generatePackage>
<generateDirectory>${project.basedir}/src/main/java</generateDirectory>
<schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>
<schemaIncludes>
<include>*.wsdl</include>
</schemaIncludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Take the WSDL file from the SOAP web service provider. In our case, we have our SOAP web service running on our machine, and here is the WSDL.
Create a file under resources/wsdl folder with the name of items.wsdl and paste the above content init.
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch="http://onlinetutorialspoint.com/generated" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://onlinetutorialspoint.com/generated" targetNamespace="http://onlinetutorialspoint.com/generated">
<wsdl:types>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://onlinetutorialspoint.com/generated">
<xs:element name="ItemRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="ItemResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:int"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="category" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</wsdl:types>
<wsdl:message name="ItemRequest">
<wsdl:part element="tns:ItemRequest" name="ItemRequest"> </wsdl:part>
</wsdl:message>
<wsdl:message name="ItemResponse">
<wsdl:part element="tns:ItemResponse" name="ItemResponse"> </wsdl:part>
</wsdl:message>
<wsdl:portType name="Item">
<wsdl:operation name="Item">
<wsdl:input message="tns:ItemRequest" name="ItemRequest"> </wsdl:input>
<wsdl:output message="tns:ItemResponse" name="ItemResponse"> </wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="ItemSoap11" type="tns:Item">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="Item">
<soap:operation soapAction=""/>
<wsdl:input name="ItemRequest">
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output name="ItemResponse">
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="ItemService">
<wsdl:port binding="tns:ItemSoap11" name="ItemSoap11">
<soap:address location="http://localhost:8080/ws"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
After this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml.
package com.onlinetutorialspoint.soap.bindings;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"id"
})
@XmlRootElement(name = "ItemRequest")
public class ItemRequest {
protected int id;
public int getId() {
return id;
}
public void setId(int value) {
this.id = value;
}
}
package com.onlinetutorialspoint.soap.bindings;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"id",
"name",
"category"
})
@XmlRootElement(name = "ItemResponse")
public class ItemResponse {
protected int id;
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String category;
public int getId() {
return id;
}
public void setId(int value) {
this.id = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getCategory() {
return category;
}
public void setCategory(String value) {
this.category = value;
}
}
package com.onlinetutorialspoint.soap.bindings;
import javax.xml.bind.annotation.XmlRegistry;
@XmlRegistry
public class ObjectFactory {
public ObjectFactory() {
}
public ItemRequest createItemRequest() {
return new ItemRequest();
}
public ItemResponse createItemResponse() {
return new ItemResponse();
}
}
Making this application port to 8081. As I have a SOAP service running on 8080 port.
server.port=8081
Creating Jaxb2Marshaller object and given the binding classes to scan while loading the application.
package com.onlinetutorialspoint.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
@Configuration
public class SoapConfig {
@Bean
public Jaxb2Marshaller marshaller(){
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setPackagesToScan("com.onlinetutorialspoint.soap.bindings");
return jaxb2Marshaller;
}
}
The SOAP client class, which is responsible for communicating with the SOAP service and getting the response using WebServiceTemplate object.
package com.onlinetutorialspoint.client;
import com.onlinetutorialspoint.soap.bindings.ItemRequest;
import com.onlinetutorialspoint.soap.bindings.ItemResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Service;
import org.springframework.ws.client.core.WebServiceTemplate;
@Service
public class SoapClient {
@Autowired
private Jaxb2Marshaller jaxb2Marshaller;
private WebServiceTemplate webServiceTemplate;
public ItemResponse getItemInfo(ItemRequest itemRequest){
webServiceTemplate = new WebServiceTemplate(jaxb2Marshaller);
return (ItemResponse) webServiceTemplate.marshalSendAndReceive("http://localhost:8080/ws",itemRequest);
}
}
On the above example, we have given the WSDL URI (http://localhost:8080/ws) to marshalSendAndReceive method. As I am running the service application on my local, I gave the local WSDL URI. If you wanted to access any remote WSDL, you could provide the remote URI here.
I am creating a RestController to access this SOAP client.
package com.onlinetutorialspoint.controller;
import com.onlinetutorialspoint.client.SoapClient;
import com.onlinetutorialspoint.soap.bindings.ItemRequest;
import com.onlinetutorialspoint.soap.bindings.ItemResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ItemController {
@Autowired
SoapClient soapClient;
@PostMapping("/item")
public ItemResponse item(@RequestBody ItemRequest itemRequest){
return soapClient.getItemInfo(itemRequest);
}
}
$mvn clean install
$mvn spring-boot:run
[INFO] --- spring-boot-maven-plugin:2.1.6.RELEASE:run (default-cli) @ Spring-Boot-SOAP-Consumer-Example ---
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.6.RELEASE)
2019-07-27 00:36:29.644 INFO 23148 --- [ main] SpringBootSoapConsumerExampleApplication : Starting SpringBootSoapConsumerExampleApplication on DESKTOP-RN4SMHT with PID 23148 (
D:\work\Spring-Boot-SOAP-Consumer-Example\target\classes started by Lenovo in D:\work\Spring-Boot-SOAP-Consumer-Example)
2019-07-27 00:36:29.657 INFO 23148 --- [ main] SpringBootSoapConsumerExampleApplication : No active profile set, falling back to default profiles: default
2019-07-27 00:36:31.723 INFO 23148 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [or
g.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$c255fca6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligi
ble for auto-proxying)
2019-07-27 00:36:31.797 INFO 23148 --- [ main] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
2019-07-27 00:36:32.760 INFO 23148 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2019-07-27 00:36:32.811 INFO 23148 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
....
....
Done!
Spring Boot Soap Web Services
Installing SOAPUI on Windows 10
Spring Boot Soap WebServices Example
Simple Spring Boot Example
MicroServices Spring Boot Eureka Server Example
Spring Boot Actuator Database Health Check
How to install SOAPUI on Windows 10
Spring Boot How to change the Tomcat to Jetty Server
How to set Spring Boot SetTimeZone
Spring Boot MongoDB + Spring Data Example
Spring Boot MVC Example Tutorials
Spring Boot JPA Integration Example
How To Change Spring Boot Context Path
How to Get All Spring Beans Details Loaded in ICO
How to change Spring Boot Tomcat Port Number
Spring Boot RabbitMQ Consumer Messages Example
How to enable Swagger in Spring Boot Application
Spring Boot Soap WebServices Example
Simple Spring Boot Example
MicroServices Spring Boot Eureka Server Example
Spring Boot Actuator Database Health Check
How to install SOAPUI on Windows 10
Spring Boot How to change the Tomcat to Jetty Server
How to set Spring Boot SetTimeZone
Spring Boot MongoDB + Spring Data Example
Spring Boot MVC Example Tutorials
Spring Boot JPA Integration Example
How To Change Spring Boot Context Path
How to Get All Spring Beans Details Loaded in ICO
How to change Spring Boot Tomcat Port Number
Spring Boot RabbitMQ Consumer Messages Example
How to enable Swagger in Spring Boot Application
Daniel
July 1, 2021 at 2:58 am - Reply
Very helpful and clean
anupama
August 9, 2021 at 12:57 pm - Reply
After this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml.
your application as is working fine.
but when i used it for my purpose the plug in is not generating any bindings package ,
i am not sure what i am doing wrong. exactly followed as per your application...
chandrashekhar
August 9, 2021 at 2:47 pm - Reply
Hey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue.
Daniel
July 1, 2021 at 2:58 am - Reply
Very helpful and clean
Very helpful and clean
anupama
August 9, 2021 at 12:57 pm - Reply
After this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml.
your application as is working fine.
but when i used it for my purpose the plug in is not generating any bindings package ,
i am not sure what i am doing wrong. exactly followed as per your application...
chandrashekhar
August 9, 2021 at 2:47 pm - Reply
Hey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue.
After this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml.
your application as is working fine.
but when i used it for my purpose the plug in is not generating any bindings package ,
i am not sure what i am doing wrong. exactly followed as per your application...
chandrashekhar
August 9, 2021 at 2:47 pm - Reply
Hey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue.
Hey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue.
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 497,
"s": 398,
"text": "In this tutorial, we are going to see how to implement a simple Spring Boot SOAP Consumer Example."
},
{
"code": null,
"e": 613,
"s": 497,
"text": "As part of this example, I am going to consume a SOAP web service; you can follow our previous tutorials to get it."
},
{
"code": null,
"e": 740,
"s": 613,
"text": "To run the Spring Boot SOAP client – Initially, you should have your running SOAP web service on your local or remote machine."
},
{
"code": null,
"e": 843,
"s": 740,
"text": "If you do not have in your local, you can follow our previous article on Spring boot SOAP web service."
},
{
"code": null,
"e": 890,
"s": 843,
"text": "Take the WSDL file handy to build java classes"
},
{
"code": null,
"e": 936,
"s": 890,
"text": "Spring Boot Starter Web Service 2.1.6 RELEASE"
},
{
"code": null,
"e": 943,
"s": 936,
"text": "Java 8"
},
{
"code": null,
"e": 949,
"s": 943,
"text": "Maven"
},
{
"code": null,
"e": 968,
"s": 949,
"text": "Maven Javb2 plugin"
},
{
"code": null,
"e": 1031,
"s": 968,
"text": "Create a Spring boot application with the following structure."
},
{
"code": null,
"e": 1111,
"s": 1031,
"text": "This application requires a single dependency – spring-boot-starter-web-service"
},
{
"code": null,
"e": 1283,
"s": 1111,
"text": "<dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web-services</artifactId>\n </dependency>\n</dependencies>"
},
{
"code": null,
"e": 1381,
"s": 1283,
"text": "Add the below maven jaxb2 plugin in pom.xml to generate the java binding classes using WSDL file."
},
{
"code": null,
"e": 2103,
"s": 1381,
"text": "<plugin>\n <groupId>org.jvnet.jaxb2.maven2</groupId>\n <artifactId>maven-jaxb2-plugin</artifactId>\n <version>0.13.2</version>\n <executions>\n <execution>\n <goals>\n <goal>generate</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <generatePackage>com.onlinetutorialspoint.soap.bindings</generatePackage>\n <generateDirectory>${project.basedir}/src/main/java</generateDirectory>\n <schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>\n <schemaIncludes>\n <include>*.wsdl</include>\n </schemaIncludes>\n </configuration>\n </plugin>"
},
{
"code": null,
"e": 4047,
"s": 2103,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.1.6.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>Spring-Boot-SOAP-Consumer-Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <name>Spring-Boot-SOAP-Consumer-Example</name>\n <description>Spring Boot SOAP Consumer Example</description>\n <properties>\n <java.version>1.8</java.version>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web-services</artifactId>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n <plugin>\n <groupId>org.jvnet.jaxb2.maven2</groupId>\n <artifactId>maven-jaxb2-plugin</artifactId>\n <version>0.13.2</version>\n <executions>\n <execution>\n <goals>\n <goal>generate</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <generatePackage>com.onlinetutorialspoint.soap.bindings</generatePackage>\n <generateDirectory>${project.basedir}/src/main/java</generateDirectory>\n <schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>\n <schemaIncludes>\n <include>*.wsdl</include>\n </schemaIncludes>\n </configuration>\n </plugin>\n </plugins>\n </build>\n</project>\n"
},
{
"code": null,
"e": 4190,
"s": 4047,
"text": "Take the WSDL file from the SOAP web service provider. In our case, we have our SOAP web service running on our machine, and here is the WSDL."
},
{
"code": null,
"e": 4294,
"s": 4190,
"text": "Create a file under resources/wsdl folder with the name of items.wsdl and paste the above content init."
},
{
"code": null,
"e": 6752,
"s": 4294,
"text": "<wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:sch=\"http://onlinetutorialspoint.com/generated\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://onlinetutorialspoint.com/generated\" targetNamespace=\"http://onlinetutorialspoint.com/generated\">\n <wsdl:types>\n <xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" targetNamespace=\"http://onlinetutorialspoint.com/generated\">\n <xs:element name=\"ItemRequest\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"id\" type=\"xs:int\"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"ItemResponse\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"id\" type=\"xs:int\"/>\n <xs:element name=\"name\" type=\"xs:string\"/>\n <xs:element name=\"category\" type=\"xs:string\"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n </xs:schema>\n </wsdl:types>\n <wsdl:message name=\"ItemRequest\">\n <wsdl:part element=\"tns:ItemRequest\" name=\"ItemRequest\"> </wsdl:part>\n </wsdl:message>\n <wsdl:message name=\"ItemResponse\">\n <wsdl:part element=\"tns:ItemResponse\" name=\"ItemResponse\"> </wsdl:part>\n </wsdl:message>\n <wsdl:portType name=\"Item\">\n <wsdl:operation name=\"Item\">\n <wsdl:input message=\"tns:ItemRequest\" name=\"ItemRequest\"> </wsdl:input>\n <wsdl:output message=\"tns:ItemResponse\" name=\"ItemResponse\"> </wsdl:output>\n </wsdl:operation>\n </wsdl:portType>\n <wsdl:binding name=\"ItemSoap11\" type=\"tns:Item\">\n <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name=\"Item\">\n <soap:operation soapAction=\"\"/>\n <wsdl:input name=\"ItemRequest\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"ItemResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n </wsdl:binding>\n <wsdl:service name=\"ItemService\">\n <wsdl:port binding=\"tns:ItemSoap11\" name=\"ItemSoap11\">\n <soap:address location=\"http://localhost:8080/ws\"/>\n </wsdl:port>\n </wsdl:service>\n</wsdl:definitions>"
},
{
"code": null,
"e": 6943,
"s": 6752,
"text": "After this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml."
},
{
"code": null,
"e": 7476,
"s": 6943,
"text": "package com.onlinetutorialspoint.soap.bindings;\n\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javax.xml.bind.annotation.XmlType;\n\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\", propOrder = {\n \"id\"\n})\n@XmlRootElement(name = \"ItemRequest\")\npublic class ItemRequest {\n\n protected int id;\n\n public int getId() {\n return id;\n }\n\n public void setId(int value) {\n this.id = value;\n }\n\n}\n"
},
{
"code": null,
"e": 8512,
"s": 7476,
"text": "package com.onlinetutorialspoint.soap.bindings;\n\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javax.xml.bind.annotation.XmlType;\n\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\", propOrder = {\n \"id\",\n \"name\",\n \"category\"\n})\n@XmlRootElement(name = \"ItemResponse\")\npublic class ItemResponse {\n\n protected int id;\n @XmlElement(required = true)\n protected String name;\n @XmlElement(required = true)\n protected String category;\n \n public int getId() {\n return id;\n }\n \n public void setId(int value) {\n this.id = value;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String value) {\n this.name = value;\n }\n \n public String getCategory() {\n return category;\n }\n \n public void setCategory(String value) {\n this.category = value;\n }\n\n}\n"
},
{
"code": null,
"e": 8869,
"s": 8512,
"text": "package com.onlinetutorialspoint.soap.bindings;\n\nimport javax.xml.bind.annotation.XmlRegistry;\n\n@XmlRegistry\npublic class ObjectFactory {\n \n public ObjectFactory() {\n }\n\n public ItemRequest createItemRequest() {\n return new ItemRequest();\n }\n\n public ItemResponse createItemResponse() {\n return new ItemResponse();\n }\n\n}\n"
},
{
"code": null,
"e": 8954,
"s": 8869,
"text": "Making this application port to 8081. As I have a SOAP service running on 8080 port."
},
{
"code": null,
"e": 8971,
"s": 8954,
"text": "server.port=8081"
},
{
"code": null,
"e": 9072,
"s": 8971,
"text": "Creating Jaxb2Marshaller object and given the binding classes to scan while loading the application."
},
{
"code": null,
"e": 9565,
"s": 9072,
"text": "package com.onlinetutorialspoint.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.oxm.jaxb.Jaxb2Marshaller;\n\n@Configuration\npublic class SoapConfig {\n\n @Bean\n public Jaxb2Marshaller marshaller(){\n Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();\n jaxb2Marshaller.setPackagesToScan(\"com.onlinetutorialspoint.soap.bindings\");\n return jaxb2Marshaller;\n }\n}\n"
},
{
"code": null,
"e": 9707,
"s": 9565,
"text": "The SOAP client class, which is responsible for communicating with the SOAP service and getting the response using WebServiceTemplate object."
},
{
"code": null,
"e": 10496,
"s": 9707,
"text": "package com.onlinetutorialspoint.client;\n\nimport com.onlinetutorialspoint.soap.bindings.ItemRequest;\nimport com.onlinetutorialspoint.soap.bindings.ItemResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.oxm.jaxb.Jaxb2Marshaller;\nimport org.springframework.stereotype.Service;\nimport org.springframework.ws.client.core.WebServiceTemplate;\n\n@Service\npublic class SoapClient {\n\n @Autowired\n private Jaxb2Marshaller jaxb2Marshaller;\n\n private WebServiceTemplate webServiceTemplate;\n\n public ItemResponse getItemInfo(ItemRequest itemRequest){\n webServiceTemplate = new WebServiceTemplate(jaxb2Marshaller);\n return (ItemResponse) webServiceTemplate.marshalSendAndReceive(\"http://localhost:8080/ws\",itemRequest);\n }\n}\n"
},
{
"code": null,
"e": 10765,
"s": 10496,
"text": "On the above example, we have given the WSDL URI (http://localhost:8080/ws) to marshalSendAndReceive method. As I am running the service application on my local, I gave the local WSDL URI. If you wanted to access any remote WSDL, you could provide the remote URI here."
},
{
"code": null,
"e": 10824,
"s": 10765,
"text": "I am creating a RestController to access this SOAP client."
},
{
"code": null,
"e": 11590,
"s": 10824,
"text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.client.SoapClient;\nimport com.onlinetutorialspoint.soap.bindings.ItemRequest;\nimport com.onlinetutorialspoint.soap.bindings.ItemResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class ItemController {\n @Autowired\n SoapClient soapClient;\n\n @PostMapping(\"/item\")\n public ItemResponse item(@RequestBody ItemRequest itemRequest){\n return soapClient.getItemInfo(itemRequest);\n }\n}\n"
},
{
"code": null,
"e": 13345,
"s": 11590,
"text": "$mvn clean install\n$mvn spring-boot:run\n[INFO] --- spring-boot-maven-plugin:2.1.6.RELEASE:run (default-cli) @ Spring-Boot-SOAP-Consumer-Example ---\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.1.6.RELEASE)\n\n2019-07-27 00:36:29.644 INFO 23148 --- [ main] SpringBootSoapConsumerExampleApplication : Starting SpringBootSoapConsumerExampleApplication on DESKTOP-RN4SMHT with PID 23148 (\nD:\\work\\Spring-Boot-SOAP-Consumer-Example\\target\\classes started by Lenovo in D:\\work\\Spring-Boot-SOAP-Consumer-Example)\n2019-07-27 00:36:29.657 INFO 23148 --- [ main] SpringBootSoapConsumerExampleApplication : No active profile set, falling back to default profiles: default\n2019-07-27 00:36:31.723 INFO 23148 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [or\ng.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$c255fca6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligi\nble for auto-proxying)\n2019-07-27 00:36:31.797 INFO 23148 --- [ main] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]\n2019-07-27 00:36:32.760 INFO 23148 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)\n2019-07-27 00:36:32.811 INFO 23148 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n....\n...."
},
{
"code": null,
"e": 13351,
"s": 13345,
"text": "Done!"
},
{
"code": null,
"e": 13381,
"s": 13351,
"text": "Spring Boot Soap Web Services"
},
{
"code": null,
"e": 13413,
"s": 13381,
"text": "Installing SOAPUI on Windows 10"
},
{
"code": null,
"e": 14036,
"s": 13413,
"text": "\nSpring Boot Soap WebServices Example\nSimple Spring Boot Example\nMicroServices Spring Boot Eureka Server Example\nSpring Boot Actuator Database Health Check\nHow to install SOAPUI on Windows 10\nSpring Boot How to change the Tomcat to Jetty Server\nHow to set Spring Boot SetTimeZone\nSpring Boot MongoDB + Spring Data Example\nSpring Boot MVC Example Tutorials\nSpring Boot JPA Integration Example\nHow To Change Spring Boot Context Path\nHow to Get All Spring Beans Details Loaded in ICO\nHow to change Spring Boot Tomcat Port Number\nSpring Boot RabbitMQ Consumer Messages Example\nHow to enable Swagger in Spring Boot Application\n"
},
{
"code": null,
"e": 14073,
"s": 14036,
"text": "Spring Boot Soap WebServices Example"
},
{
"code": null,
"e": 14100,
"s": 14073,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 14148,
"s": 14100,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 14191,
"s": 14148,
"text": "Spring Boot Actuator Database Health Check"
},
{
"code": null,
"e": 14227,
"s": 14191,
"text": "How to install SOAPUI on Windows 10"
},
{
"code": null,
"e": 14280,
"s": 14227,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 14315,
"s": 14280,
"text": "How to set Spring Boot SetTimeZone"
},
{
"code": null,
"e": 14357,
"s": 14315,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 14391,
"s": 14357,
"text": "Spring Boot MVC Example Tutorials"
},
{
"code": null,
"e": 14427,
"s": 14391,
"text": "Spring Boot JPA Integration Example"
},
{
"code": null,
"e": 14466,
"s": 14427,
"text": "How To Change Spring Boot Context Path"
},
{
"code": null,
"e": 14516,
"s": 14466,
"text": "How to Get All Spring Beans Details Loaded in ICO"
},
{
"code": null,
"e": 14561,
"s": 14516,
"text": "How to change Spring Boot Tomcat Port Number"
},
{
"code": null,
"e": 14608,
"s": 14561,
"text": "Spring Boot RabbitMQ Consumer Messages Example"
},
{
"code": null,
"e": 14657,
"s": 14608,
"text": "How to enable Swagger in Spring Boot Application"
},
{
"code": null,
"e": 15418,
"s": 14657,
"text": "\n\n\n\n\n\nDaniel\nJuly 1, 2021 at 2:58 am - Reply \n\nVery helpful and clean\n\n\n\n\n\n\n\n\n\nanupama\nAugust 9, 2021 at 12:57 pm - Reply \n\nAfter this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml.\nyour application as is working fine.\nbut when i used it for my purpose the plug in is not generating any bindings package ,\ni am not sure what i am doing wrong. exactly followed as per your application...\n\n\n\n\n\n\n\n\n\nchandrashekhar\nAugust 9, 2021 at 2:47 pm - Reply \n\nHey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue.\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 15491,
"s": 15418,
"text": "\n\n\n\n\nDaniel\nJuly 1, 2021 at 2:58 am - Reply \n\nVery helpful and clean\n\n\n\n"
},
{
"code": null,
"e": 15514,
"s": 15491,
"text": "Very helpful and clean"
},
{
"code": null,
"e": 16200,
"s": 15514,
"text": "\n\n\n\n\nanupama\nAugust 9, 2021 at 12:57 pm - Reply \n\nAfter this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml.\nyour application as is working fine.\nbut when i used it for my purpose the plug in is not generating any bindings package ,\ni am not sure what i am doing wrong. exactly followed as per your application...\n\n\n\n\n\n\n\n\n\nchandrashekhar\nAugust 9, 2021 at 2:47 pm - Reply \n\nHey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue.\n\n\n\n\n\n"
},
{
"code": null,
"e": 16391,
"s": 16200,
"text": "After this step, you just build the application, then you could see the binding classes under src/main/soap/bindings package. Because we configured this under the plugins section in pom.xml."
},
{
"code": null,
"e": 16516,
"s": 16391,
"text": "your application as is working fine.\nbut when i used it for my purpose the plug in is not generating any bindings package ,"
},
{
"code": null,
"e": 16597,
"s": 16516,
"text": "i am not sure what i am doing wrong. exactly followed as per your application..."
},
{
"code": null,
"e": 16830,
"s": 16597,
"text": "\n\n\n\n\nchandrashekhar\nAugust 9, 2021 at 2:47 pm - Reply \n\nHey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue.\n\n\n\n"
},
{
"code": null,
"e": 17003,
"s": 16830,
"text": "Hey Anupama, thanks for reaching me. Can you elaborate on the issue you are facing? or if you provide the error logs, that is much helpful for better research on the issue."
},
{
"code": null,
"e": 17009,
"s": 17007,
"text": "Δ"
},
{
"code": null,
"e": 17036,
"s": 17009,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 17063,
"s": 17036,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 17097,
"s": 17063,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 17138,
"s": 17097,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 17183,
"s": 17138,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 17221,
"s": 17183,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 17255,
"s": 17221,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 17286,
"s": 17255,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 17320,
"s": 17286,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 17353,
"s": 17320,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 17386,
"s": 17353,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 17426,
"s": 17386,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 17451,
"s": 17426,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 17482,
"s": 17451,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 17506,
"s": 17482,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 17552,
"s": 17506,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 17575,
"s": 17552,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 17602,
"s": 17575,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 17648,
"s": 17602,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 17688,
"s": 17648,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 17717,
"s": 17688,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 17751,
"s": 17717,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 17781,
"s": 17751,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 17817,
"s": 17781,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 17850,
"s": 17817,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 17883,
"s": 17850,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 17927,
"s": 17883,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 17961,
"s": 17927,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 17993,
"s": 17961,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 18021,
"s": 17993,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 18052,
"s": 18021,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 18093,
"s": 18052,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 18127,
"s": 18093,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 18152,
"s": 18127,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 18186,
"s": 18152,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 18222,
"s": 18186,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 18268,
"s": 18222,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 18319,
"s": 18268,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 18361,
"s": 18319,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 18392,
"s": 18361,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 18415,
"s": 18392,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 18445,
"s": 18415,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 18475,
"s": 18445,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 18524,
"s": 18475,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 18558,
"s": 18524,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 18591,
"s": 18558,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 18620,
"s": 18591,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 18652,
"s": 18620,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 18689,
"s": 18652,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 18718,
"s": 18689,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 18747,
"s": 18718,
"text": " Spring Boot – MockMvc JUnit"
}
] |
Java - toString() Method
|
This method returns a String object representing the specified character value, that is, a one-character string.
String toString(char ch)
Here is the detail of parameters −
ch − Primitive character type.
ch − Primitive character type.
This method returns String object.
public class Test {
public static void main(String args[]) {
System.out.println(Character.toString('c'));
System.out.println(Character.toString('C'));
}
}
This will produce the following result −
c
C
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2490,
"s": 2377,
"text": "This method returns a String object representing the specified character value, that is, a one-character string."
},
{
"code": null,
"e": 2516,
"s": 2490,
"text": "String toString(char ch)\n"
},
{
"code": null,
"e": 2551,
"s": 2516,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2582,
"s": 2551,
"text": "ch − Primitive character type."
},
{
"code": null,
"e": 2613,
"s": 2582,
"text": "ch − Primitive character type."
},
{
"code": null,
"e": 2648,
"s": 2613,
"text": "This method returns String object."
},
{
"code": null,
"e": 2822,
"s": 2648,
"text": "public class Test {\n\n public static void main(String args[]) {\n System.out.println(Character.toString('c'));\n System.out.println(Character.toString('C'));\n }\n}"
},
{
"code": null,
"e": 2863,
"s": 2822,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2868,
"s": 2863,
"text": "c\nC\n"
},
{
"code": null,
"e": 2901,
"s": 2868,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2917,
"s": 2901,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2950,
"s": 2917,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2966,
"s": 2950,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3001,
"s": 2966,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3015,
"s": 3001,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3049,
"s": 3015,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3063,
"s": 3049,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3100,
"s": 3063,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3115,
"s": 3100,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3148,
"s": 3115,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3167,
"s": 3148,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3174,
"s": 3167,
"text": " Print"
},
{
"code": null,
"e": 3185,
"s": 3174,
"text": " Add Notes"
}
] |
Find the element that appears once in sorted array | Practice | GeeksforGeeks
|
Given a sorted array arr[] of size N. Find the element that appears only once in the array. All other elements appear exactly twice.
Example 1:
Input:
N = 11
arr[] = {1, 1, 2, 2, 3, 3, 4, 50, 50, 65, 65}
Output: 4
Explanation: 4 is the only element that
appears exactly once.
Your Task:
You don't need to read input or print anything. Complete the function findOnce() which takes sorted array and its size as its input parameter and returns the element that appears only once.
Expected Time Complexity: O(log N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
-105 <= arr[i] <= 105
0
heenabaig31717 hours ago
Kkk
0
prathyushab8002 days ago
from collections import Counterclass Solution: def findOnce(self,arr : list, n : int): # Complete this function c=Counter(arr) for k,v in c.items(): if(v==1): return k
0
patilamrut1793 days ago
class Solution{ findOnce(arr,n){ //code here if(n===1) return arr[0];
for(let i=0; i<n; i++) { if(i%2===0 && (i===n-1 || arr[i]!==arr[i+1])) return arr[i]; } return -1; }}
0
sanketmudhulkar983 days ago
C++ easy solution using hashmap
int findOnce(int arr[], int n) { unordered_map<int,int>freq; for(int i=0;i<n;i++) { freq[arr[i]]++; } for(int i=0;i<n;i++) { if(freq[arr[i]]==1) { return arr[i]; } } return -1; }
0
harshilrpanchal19984 days ago
superb java solution
class Solution { int findOnce(int arr[], int n) { // Complete this function HashMap<Integer, Integer> map = new HashMap<>(); int ans = 0;
for (int i=0 ; i < n ; i++){ map.put(arr[i] , map.getOrDefault(arr[i] ,0)+1); } for (Map.Entry<Integer ,Integer> entry : map.entrySet()){ if (entry.getValue() == 1){ ans = entry.getKey(); break; } } return ans; }}
0
mayank180919991 week ago
int findOnce(int arr[], int n)
{
//code here.
int ans=0;
unordered_map<int,int>m;
for(int i=0;i<n;i++){
m[arr[i]]++;
}
for(int i=0;i<n;i++){
if(m[arr[i]]==1){
ans=arr[i];
}
}
return ans;
}
0
prabhakarsati294261 week ago
def findOnce(self,arr : list, n : int): # Complete this function x = 0 for i in range(n): x = x^arr[i] return x
0
prabhakarsati29426
This comment was deleted.
+1
aloksinghbais021 week ago
C++ solution having time complexity as O(log(N)) and space complexity as O(1) is as follows :-
Execution Time :- 0.21 / 1.37 sec
int findOnce(int arr[], int n){ int s = 0; int e = n-1; int ans = -1; while(s <= e){ int mid = (s+e)/2; if((mid + 1 < n && arr[mid+1] == arr[mid]) || (mid - 1 >= 0 && arr[mid-1] == arr[mid])){ if(mid+1 < n && arr[mid+1] == arr[mid]){ if(mid & 1){ ans = mid; e = mid - 1; } else{ s = mid + 1; } } else if(mid - 1 >= 0 && arr[mid-1] == arr[mid]){ if((mid+1) & 1){ ans = mid; e = mid - 1; } else{ s = mid + 1; } } } else{ ans = mid; break; } } return (arr[ans]); }
0
aryapratik8282 weeks ago
int ans=0; for(int i=0;i<n;i++) { ans=ans^arr[i]; } return ans;
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": 372,
"s": 238,
"text": "Given a sorted array arr[] of size N. Find the element that appears only once in the array. All other elements appear exactly twice. "
},
{
"code": null,
"e": 383,
"s": 372,
"text": "Example 1:"
},
{
"code": null,
"e": 516,
"s": 383,
"text": "Input:\nN = 11\narr[] = {1, 1, 2, 2, 3, 3, 4, 50, 50, 65, 65}\nOutput: 4\nExplanation: 4 is the only element that \nappears exactly once."
},
{
"code": null,
"e": 722,
"s": 518,
"text": "Your Task: \nYou don't need to read input or print anything. Complete the function findOnce() which takes sorted array and its size as its input parameter and returns the element that appears only once. "
},
{
"code": null,
"e": 789,
"s": 722,
"text": "\nExpected Time Complexity: O(log N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 840,
"s": 791,
"text": "Constraints:\n1 <= N <= 105\n-105 <= arr[i] <= 105"
},
{
"code": null,
"e": 844,
"s": 842,
"text": "0"
},
{
"code": null,
"e": 869,
"s": 844,
"text": "heenabaig31717 hours ago"
},
{
"code": null,
"e": 873,
"s": 869,
"text": "Kkk"
},
{
"code": null,
"e": 875,
"s": 873,
"text": "0"
},
{
"code": null,
"e": 900,
"s": 875,
"text": "prathyushab8002 days ago"
},
{
"code": null,
"e": 1112,
"s": 900,
"text": "from collections import Counterclass Solution: def findOnce(self,arr : list, n : int): # Complete this function c=Counter(arr) for k,v in c.items(): if(v==1): return k"
},
{
"code": null,
"e": 1116,
"s": 1114,
"text": "0"
},
{
"code": null,
"e": 1140,
"s": 1116,
"text": "patilamrut1793 days ago"
},
{
"code": null,
"e": 1224,
"s": 1140,
"text": "class Solution{ findOnce(arr,n){ //code here if(n===1) return arr[0];"
},
{
"code": null,
"e": 1357,
"s": 1224,
"text": " for(let i=0; i<n; i++) { if(i%2===0 && (i===n-1 || arr[i]!==arr[i+1])) return arr[i]; } return -1; }}"
},
{
"code": null,
"e": 1359,
"s": 1357,
"text": "0"
},
{
"code": null,
"e": 1387,
"s": 1359,
"text": "sanketmudhulkar983 days ago"
},
{
"code": null,
"e": 1419,
"s": 1387,
"text": "C++ easy solution using hashmap"
},
{
"code": null,
"e": 1728,
"s": 1421,
"text": " int findOnce(int arr[], int n) { unordered_map<int,int>freq; for(int i=0;i<n;i++) { freq[arr[i]]++; } for(int i=0;i<n;i++) { if(freq[arr[i]]==1) { return arr[i]; } } return -1; }"
},
{
"code": null,
"e": 1730,
"s": 1728,
"text": "0"
},
{
"code": null,
"e": 1760,
"s": 1730,
"text": "harshilrpanchal19984 days ago"
},
{
"code": null,
"e": 1781,
"s": 1760,
"text": "superb java solution"
},
{
"code": null,
"e": 1943,
"s": 1783,
"text": "class Solution { int findOnce(int arr[], int n) { // Complete this function HashMap<Integer, Integer> map = new HashMap<>(); int ans = 0;"
},
{
"code": null,
"e": 2245,
"s": 1943,
"text": " for (int i=0 ; i < n ; i++){ map.put(arr[i] , map.getOrDefault(arr[i] ,0)+1); } for (Map.Entry<Integer ,Integer> entry : map.entrySet()){ if (entry.getValue() == 1){ ans = entry.getKey(); break; } } return ans; }}"
},
{
"code": null,
"e": 2247,
"s": 2245,
"text": "0"
},
{
"code": null,
"e": 2272,
"s": 2247,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 2584,
"s": 2272,
"text": " int findOnce(int arr[], int n)\n {\n //code here.\n int ans=0;\n unordered_map<int,int>m;\n for(int i=0;i<n;i++){\n m[arr[i]]++;\n }\n for(int i=0;i<n;i++){\n if(m[arr[i]]==1){\n ans=arr[i];\n }\n }\n return ans;\n }"
},
{
"code": null,
"e": 2586,
"s": 2584,
"text": "0"
},
{
"code": null,
"e": 2615,
"s": 2586,
"text": "prabhakarsati294261 week ago"
},
{
"code": null,
"e": 2762,
"s": 2615,
"text": " def findOnce(self,arr : list, n : int): # Complete this function x = 0 for i in range(n): x = x^arr[i] return x"
},
{
"code": null,
"e": 2764,
"s": 2762,
"text": "0"
},
{
"code": null,
"e": 2783,
"s": 2764,
"text": "prabhakarsati29426"
},
{
"code": null,
"e": 2809,
"s": 2783,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2812,
"s": 2809,
"text": "+1"
},
{
"code": null,
"e": 2838,
"s": 2812,
"text": "aloksinghbais021 week ago"
},
{
"code": null,
"e": 2934,
"s": 2838,
"text": "C++ solution having time complexity as O(log(N)) and space complexity as O(1) is as follows :- "
},
{
"code": null,
"e": 2970,
"s": 2936,
"text": "Execution Time :- 0.21 / 1.37 sec"
},
{
"code": null,
"e": 3893,
"s": 2972,
"text": "int findOnce(int arr[], int n){ int s = 0; int e = n-1; int ans = -1; while(s <= e){ int mid = (s+e)/2; if((mid + 1 < n && arr[mid+1] == arr[mid]) || (mid - 1 >= 0 && arr[mid-1] == arr[mid])){ if(mid+1 < n && arr[mid+1] == arr[mid]){ if(mid & 1){ ans = mid; e = mid - 1; } else{ s = mid + 1; } } else if(mid - 1 >= 0 && arr[mid-1] == arr[mid]){ if((mid+1) & 1){ ans = mid; e = mid - 1; } else{ s = mid + 1; } } } else{ ans = mid; break; } } return (arr[ans]); }"
},
{
"code": null,
"e": 3895,
"s": 3893,
"text": "0"
},
{
"code": null,
"e": 3920,
"s": 3895,
"text": "aryapratik8282 weeks ago"
},
{
"code": null,
"e": 4017,
"s": 3920,
"text": "int ans=0; for(int i=0;i<n;i++) { ans=ans^arr[i]; } return ans;"
},
{
"code": null,
"e": 4163,
"s": 4017,
"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": 4199,
"s": 4163,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4209,
"s": 4199,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4219,
"s": 4209,
"text": "\nContest\n"
},
{
"code": null,
"e": 4282,
"s": 4219,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4430,
"s": 4282,
"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": 4638,
"s": 4430,
"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": 4744,
"s": 4638,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Scatter Plots with Plotly Express | by Darío Weitz | Towards Data Science
|
You could say that it was a dream team of data science: a physics Ph.D. from Harvard, a Silicon Valley analyst in energy, a member of Facebook, and a guy who worked in a research startup, also in the Valley. Together, Alex Johnson, Jack Parmer, Matthew Sundquist, and Chris Parmer, founded Plotly, a technical computing company in Montreal, Canada.
The Plotly visualization tool was built around 2013 using Python and the Django framework, with a front end using JavaScript and the visualization library D3.js, HTML, and CSS. So, at its core, Plotly is actually a JavaScript library. Remember that D3.js is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. But Python developers hardly ever need to engage with the JavaScript library directly. They can use plotly.py, an interactive, open-source, and browser-based graphing library for Python.
In 2019 the company made a quantitative leap with the launch of Plotly Express, a new high-level Python visualization library. Plotly Express is a high-level wrapper for Plotly.py fully compatible with the rest of the Plotly ecosystem, simple, powerful, and somewhat similar to Seaborn. It’s free and can be used in commercial applications and products. The library includes functions to plot trendlines and maps, as well as to perform faceting and animations. With Plotly Express you can make interactive graphics online but you can also save them offline.
The last version of plotly may be installed using pip:
$ pip install plotly==4.14.3
or conda:
$ conda install -c plotly plotly=4.14.3
Scatter plots are used to determine if a pair of numerical variables are correlated. They are suitable for distribution analysis of two numerical variables. They should not be used to show trends over time. They are also not suitable for comparison analysis. Besides, they are not appropriate when the nature of the message is to show quantities.
Starting from a dataset representing two numerical variables that are indicated by points in a Cartesian plane x-y, the message is narrated from the shape that these data points generate, through revealing the existence or not of a correlation. Such correlation can be positive or negative and is obtained by representing a significant number of data points. Even though each point indicates exact numerical values, the purpose of the visualization is to determine whether or not a relationship or correlation exists between the numerical variables represented, rather than focusing on the exact values indicated.
A correlation is defined as a measure (a metric) to evaluate the relationship between two variables. You can calculate (using an equation) the correlation coefficient (r) that takes values between 1 to -1: a value close to 0 indicates no correlation; a value close to 1 indicates a very strong direct relationship between the two variables; a value close to -1 indicates a very strong inverse relationship between them; values greater than 0.7 or -0.7 indicate, respectively, strong direct or inverse relationships; values below 0.3 or -0.3 indicate weak or null direct or inverse relationships.
Three important features of the dataset can be found in a scatter plot: 1.- Outliers, a piece of data that is very different from all the others in the dataset and does not seem to fit the same pattern. Those anomalous values might represent valuable information to analyze. First of all, it must be verified that the existence of these anomalous values is not due to errors while measuring the data; 2.- Gaps, an interval that contains no data. The visualization of gaps between data justifies an in-depth analysis that explains their presence; 3.- Clusters, isolated groups of data points which can also merit a particular analysis of the reason for their presence in the graph. Of course, gaps and clusters might also represent errors in the data collection methodology.
A regression line is habitually added to the scatter plot. Also named as Line of Best Fit or Trendline, it mathematically expresses the relationship between both numerical variables. A trendline is meant to mimic the trend of the data. It’s a line of best fit that approximates the direction in which the plotted points appear to be heading. Usually, the goal of the regression lines is to estimate some unmeasured values of the independent variable utilizing the interpolation technique or use it for forecasting purposes via extrapolation. Special care should be taken not to confuse correlation with causation.
First, we import Plotly Express usually as px:
import plotly.express as px
In our first example, we are going to determine if there is a correlation between two datasets generated with the Numpy function random.randint:
import plotly.express as pximport numpy as np## set the seed to a random number obtained from /dev/urandom## or its Windows analog, ## or if neither of those is available, it will use the clock.np.random.seed()rand_x = np.random.randint(1,100,50)rand_y = np.random.randint(1,100,50)## trendline = 'ols' allow us to draw a trendlinefig = px.scatter(x = rand_x, y = rand_y, trendline = 'ols')fig.write_image(path + "figscat.png")fig.show()
Clearly, there is no correlation. The trendline is based on the Ordinary Least Square method (OLS). Previously, you must install statsmodels and its dependencies to use the argument trendline.
It's a nice chart, but not enough for today's standards. We can improve it significantly using functions from the Plotly Express library.
We suggest using a procedure similar to the following:
First, select an effective visual encoding to map your data values to a graphical feature and determine the corresponding parameters. For the scatter plots in this article, the Plotly Express function is px.scatter and the corresponding parameters are: dataframe; a numerical variable for the x-axis; a numerical variable for the y-axis; color to include other variables, especially categorical ones; the trendline method for the regression line; and the hover data and hover name. The hover_name property controls which column is displayed in bold as the tooltip title, whilst the hover_data argument accepts a list of column names to be added to the hover tooltip.
Second, analyze if your storytelling needs faceting. The faceting approach splits a chart into a matrix of panels, each one showing a different subset of the dataset based on a categorical variable. You can do it by column facet_col = [‘col_name’], or by row.
Third, update the chart with update.layout: set the title; the name of the x-axis and the name of the y-axis; set the figure dimensions with width and height.
Forth, add annotations with add_annotation. Remember that annotations relate to text placed in arbitrary positions in the chart. They usually consist of text, arrows, or other shapes.
Fifth, analyze if you need animation frames. Animated plots are a great way to display the dynamics of the underlying data. Dynamic systems are systems that evolve over time. We are not going to include animations because our dataframe doesn’t include a time dimension.
Finally, export the file: you can do that as a static format like PDF, SVG, PNG, or similar using fig.write_image(path + “fig_scat.png”) or save it as an HTML page for zooming or seeing the tooltips fig.write_html(path + ‘fig_scat.html’).
We worked with a dataset downloaded from Kaggle [2]. The dataset consists of 10,000 bank customers mentioning their age, salary, marital status, credit card limit, credit card category, education level, and additional features. The bank manager is disturbed with customers leaving their credit card services (attrited customers). So, we are going to determine if there is any relationship between some numerical variables and the attrition condition.
To avoid congestion and overlapping, we selected randomly 1500 of those customers as a sample of the population under study by means of df = df.sample(frac = 0.15).
First, we analyzed if there was any relationship between customer age and the limit in credit imposed by the bank. So, Customer_Age was chosen as the numerical variable for the x-axis and Credit_Limit as the numerical variable for the y-axis. We included color = ‘Gender’ to verify if there was a gender bias in the bank management directives. We saved the chart in a PNG static format. If you want to use the following code, don’t forget to import pandas as pd.
df = pd.read_csv(path + 'CreditCardCustomersCols.csv', index_col = False, header = 0,sep = ';', engine='python')## get a random selection of 1500 rows, a fifteen-percent of the ## dataframedf = df.sample(frac = 0.15)fig = px.scatter(df, x="Customer_Age", y="Credit_Limit", color = 'Gender', trendline = ‘ols’)fig.update_layout(title = 'Relation between Customer Age and Credit Limit', xaxis_title = 'Customer Age', yaxis_title = 'Credit Limit', width = 1600, height = 1400)fig.write_image(path + "figscat1.png")fig.show()
Plotly Express allows you to retrieve the model parameters using results = px.get_trendline_results(fig). You may choose between .summary() for a complete statistical summary, or .params for the equation of the line, or .rsquared to get the statistical measure of fit.
# retrieve the model parametersresults = px.get_trendline_results(fig)results = results.iloc[0]["px_fit_results"].summary()coef1 = results.iloc[0]["px_fit_results"].paramscoef2 = results.iloc[1]["px_fit_results"].paramsrsq1 = px.get_trendline_results(fig).px_fit_results.iloc[0].rsquaredrsq2 = px.get_trendline_results(fig).px_fit_results.iloc[1].rsquaredprint(results)print(coef1, coef2)print(rsq1, rsq2)
Fig. 4 shows the same numerical variables faceted on the categorical variable facet_col = ‘Attrition_Flag’. This variable only takes the following two values: [Existing Customer, Attrited Customer]. Similar weak correlations and the gender bias are shown in both panels.
In the following two figures, we change one of the numerical variables (Months on Book instead of Customer Age), replace the categorical variable associated with the color argument (Marital Status), and add an annotation (35K Cluster). The second figure is the faceted version of the first one (facet_col = ‘Attrition_Flag’), also based on the categorical variable related to the condition of customers’ attrition. Both figures are exported as HTML files with the variable Education Level included in the tooltips.
fig2 = px.scatter(df, x="Months_on_book", y="Credit_Limit", color = 'Marital_Status',hover_data = ['Education_Level'])fig2.update_layout(title = 'Relation between Months on Book and Credit Limit', xaxis_title = 'Months on Book' , yaxis_title = 'Credit Limit', width = 800, height = 600)fig2.add_annotation( # add a text callout with arrow text="35K Cluster", x= 35, y=35000, arrowhead=1,showarrow=True)fig2.write_html(path + 'figscat2.html')fig2.show()
There is no correlation between the numerical variables. Also, there is no relationship between the variables and the attrition condition or the marital status. We decide not to plot the trendlines because more than two regression lines on the screen might confuse the audience.
To sum up:
You might use a scatter plot when you want to show the relationship or correlation that exists between two numerical variables;
Plotly Express is an excellent choice for building and customizing charts that include trendlines and faceting.
If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):
Diverging Bars, Why & How, Storytelling with Divergences
towardsdatascience.com
Slope Charts, Why & How, Storytelling with Slopes
|
[
{
"code": null,
"e": 521,
"s": 172,
"text": "You could say that it was a dream team of data science: a physics Ph.D. from Harvard, a Silicon Valley analyst in energy, a member of Facebook, and a guy who worked in a research startup, also in the Valley. Together, Alex Johnson, Jack Parmer, Matthew Sundquist, and Chris Parmer, founded Plotly, a technical computing company in Montreal, Canada."
},
{
"code": null,
"e": 1059,
"s": 521,
"text": "The Plotly visualization tool was built around 2013 using Python and the Django framework, with a front end using JavaScript and the visualization library D3.js, HTML, and CSS. So, at its core, Plotly is actually a JavaScript library. Remember that D3.js is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. But Python developers hardly ever need to engage with the JavaScript library directly. They can use plotly.py, an interactive, open-source, and browser-based graphing library for Python."
},
{
"code": null,
"e": 1617,
"s": 1059,
"text": "In 2019 the company made a quantitative leap with the launch of Plotly Express, a new high-level Python visualization library. Plotly Express is a high-level wrapper for Plotly.py fully compatible with the rest of the Plotly ecosystem, simple, powerful, and somewhat similar to Seaborn. It’s free and can be used in commercial applications and products. The library includes functions to plot trendlines and maps, as well as to perform faceting and animations. With Plotly Express you can make interactive graphics online but you can also save them offline."
},
{
"code": null,
"e": 1672,
"s": 1617,
"text": "The last version of plotly may be installed using pip:"
},
{
"code": null,
"e": 1701,
"s": 1672,
"text": "$ pip install plotly==4.14.3"
},
{
"code": null,
"e": 1711,
"s": 1701,
"text": "or conda:"
},
{
"code": null,
"e": 1751,
"s": 1711,
"text": "$ conda install -c plotly plotly=4.14.3"
},
{
"code": null,
"e": 2098,
"s": 1751,
"text": "Scatter plots are used to determine if a pair of numerical variables are correlated. They are suitable for distribution analysis of two numerical variables. They should not be used to show trends over time. They are also not suitable for comparison analysis. Besides, they are not appropriate when the nature of the message is to show quantities."
},
{
"code": null,
"e": 2712,
"s": 2098,
"text": "Starting from a dataset representing two numerical variables that are indicated by points in a Cartesian plane x-y, the message is narrated from the shape that these data points generate, through revealing the existence or not of a correlation. Such correlation can be positive or negative and is obtained by representing a significant number of data points. Even though each point indicates exact numerical values, the purpose of the visualization is to determine whether or not a relationship or correlation exists between the numerical variables represented, rather than focusing on the exact values indicated."
},
{
"code": null,
"e": 3314,
"s": 2712,
"text": "A correlation is defined as a measure (a metric) to evaluate the relationship between two variables. You can calculate (using an equation) the correlation coefficient (r) that takes values between 1 to -1: a value close to 0 indicates no correlation; a value close to 1 indicates a very strong direct relationship between the two variables; a value close to -1 indicates a very strong inverse relationship between them; values greater than 0.7 or -0.7 indicate, respectively, strong direct or inverse relationships; values below 0.3 or -0.3 indicate weak or null direct or inverse relationships."
},
{
"code": null,
"e": 4092,
"s": 3314,
"text": "Three important features of the dataset can be found in a scatter plot: 1.- Outliers, a piece of data that is very different from all the others in the dataset and does not seem to fit the same pattern. Those anomalous values might represent valuable information to analyze. First of all, it must be verified that the existence of these anomalous values is not due to errors while measuring the data; 2.- Gaps, an interval that contains no data. The visualization of gaps between data justifies an in-depth analysis that explains their presence; 3.- Clusters, isolated groups of data points which can also merit a particular analysis of the reason for their presence in the graph. Of course, gaps and clusters might also represent errors in the data collection methodology."
},
{
"code": null,
"e": 4706,
"s": 4092,
"text": "A regression line is habitually added to the scatter plot. Also named as Line of Best Fit or Trendline, it mathematically expresses the relationship between both numerical variables. A trendline is meant to mimic the trend of the data. It’s a line of best fit that approximates the direction in which the plotted points appear to be heading. Usually, the goal of the regression lines is to estimate some unmeasured values of the independent variable utilizing the interpolation technique or use it for forecasting purposes via extrapolation. Special care should be taken not to confuse correlation with causation."
},
{
"code": null,
"e": 4753,
"s": 4706,
"text": "First, we import Plotly Express usually as px:"
},
{
"code": null,
"e": 4781,
"s": 4753,
"text": "import plotly.express as px"
},
{
"code": null,
"e": 4926,
"s": 4781,
"text": "In our first example, we are going to determine if there is a correlation between two datasets generated with the Numpy function random.randint:"
},
{
"code": null,
"e": 5364,
"s": 4926,
"text": "import plotly.express as pximport numpy as np## set the seed to a random number obtained from /dev/urandom## or its Windows analog, ## or if neither of those is available, it will use the clock.np.random.seed()rand_x = np.random.randint(1,100,50)rand_y = np.random.randint(1,100,50)## trendline = 'ols' allow us to draw a trendlinefig = px.scatter(x = rand_x, y = rand_y, trendline = 'ols')fig.write_image(path + \"figscat.png\")fig.show()"
},
{
"code": null,
"e": 5557,
"s": 5364,
"text": "Clearly, there is no correlation. The trendline is based on the Ordinary Least Square method (OLS). Previously, you must install statsmodels and its dependencies to use the argument trendline."
},
{
"code": null,
"e": 5695,
"s": 5557,
"text": "It's a nice chart, but not enough for today's standards. We can improve it significantly using functions from the Plotly Express library."
},
{
"code": null,
"e": 5750,
"s": 5695,
"text": "We suggest using a procedure similar to the following:"
},
{
"code": null,
"e": 6417,
"s": 5750,
"text": "First, select an effective visual encoding to map your data values to a graphical feature and determine the corresponding parameters. For the scatter plots in this article, the Plotly Express function is px.scatter and the corresponding parameters are: dataframe; a numerical variable for the x-axis; a numerical variable for the y-axis; color to include other variables, especially categorical ones; the trendline method for the regression line; and the hover data and hover name. The hover_name property controls which column is displayed in bold as the tooltip title, whilst the hover_data argument accepts a list of column names to be added to the hover tooltip."
},
{
"code": null,
"e": 6677,
"s": 6417,
"text": "Second, analyze if your storytelling needs faceting. The faceting approach splits a chart into a matrix of panels, each one showing a different subset of the dataset based on a categorical variable. You can do it by column facet_col = [‘col_name’], or by row."
},
{
"code": null,
"e": 6836,
"s": 6677,
"text": "Third, update the chart with update.layout: set the title; the name of the x-axis and the name of the y-axis; set the figure dimensions with width and height."
},
{
"code": null,
"e": 7020,
"s": 6836,
"text": "Forth, add annotations with add_annotation. Remember that annotations relate to text placed in arbitrary positions in the chart. They usually consist of text, arrows, or other shapes."
},
{
"code": null,
"e": 7290,
"s": 7020,
"text": "Fifth, analyze if you need animation frames. Animated plots are a great way to display the dynamics of the underlying data. Dynamic systems are systems that evolve over time. We are not going to include animations because our dataframe doesn’t include a time dimension."
},
{
"code": null,
"e": 7529,
"s": 7290,
"text": "Finally, export the file: you can do that as a static format like PDF, SVG, PNG, or similar using fig.write_image(path + “fig_scat.png”) or save it as an HTML page for zooming or seeing the tooltips fig.write_html(path + ‘fig_scat.html’)."
},
{
"code": null,
"e": 7980,
"s": 7529,
"text": "We worked with a dataset downloaded from Kaggle [2]. The dataset consists of 10,000 bank customers mentioning their age, salary, marital status, credit card limit, credit card category, education level, and additional features. The bank manager is disturbed with customers leaving their credit card services (attrited customers). So, we are going to determine if there is any relationship between some numerical variables and the attrition condition."
},
{
"code": null,
"e": 8145,
"s": 7980,
"text": "To avoid congestion and overlapping, we selected randomly 1500 of those customers as a sample of the population under study by means of df = df.sample(frac = 0.15)."
},
{
"code": null,
"e": 8608,
"s": 8145,
"text": "First, we analyzed if there was any relationship between customer age and the limit in credit imposed by the bank. So, Customer_Age was chosen as the numerical variable for the x-axis and Credit_Limit as the numerical variable for the y-axis. We included color = ‘Gender’ to verify if there was a gender bias in the bank management directives. We saved the chart in a PNG static format. If you want to use the following code, don’t forget to import pandas as pd."
},
{
"code": null,
"e": 9174,
"s": 8608,
"text": "df = pd.read_csv(path + 'CreditCardCustomersCols.csv', index_col = False, header = 0,sep = ';', engine='python')## get a random selection of 1500 rows, a fifteen-percent of the ## dataframedf = df.sample(frac = 0.15)fig = px.scatter(df, x=\"Customer_Age\", y=\"Credit_Limit\", color = 'Gender', trendline = ‘ols’)fig.update_layout(title = 'Relation between Customer Age and Credit Limit', xaxis_title = 'Customer Age', yaxis_title = 'Credit Limit', width = 1600, height = 1400)fig.write_image(path + \"figscat1.png\")fig.show()"
},
{
"code": null,
"e": 9443,
"s": 9174,
"text": "Plotly Express allows you to retrieve the model parameters using results = px.get_trendline_results(fig). You may choose between .summary() for a complete statistical summary, or .params for the equation of the line, or .rsquared to get the statistical measure of fit."
},
{
"code": null,
"e": 9849,
"s": 9443,
"text": "# retrieve the model parametersresults = px.get_trendline_results(fig)results = results.iloc[0][\"px_fit_results\"].summary()coef1 = results.iloc[0][\"px_fit_results\"].paramscoef2 = results.iloc[1][\"px_fit_results\"].paramsrsq1 = px.get_trendline_results(fig).px_fit_results.iloc[0].rsquaredrsq2 = px.get_trendline_results(fig).px_fit_results.iloc[1].rsquaredprint(results)print(coef1, coef2)print(rsq1, rsq2)"
},
{
"code": null,
"e": 10120,
"s": 9849,
"text": "Fig. 4 shows the same numerical variables faceted on the categorical variable facet_col = ‘Attrition_Flag’. This variable only takes the following two values: [Existing Customer, Attrited Customer]. Similar weak correlations and the gender bias are shown in both panels."
},
{
"code": null,
"e": 10635,
"s": 10120,
"text": "In the following two figures, we change one of the numerical variables (Months on Book instead of Customer Age), replace the categorical variable associated with the color argument (Marital Status), and add an annotation (35K Cluster). The second figure is the faceted version of the first one (facet_col = ‘Attrition_Flag’), also based on the categorical variable related to the condition of customers’ attrition. Both figures are exported as HTML files with the variable Education Level included in the tooltips."
},
{
"code": null,
"e": 11125,
"s": 10635,
"text": "fig2 = px.scatter(df, x=\"Months_on_book\", y=\"Credit_Limit\", color = 'Marital_Status',hover_data = ['Education_Level'])fig2.update_layout(title = 'Relation between Months on Book and Credit Limit', xaxis_title = 'Months on Book' , yaxis_title = 'Credit Limit', width = 800, height = 600)fig2.add_annotation( # add a text callout with arrow text=\"35K Cluster\", x= 35, y=35000, arrowhead=1,showarrow=True)fig2.write_html(path + 'figscat2.html')fig2.show()"
},
{
"code": null,
"e": 11404,
"s": 11125,
"text": "There is no correlation between the numerical variables. Also, there is no relationship between the variables and the attrition condition or the marital status. We decide not to plot the trendlines because more than two regression lines on the screen might confuse the audience."
},
{
"code": null,
"e": 11415,
"s": 11404,
"text": "To sum up:"
},
{
"code": null,
"e": 11543,
"s": 11415,
"text": "You might use a scatter plot when you want to show the relationship or correlation that exists between two numerical variables;"
},
{
"code": null,
"e": 11655,
"s": 11543,
"text": "Plotly Express is an excellent choice for building and customizing charts that include trendlines and faceting."
},
{
"code": null,
"e": 11748,
"s": 11655,
"text": "If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):"
},
{
"code": null,
"e": 11805,
"s": 11748,
"text": "Diverging Bars, Why & How, Storytelling with Divergences"
},
{
"code": null,
"e": 11828,
"s": 11805,
"text": "towardsdatascience.com"
}
] |
Tryit Editor v3.7
|
Tryit: HTML fonts
|
[] |
How to find the 95% confidence interval for the glm model in R?
|
To find the confidence interval for a lm model (linear regression model), we can use confint function and there is no need to pass the confidence level because the default is 95%. This can be also used for a glm model (general linear model). Check out the below examples to see the output of confint for a glm model.
Live Demo
> set.seed(3214)
> x1<-rpois(20,5)
> y1<-sample(0:1,20,replace=TRUE)
> Model1<-glm(y1~x1,family="binomial")
> summary(Model1)
Call:
glm(formula = y1 ~ x1, family = "binomial")
Deviance Residuals:
Min 1Q Median 3Q Max
-1.6360 -1.4156 0.7800 0.8567 0.9946
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.34851 1.17554 0.296 0.767
x1 0.09794 0.21421 0.457 0.648
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 24.435 on 19 degrees of freedom
Residual deviance: 24.221 on 18 degrees of freedom
AIC: 28.221
Number of Fisher Scoring iterations: 4
> confint(Model1)
Waiting for profiling to be done...
2.5 % 97.5 %
(Intercept) -1.9946211 2.8014055
x1 -0.3179604 0.5537196
Live Demo
> x2<-runif(200,2,5)
> y2<-sample(0:1,200,replace=TRUE)
> Model2<-glm(y2~x2,family="binomial")
> summary(Model2)
Call:
glm(formula = y2 ~ x2, family = "binomial")
Deviance Residuals:
Min 1Q Median 3Q Max
-1.162 -1.152 -1.145 1.202 1.211
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.009208 0.631317 -0.015 0.988
x2 -0.013999 0.169522 -0.083 0.934
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 277.08 on 199 degrees of freedom
Residual deviance: 277.07 on 198 degrees of freedom
AIC: 281.07
Number of Fisher Scoring iterations: 3
> confint(Model2)
Waiting for profiling to be done...
2.5 % 97.5 %
(Intercept) -1.2517839 1.2317974
x2 -0.3473611 0.3192271
Live Demo
> x3<-runif(5000,2,5)
> y3<-sample(0:1,5000,replace=TRUE)
> Model3<-glm(y3~x3,family="binomial")
> summary(Model3)
Call:
glm(formula = y3 ~ x3, family = "binomial")
Deviance Residuals:
Min 1Q Median 3Q Max
-1.177 -1.166 -1.156 1.188 1.199
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.03254 0.11913 0.273 0.785
x3 -0.01674 0.03288 -0.509 0.611
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 6930.6 on 4999 degrees of freedom
Residual deviance: 6930.3 on 4998 degrees of freedom
AIC: 6934.3
Number of Fisher Scoring iterations: 3
> confint(Model3)
Waiting for profiling to be done...
2.5 % 97.5 %
(Intercept) -0.20096508 0.2660569
x3 -0.08119495 0.0476911
|
[
{
"code": null,
"e": 1379,
"s": 1062,
"text": "To find the confidence interval for a lm model (linear regression model), we can use confint function and there is no need to pass the confidence level because the default is 95%. This can be also used for a glm model (general linear model). Check out the below examples to see the output of confint for a glm model."
},
{
"code": null,
"e": 1389,
"s": 1379,
"text": "Live Demo"
},
{
"code": null,
"e": 1515,
"s": 1389,
"text": "> set.seed(3214)\n> x1<-rpois(20,5)\n> y1<-sample(0:1,20,replace=TRUE)\n> Model1<-glm(y1~x1,family=\"binomial\")\n> summary(Model1)"
},
{
"code": null,
"e": 2101,
"s": 1515,
"text": "Call:\nglm(formula = y1 ~ x1, family = \"binomial\")\n\nDeviance Residuals:\nMin 1Q Median 3Q Max\n-1.6360 -1.4156 0.7800 0.8567 0.9946\n\nCoefficients:\nEstimate Std. Error z value Pr(>|z|)\n(Intercept) 0.34851 1.17554 0.296 0.767\nx1 0.09794 0.21421 0.457 0.648\n\n(Dispersion parameter for binomial family taken to be 1)\n\nNull deviance: 24.435 on 19 degrees of freedom\nResidual deviance: 24.221 on 18 degrees of freedom\nAIC: 28.221\n\nNumber of Fisher Scoring iterations: 4\n\n> confint(Model1)\nWaiting for profiling to be done...\n2.5 % 97.5 %\n(Intercept) -1.9946211 2.8014055\nx1 -0.3179604 0.5537196"
},
{
"code": null,
"e": 2111,
"s": 2101,
"text": "Live Demo"
},
{
"code": null,
"e": 2224,
"s": 2111,
"text": "> x2<-runif(200,2,5)\n> y2<-sample(0:1,200,replace=TRUE)\n> Model2<-glm(y2~x2,family=\"binomial\")\n> summary(Model2)"
},
{
"code": null,
"e": 2816,
"s": 2224,
"text": "Call:\nglm(formula = y2 ~ x2, family = \"binomial\")\n\nDeviance Residuals:\nMin 1Q Median 3Q Max\n-1.162 -1.152 -1.145 1.202 1.211\n\nCoefficients:\nEstimate Std. Error z value Pr(>|z|)\n(Intercept) -0.009208 0.631317 -0.015 0.988\nx2 -0.013999 0.169522 -0.083 0.934\n\n(Dispersion parameter for binomial family taken to be 1)\n\nNull deviance: 277.08 on 199 degrees of freedom\nResidual deviance: 277.07 on 198 degrees of freedom\nAIC: 281.07\n\nNumber of Fisher Scoring iterations: 3\n\n> confint(Model2)\nWaiting for profiling to be done...\n2.5 % 97.5 %\n(Intercept) -1.2517839 1.2317974\nx2 -0.3473611 0.3192271"
},
{
"code": null,
"e": 2826,
"s": 2816,
"text": "Live Demo"
},
{
"code": null,
"e": 2941,
"s": 2826,
"text": "> x3<-runif(5000,2,5)\n> y3<-sample(0:1,5000,replace=TRUE)\n> Model3<-glm(y3~x3,family=\"binomial\")\n> summary(Model3)"
},
{
"code": null,
"e": 3531,
"s": 2941,
"text": "Call:\nglm(formula = y3 ~ x3, family = \"binomial\")\n\nDeviance Residuals:\nMin 1Q Median 3Q Max\n-1.177 -1.166 -1.156 1.188 1.199\n\nCoefficients:\nEstimate Std. Error z value Pr(>|z|)\n(Intercept) 0.03254 0.11913 0.273 0.785\nx3 -0.01674 0.03288 -0.509 0.611\n\n(Dispersion parameter for binomial family taken to be 1)\n\nNull deviance: 6930.6 on 4999 degrees of freedom\nResidual deviance: 6930.3 on 4998 degrees of freedom\nAIC: 6934.3\n\nNumber of Fisher Scoring iterations: 3\n\n> confint(Model3)\nWaiting for profiling to be done...\n2.5 % 97.5 %\n(Intercept) -0.20096508 0.2660569\nx3 -0.08119495 0.0476911"
}
] |
Computer Networks | Set 13 - GeeksforGeeks
|
25 Feb, 2019
These questions for practice purpose for GATE CS Exam.
Ques-1: How many bits are allocated for network id (NID) and host id(HID) in the IP address 25.193.155.233?
(A) 24 bit for NID, 8 bits for HID(B) 8 bit for NID, 24 bits for HID(C) 16 bit for NID, 16 bits for HID(D) none
Explanation:It is class A IP address and you know, that class A has 24 bits in HID and 8 bits in NID part.
So, option (B) is correct.
Ques-2: The bandwidth of the line is 1.5 Mbps with round trip time(RTT) as 45 milliseconds.If the size of each packet is 1 KB(kilobytes), then what is the efficiency in Stop and wait protocol?
(A) 20.3(B) 10.0(C) 10.8(D) 11
Explanation:So in order to find the efficiency, lets first calculate the propagation delay (p) and transmission delay(t). You know that,
(2*p) = RTT = 45 ms
Therefore,
p = 45/2 = 22.5 ms
Now, lets find transmission delay (t), you know that, t = L/B (where, L= size of packet and B= bandwidth). Therefore,
L = 1KB = (1024*8) = 8192 bits
And
B = (1.5*106)
So,
t = L/B = 8192/(1.5*106) = 5.461 ms
Thus efficiency,
= 1/(1 + 2a) {where a = p/t = 22.5/5.461 = 4.12}
= 1/(1 + 2*4.12)
= 0.108
= 10.8 %
So, option (C) is correct.
Ques-3: A 1 km long broadcast LAN has bandwidth (BW) of 107 bps and uses CSMA/CD, then what is the minimum size of the packet?Given:
velocity(v) = 2*108 m/sec
(A) 200 bits(B) 10(C) 50(D) 100
Explanation:Here,
Distance(d) = 1 km = 1*103 meter,
and BW = 107 bps
So,
p = propagation delay
= (d/v) = (103/2*108) = 5*10(-6)
Therefore, minimum size of the packet is,
= (2*p*BW)
= 2*5*10(-6)*107
= 100 bits
So, option (D) is correct.
Ques-4: Consider Subnet mask of class B network on the internet is 255.255.240.0 then, what is the maximum number of hosts per subnets?
(A) 4098(B) 4096(C) 4094(D) 4092
Explanation:To find number of hosts per Subnet, you need to check number of zeroes in the host id part.Here, Subnet mask
= 255.255.240.0
= 11111111.11111111.11110000.00000000
Therefore, number of zeroes is 12 so,
Number of hosts
= (212 - 2)
= 4096 - 2
= 4094
Since, one of them is used for network id of entire network and the other one is used for the directed broadcast address of the network so, two is subtracted.
So, option (C) is correct.
Ques-5: What is the maximum window size for data transmission Using Selective Repeat protocol with n-bit frame sequence number?
(A) 2n(B) 2n-1(C) 2n-2(D) 2n-1
Explanation:Since, window size of sender(W) = window size of the receiver(R) and we know that,
(W + R) = 2n
or, (W + W) = 2n since, (W = R)
or, 2*W = 2n
or, W = 2n-1
Hence, option (D) is correct.
Computer Networks Quiz
GATE
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Computer Networks | IP Addressing | Question 8
Computer Networks | IP Addressing | Question 8
Message encryption and decryption using UDP server
Computer Networks | IP Addressing | Question 2
Computer Networks | Network Layer | Question 2
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2008 | Question 66
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
|
[
{
"code": null,
"e": 23477,
"s": 23449,
"text": "\n25 Feb, 2019"
},
{
"code": null,
"e": 23532,
"s": 23477,
"text": "These questions for practice purpose for GATE CS Exam."
},
{
"code": null,
"e": 23640,
"s": 23532,
"text": "Ques-1: How many bits are allocated for network id (NID) and host id(HID) in the IP address 25.193.155.233?"
},
{
"code": null,
"e": 23752,
"s": 23640,
"text": "(A) 24 bit for NID, 8 bits for HID(B) 8 bit for NID, 24 bits for HID(C) 16 bit for NID, 16 bits for HID(D) none"
},
{
"code": null,
"e": 23859,
"s": 23752,
"text": "Explanation:It is class A IP address and you know, that class A has 24 bits in HID and 8 bits in NID part."
},
{
"code": null,
"e": 23886,
"s": 23859,
"text": "So, option (B) is correct."
},
{
"code": null,
"e": 24079,
"s": 23886,
"text": "Ques-2: The bandwidth of the line is 1.5 Mbps with round trip time(RTT) as 45 milliseconds.If the size of each packet is 1 KB(kilobytes), then what is the efficiency in Stop and wait protocol?"
},
{
"code": null,
"e": 24110,
"s": 24079,
"text": "(A) 20.3(B) 10.0(C) 10.8(D) 11"
},
{
"code": null,
"e": 24247,
"s": 24110,
"text": "Explanation:So in order to find the efficiency, lets first calculate the propagation delay (p) and transmission delay(t). You know that,"
},
{
"code": null,
"e": 24268,
"s": 24247,
"text": "(2*p) = RTT = 45 ms "
},
{
"code": null,
"e": 24279,
"s": 24268,
"text": "Therefore,"
},
{
"code": null,
"e": 24299,
"s": 24279,
"text": "p = 45/2 = 22.5 ms "
},
{
"code": null,
"e": 24417,
"s": 24299,
"text": "Now, lets find transmission delay (t), you know that, t = L/B (where, L= size of packet and B= bandwidth). Therefore,"
},
{
"code": null,
"e": 24511,
"s": 24417,
"text": "L = 1KB = (1024*8) = 8192 bits\n\nAnd \nB = (1.5*106)\n\nSo, \nt = L/B = 8192/(1.5*106) = 5.461 ms "
},
{
"code": null,
"e": 24528,
"s": 24511,
"text": "Thus efficiency,"
},
{
"code": null,
"e": 24613,
"s": 24528,
"text": "= 1/(1 + 2a) {where a = p/t = 22.5/5.461 = 4.12}\n= 1/(1 + 2*4.12)\n= 0.108 \n= 10.8 % "
},
{
"code": null,
"e": 24640,
"s": 24613,
"text": "So, option (C) is correct."
},
{
"code": null,
"e": 24773,
"s": 24640,
"text": "Ques-3: A 1 km long broadcast LAN has bandwidth (BW) of 107 bps and uses CSMA/CD, then what is the minimum size of the packet?Given:"
},
{
"code": null,
"e": 24800,
"s": 24773,
"text": "velocity(v) = 2*108 m/sec "
},
{
"code": null,
"e": 24832,
"s": 24800,
"text": "(A) 200 bits(B) 10(C) 50(D) 100"
},
{
"code": null,
"e": 24850,
"s": 24832,
"text": "Explanation:Here,"
},
{
"code": null,
"e": 24963,
"s": 24850,
"text": "Distance(d) = 1 km = 1*103 meter, \nand BW = 107 bps\n\nSo,\np = propagation delay\n= (d/v) = (103/2*108) = 5*10(-6) "
},
{
"code": null,
"e": 25005,
"s": 24963,
"text": "Therefore, minimum size of the packet is,"
},
{
"code": null,
"e": 25045,
"s": 25005,
"text": "= (2*p*BW)\n= 2*5*10(-6)*107\n= 100 bits "
},
{
"code": null,
"e": 25072,
"s": 25045,
"text": "So, option (D) is correct."
},
{
"code": null,
"e": 25208,
"s": 25072,
"text": "Ques-4: Consider Subnet mask of class B network on the internet is 255.255.240.0 then, what is the maximum number of hosts per subnets?"
},
{
"code": null,
"e": 25241,
"s": 25208,
"text": "(A) 4098(B) 4096(C) 4094(D) 4092"
},
{
"code": null,
"e": 25362,
"s": 25241,
"text": "Explanation:To find number of hosts per Subnet, you need to check number of zeroes in the host id part.Here, Subnet mask"
},
{
"code": null,
"e": 25417,
"s": 25362,
"text": "= 255.255.240.0\n= 11111111.11111111.11110000.00000000 "
},
{
"code": null,
"e": 25455,
"s": 25417,
"text": "Therefore, number of zeroes is 12 so,"
},
{
"code": null,
"e": 25503,
"s": 25455,
"text": "Number of hosts\n= (212 - 2) \n= 4096 - 2\n= 4094 "
},
{
"code": null,
"e": 25662,
"s": 25503,
"text": "Since, one of them is used for network id of entire network and the other one is used for the directed broadcast address of the network so, two is subtracted."
},
{
"code": null,
"e": 25689,
"s": 25662,
"text": "So, option (C) is correct."
},
{
"code": null,
"e": 25817,
"s": 25689,
"text": "Ques-5: What is the maximum window size for data transmission Using Selective Repeat protocol with n-bit frame sequence number?"
},
{
"code": null,
"e": 25848,
"s": 25817,
"text": "(A) 2n(B) 2n-1(C) 2n-2(D) 2n-1"
},
{
"code": null,
"e": 25943,
"s": 25848,
"text": "Explanation:Since, window size of sender(W) = window size of the receiver(R) and we know that,"
},
{
"code": null,
"e": 26015,
"s": 25943,
"text": "(W + R) = 2n\nor, (W + W) = 2n since, (W = R)\nor, 2*W = 2n\nor, W = 2n-1 "
},
{
"code": null,
"e": 26045,
"s": 26015,
"text": "Hence, option (D) is correct."
},
{
"code": null,
"e": 26068,
"s": 26045,
"text": "Computer Networks Quiz"
},
{
"code": null,
"e": 26073,
"s": 26068,
"text": "GATE"
},
{
"code": null,
"e": 26081,
"s": 26073,
"text": "GATE CS"
},
{
"code": null,
"e": 26179,
"s": 26081,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26188,
"s": 26179,
"text": "Comments"
},
{
"code": null,
"e": 26201,
"s": 26188,
"text": "Old Comments"
},
{
"code": null,
"e": 26248,
"s": 26201,
"text": "Computer Networks | IP Addressing | Question 8"
},
{
"code": null,
"e": 26295,
"s": 26248,
"text": "Computer Networks | IP Addressing | Question 8"
},
{
"code": null,
"e": 26346,
"s": 26295,
"text": "Message encryption and decryption using UDP server"
},
{
"code": null,
"e": 26393,
"s": 26346,
"text": "Computer Networks | IP Addressing | Question 2"
},
{
"code": null,
"e": 26440,
"s": 26393,
"text": "Computer Networks | Network Layer | Question 2"
},
{
"code": null,
"e": 26482,
"s": 26440,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26516,
"s": 26482,
"text": "GATE | GATE CS 2008 | Question 66"
},
{
"code": null,
"e": 26558,
"s": 26516,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 26592,
"s": 26558,
"text": "GATE | GATE-CS-2001 | Question 23"
}
] |
Generating any custom JSON in ABAP
|
You can use class ZCL_MDP_JSON Library that can encode/parse any JSON. JSON is supported natively in ABAP by the following features:
With the use of JSON-XML- it is known as special XML format that can be used for JSON data to be described using an XML representation.
By defining a mapping between ABAP types and JSON. This is used in serializations and deserializations using the identity transformation ID.
As you can specify JSON data in different forms as an XML source in the statement CALL TRANSFORMATION and JSON can be specified as a target.
Check out the following sample code:
Example:
DATA text TYPE string VALUE `Hi JSON, ABAP here!`.
DATA writer TYPE REF TO cl_sxml_string_writer.
DATA json TYPE xstring.
“ABAP to JSON
writer =cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE text = text
RESULT XML writer.
json = writer->get_output( ).
“JSON to ABAP
text =`{“TEXT”:”Hi ABAP, JSON here!”}`.
CALL TRANSFORMATION id SOURCE XML text
RESULT text = text.
JSON/ABAP Serializer and Deserializer
In SAP ERP7.40, you have a simple transformation that can be used to convert ABAP to JSON and JSON to ABAP. This is most suitable when you require maximum performance and not worried about using Serializer and de-serializer.
You can also refer to the below link:
https://wiki.scn.sap.com/wiki/display/Snippets/One+more+ABAP+to+JSON+Serializer+and+Deserializer
ABAP to JSON usage example:
DATA: lt_flight TYPE STANDARD TABLE OF sflight,
lrf_descr TYPE REF TO cl_abap_typedescr,
lv_json TYPE string.
SELECT * FROM sflight INTO TABLE lt_flight.
* serialize table lt_flight into JSON, skipping initial fields and converting ABAP field names into camelCase
lv_json =/ui2/cl_json=>serialize( data = lt_flight compress = abap_true pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).
WRITE / lv_json.
CLEAR lt_flight.
* deserialize JSON string json into internal table lt_flight doing camelCase to ABAP like field name mapping
/ui2/cl_json=>deserialize(EXPORTING json = lv_json pretty_name =/ui2/cl_json=>pretty_mode-camel_case CHANGING data = lt_flight ).
* serialize ABAP object into JSON string
lrf_descr = cl_abap_typedescr=>describe_by_data( lt_flight ).
lv_json =/ui2/cl_json=>serialize( lrf_descr ).
WRITE / lv_json.
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "You can use class ZCL_MDP_JSON Library that can encode/parse any JSON. JSON is supported natively in ABAP by the following features:"
},
{
"code": null,
"e": 1332,
"s": 1195,
"text": "With the use of JSON-XML- it is known as special XML format that can be used for JSON data to be described using an XML representation. "
},
{
"code": null,
"e": 1473,
"s": 1332,
"text": "By defining a mapping between ABAP types and JSON. This is used in serializations and deserializations using the identity transformation ID."
},
{
"code": null,
"e": 1614,
"s": 1473,
"text": "As you can specify JSON data in different forms as an XML source in the statement CALL TRANSFORMATION and JSON can be specified as a target."
},
{
"code": null,
"e": 1651,
"s": 1614,
"text": "Check out the following sample code:"
},
{
"code": null,
"e": 1660,
"s": 1651,
"text": "Example:"
},
{
"code": null,
"e": 2075,
"s": 1660,
"text": "DATA text TYPE string VALUE `Hi JSON, ABAP here!`.\nDATA writer TYPE REF TO cl_sxml_string_writer.\nDATA json TYPE xstring.\n“ABAP to JSON\nwriter =cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).\nCALL TRANSFORMATION id SOURCE text = text\n RESULT XML writer.\njson = writer->get_output( ).\n“JSON to ABAP\ntext =`{“TEXT”:”Hi ABAP, JSON here!”}`.\nCALL TRANSFORMATION id SOURCE XML text\n RESULT text = text."
},
{
"code": null,
"e": 2113,
"s": 2075,
"text": "JSON/ABAP Serializer and Deserializer"
},
{
"code": null,
"e": 2338,
"s": 2113,
"text": "In SAP ERP7.40, you have a simple transformation that can be used to convert ABAP to JSON and JSON to ABAP. This is most suitable when you require maximum performance and not worried about using Serializer and de-serializer."
},
{
"code": null,
"e": 2377,
"s": 2338,
"text": "You can also refer to the below link: "
},
{
"code": null,
"e": 2474,
"s": 2377,
"text": "https://wiki.scn.sap.com/wiki/display/Snippets/One+more+ABAP+to+JSON+Serializer+and+Deserializer"
},
{
"code": null,
"e": 2502,
"s": 2474,
"text": "ABAP to JSON usage example:"
},
{
"code": null,
"e": 3342,
"s": 2502,
"text": "DATA: lt_flight TYPE STANDARD TABLE OF sflight,\n lrf_descr TYPE REF TO cl_abap_typedescr,\n lv_json TYPE string.\nSELECT * FROM sflight INTO TABLE lt_flight.\n\n* serialize table lt_flight into JSON, skipping initial fields and converting ABAP field names into camelCase\nlv_json =/ui2/cl_json=>serialize( data = lt_flight compress = abap_true pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).\nWRITE / lv_json.\nCLEAR lt_flight.\n\n* deserialize JSON string json into internal table lt_flight doing camelCase to ABAP like field name mapping\n/ui2/cl_json=>deserialize(EXPORTING json = lv_json pretty_name =/ui2/cl_json=>pretty_mode-camel_case CHANGING data = lt_flight ).\n\n* serialize ABAP object into JSON string\nlrf_descr = cl_abap_typedescr=>describe_by_data( lt_flight ).\nlv_json =/ui2/cl_json=>serialize( lrf_descr ).\nWRITE / lv_json."
}
] |
rand package in Golang - GeeksforGeeks
|
08 Jun, 2020
Go language provides inbuilt support for generating random numbers of the specified type with the help of a math/rand package. This package implements pseudo-random number generators. These random numbers are generated by a source and this source produces a deterministic sequence of values every time when the program run. And if you want to random numbers for security-sensitive work, then use the crypto/rand package.
Note: In this package, the mathematical interval notation such as [0, n) is used.
type Rand
type Source
type Zipf
Example 1:
// Golang program to illustrate // how to Get Intn Type Random // Number package main import ( "fmt" "math/rand") // Main function func main() { // Finding random numbers of int type // Using Intn() function res_1 := rand.Intn(7) res_2 := rand.Intn(8) res_3 := rand.Intn(2) // Displaying the result fmt.Println("Random Number 1: ", res_1) fmt.Println("Random Number 2: ", res_2) fmt.Println("Random Number 3: ", res_3) }
Output:
Random Number 1: 6
Random Number 2: 7
Random Number 3: 1
Example 2:
// Golang program to illustrate // how to get a random number package main import ( "fmt" "math/rand") // Main function func main() { // Finding random numbers of int type // Using Int31() function res_1 := rand.Int31() res_2 := rand.Int31() res_3 := rand.Int31() // Displaying the result fmt.Println("Random Number 1: ", res_1) fmt.Println("Random Number 2: ", res_2) fmt.Println("Random Number 3: ", res_3) }
Output:
Random Number 1: 1298498081
Random Number 2: 2019727887
Random Number 3: 1427131847
Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
|
[
{
"code": null,
"e": 24069,
"s": 24041,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 24490,
"s": 24069,
"text": "Go language provides inbuilt support for generating random numbers of the specified type with the help of a math/rand package. This package implements pseudo-random number generators. These random numbers are generated by a source and this source produces a deterministic sequence of values every time when the program run. And if you want to random numbers for security-sensitive work, then use the crypto/rand package."
},
{
"code": null,
"e": 24572,
"s": 24490,
"text": "Note: In this package, the mathematical interval notation such as [0, n) is used."
},
{
"code": null,
"e": 24582,
"s": 24572,
"text": "type Rand"
},
{
"code": null,
"e": 24594,
"s": 24582,
"text": "type Source"
},
{
"code": null,
"e": 24604,
"s": 24594,
"text": "type Zipf"
},
{
"code": null,
"e": 24615,
"s": 24604,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate // how to Get Intn Type Random // Number package main import ( \"fmt\" \"math/rand\") // Main function func main() { // Finding random numbers of int type // Using Intn() function res_1 := rand.Intn(7) res_2 := rand.Intn(8) res_3 := rand.Intn(2) // Displaying the result fmt.Println(\"Random Number 1: \", res_1) fmt.Println(\"Random Number 2: \", res_2) fmt.Println(\"Random Number 3: \", res_3) } ",
"e": 25101,
"s": 24615,
"text": null
},
{
"code": null,
"e": 25109,
"s": 25101,
"text": "Output:"
},
{
"code": null,
"e": 25170,
"s": 25109,
"text": "Random Number 1: 6\nRandom Number 2: 7\nRandom Number 3: 1\n"
},
{
"code": null,
"e": 25181,
"s": 25170,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate // how to get a random number package main import ( \"fmt\" \"math/rand\") // Main function func main() { // Finding random numbers of int type // Using Int31() function res_1 := rand.Int31() res_2 := rand.Int31() res_3 := rand.Int31() // Displaying the result fmt.Println(\"Random Number 1: \", res_1) fmt.Println(\"Random Number 2: \", res_2) fmt.Println(\"Random Number 3: \", res_3) } ",
"e": 25648,
"s": 25181,
"text": null
},
{
"code": null,
"e": 25656,
"s": 25648,
"text": "Output:"
},
{
"code": null,
"e": 25744,
"s": 25656,
"text": "Random Number 1: 1298498081\nRandom Number 2: 2019727887\nRandom Number 3: 1427131847\n"
},
{
"code": null,
"e": 25756,
"s": 25744,
"text": "Golang-Math"
},
{
"code": null,
"e": 25768,
"s": 25756,
"text": "Go Language"
},
{
"code": null,
"e": 25866,
"s": 25768,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25875,
"s": 25866,
"text": "Comments"
},
{
"code": null,
"e": 25888,
"s": 25875,
"text": "Old Comments"
},
{
"code": null,
"e": 25917,
"s": 25888,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 25941,
"s": 25917,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 25956,
"s": 25941,
"text": "Rune in Golang"
},
{
"code": null,
"e": 25990,
"s": 25956,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 26011,
"s": 25990,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 26038,
"s": 26011,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 26063,
"s": 26038,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 26084,
"s": 26063,
"text": "Structures in Golang"
},
{
"code": null,
"e": 26102,
"s": 26084,
"text": "Strings in Golang"
}
] |
Python program to sort a list of tuples alphabetically
|
When it is required to sort a list of tuples in alphabetical order, the 'sort' method can be used. When using this, the contents of the original tuple get changed, since in-place sorting is performed.
The 'sort' function sorts the values in ascending order by default. If the order of sorting is specified as descending, it is sorted in descending order.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration of the same −
Live Demo
def sort_tuple_vals(my_tup):
my_tup.sort(key = lambda x: x[0])
return my_tup
my_tup = [("Hey", 18), ("Jane", 33), ("Will", 56),("Nysa", 35), ("May", "Pink")]
print("The tuple is ")
print(my_tup)
print("After sorting the tuple alphabetically, it becomes : ")
print(sort_tuple_vals(my_tup))
The tuple is
[('Hey', 18), ('Jane', 33), ('Will', 56), ('Nysa', 35), ('May', 'Pink')]
After sorting the tuple alphabetically, it becomes :
[('Hey', 18), ('Jane', 33), ('May', 'Pink'), ('Nysa', 35), ('Will', 56)]
A function named 'sort_tuple_vals' is defined, that takes a tuple as a parameter.
It uses the sort method and the lambda function to sort the elements in the tuple.
This is returned when the function is called.
Now the tuple is defined, and the function is called by passing this tuple as the parameter.
The output is displayed on the console.
|
[
{
"code": null,
"e": 1263,
"s": 1062,
"text": "When it is required to sort a list of tuples in alphabetical order, the 'sort' method can be used. When using this, the contents of the original tuple get changed, since in-place sorting is performed."
},
{
"code": null,
"e": 1417,
"s": 1263,
"text": "The 'sort' function sorts the values in ascending order by default. If the order of sorting is specified as descending, it is sorted in descending order."
},
{
"code": null,
"e": 1544,
"s": 1417,
"text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)."
},
{
"code": null,
"e": 1606,
"s": 1544,
"text": "A list of tuple basically contains tuples enclosed in a list."
},
{
"code": null,
"e": 1645,
"s": 1606,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1655,
"s": 1645,
"text": "Live Demo"
},
{
"code": null,
"e": 1958,
"s": 1655,
"text": "def sort_tuple_vals(my_tup): \n my_tup.sort(key = lambda x: x[0])\n return my_tup\nmy_tup = [(\"Hey\", 18), (\"Jane\", 33), (\"Will\", 56),(\"Nysa\", 35), (\"May\", \"Pink\")]\n \nprint(\"The tuple is \")\nprint(my_tup)\nprint(\"After sorting the tuple alphabetically, it becomes : \")\nprint(sort_tuple_vals(my_tup))"
},
{
"code": null,
"e": 2170,
"s": 1958,
"text": "The tuple is\n[('Hey', 18), ('Jane', 33), ('Will', 56), ('Nysa', 35), ('May', 'Pink')]\nAfter sorting the tuple alphabetically, it becomes :\n[('Hey', 18), ('Jane', 33), ('May', 'Pink'), ('Nysa', 35), ('Will', 56)]"
},
{
"code": null,
"e": 2252,
"s": 2170,
"text": "A function named 'sort_tuple_vals' is defined, that takes a tuple as a parameter."
},
{
"code": null,
"e": 2335,
"s": 2252,
"text": "It uses the sort method and the lambda function to sort the elements in the tuple."
},
{
"code": null,
"e": 2381,
"s": 2335,
"text": "This is returned when the function is called."
},
{
"code": null,
"e": 2474,
"s": 2381,
"text": "Now the tuple is defined, and the function is called by passing this tuple as the parameter."
},
{
"code": null,
"e": 2514,
"s": 2474,
"text": "The output is displayed on the console."
}
] |
PySpark Sentiment Analysis on Google Dataproc | by Ricky Kim | Towards Data Science
|
I recently had a chance to play around with Google Cloud Platform through a specialization course on Coursera; Data Engineering on Google Cloud Platform Specialization. Overall I learned a lot through the courses, and it was such a good opportunity to try various services of Google Cloud Platform(GCP) for free while going through the assignments. Even though I’m not using any of GCP’s services at work at the moment, if I have a chance I’d be happy to migrate some parts of my data works to GCP.
However, one thing that the course lacks is room for your own creativity. The assignments of the course were more like tutorials than assignments. You basically follow along already written codes. Of course, you can still learn a lot by trying to read every single line of codes and understand what each line does in detail. Still, without applying what you have learned in your own problem-solving, it is difficult to make this knowledge completely yours. That’s also what the instructor Lak Lakshmanan advised at the end of the course. (Shout out to Lak Lakshmanan, thank you for the great courses!)
*In addition to short code blocks I will attach, you can find the link for the whole Git Repository at the end of this post.
Homebrew (https://brew.sh/)
Git (https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
So I have decided to do some personal mini projects making use of various GCP services. Luckily, if you haven’t tried GCP yet, Google generously offers a free trial which gives you $300 credit you can use over 12 months.
The first project I tried is Spark sentiment analysis model training on Google Dataproc. There are a couple of reasons why I chose it as my first project on GCP. I already wrote about PySpark sentiment analysis in one of my previous posts, which means I can use it as a starting point and easily make this a standalone Python program. The other reason is I just wanted to try Google Dataproc! I was fascinated by how easy and fast it is to spin up a cluster on GCP and couldn’t help myself from trying it outside the Coursera course.
If you have clicked “TRY GCP FREE”, and fill in information such as your billing account (Even though you set up a billing account, you won’t be charged unless you upgrade to a paid account), you will be directed to a page looks like below.
On the top menu bar, you can see “My First Project” next to Google Cloud Platform. In GCP, “project” is the base-level entity to use GCP services, enable billing, etc. On the first login, you can see that Google automatically created a “project” called “My First Project” for you. Click on it to see ID of the current project, copy it or write it down, this will be used later. By clicking into “Billing” on the left-side menu from the web console home screen, “My First Project” is automatically linked to the free credit you received.
In GCP, there are many different services; Compute Engine, Cloud Storage, BigQuery, Cloud SQL, Cloud Dataproc to name a few. In order to use any of these services in your project, you first have to enable them.
Put your mouse over “APIs & Services” on the left-side menu, then click into “Library”. For this project, we will enable three APIs: Cloud Dataproc, Compute Engine, and Cloud Storage.
In the API Library page, search the above mentioned three APIs one by one by typing the name in the search box. Clicking into the search result, and enable the API by clicking “ENABLE” button on the screen.
When I tried it myself, I only had to enable Cloud Dataproc API, since the other two (Compute Engine, Cloud Storage) were already enabled when I clicked into them. But if that’s not the case for you, please enable Compute Engine API, Cloud Storage API.
If this is your very first time to try GCP, you first might want to install the Google Cloud SDK so that you can interact with many services of GCP from the command-line. You can find more information on how to install from here.
By following instructions from the link, you will be prompted to log in (use the Google account you used to start the free trial), then to select a project and compute zone (project: choose the project you enable the APIs from the above steps if there are more than one, compute zone: To decrease network latency, you might want to choose a zone that is close to you. You can check the physical locations of each zone from here.).
Since you have installed Google Cloud SDK, you can either create a bucket from the command-line or from the web console.
Click into “Storage” from left-side menu, then you’ll see a page like the above. Click “Create bucket”
For convenience, enter project ID you checked at the end of “Creating a Free Trial Account on GCP” stage. You can just click “create” without changing any other details, or choose the same location as your project.
Replace your_project_id with the project ID that you copied and run the below line on your terminal to set BUCKET_NAME variable to your project ID and make it available to sub-processes. (A Bash script you need to run later will make use of this)
export PROJECT_ID='your_project_id'
Then create a bucket by running gsutil mb command as below.
gsutil mb gs://${PROJECT_ID}
The above command will create a bucket with the default settings. If you want to create a bucket in a specific region or multi-region, you can give it -l option to specify the region. You can see available bucket locations from here.
#ex1) multi-region europegsutil mb -l eu gs://${PROJECT_ID}#ex)2 region europe-west1gsutil mb -l europe-west1 gs://${PROJECT_ID}
Now clone the git repository I uploaded by running below command in terminal.
git clone https://github.com/tthustla/pyspark_sa_gcp.git
Once you clone the repository, it will create a folder named pyspark_sa_gcp. Go into the folder and check what files are there.
cd pyspark_sa_gcp/ls
You will see three files in the directory: data_prep.sh, pyspark_sa.py, train_test_split.py. In order to download the training data and prepare for training let’s run the Bash script data_prep.sh. Below is the content of the script and I have added comments to explain what each line does.
The original dataset for training is “Sentiment140”, which originated from Stanford University. The Dataset has 1.6million labelled tweets.50% of the data is with negative labels and the other 50% with positive labels. More info on the dataset can be found from the link. http://help.sentiment140.com/for-students/
In the above Bash script, you can see it’s calling a Python script train_test_split.py. Let’s also take a look at what it does.
Now we can run the Bash script to prepare the data. Once it’s finished, it will have uploaded prepared data to the cloud storage bucket you created earlier. It will take 5~6 mins to upload the data.
./data_prep.sh
Go to the Storage from the left side menu and click into your bucket -> pyspark_nlp -> data. You will see two files are uploaded.
Or you can also check the content of your bucket from your terminal by running below command.
gsutil ls -r gs://${PROJECT_ID}/**
Cloud Dataproc is a Google cloud service for running Apache Spark and Apache Hadoop clusters. I have to say it is ridiculously simple and easy-to-use and it only takes a couple of minutes to spin up a cluster with Google Dataproc. Also, Google Dataproc offers autoscaling if you need, and you can adjust the cluster at any time, even when jobs are running on the cluster.
Go to Dataproc from the left side menu (you have to scroll down a bit. It’s under Big Data section) and click on “Clusters”. Click “Create clusters”, then you’ll see a page like below.
Give it a name (for convenience, I gave the project ID as its name), choose Region and Zone. To decrease the latency, it is a good idea to set the region to be the same as your bucket region. Here you need to change the default settings for worker nodes a little, as the free trial only gives you permission to run up to 8 cores. The default setting for a cluster is one master and two workers all with 4 CPUs each, which will exceed the 8 cores quota. So change the setting for your worker nodes to 2 CPUs, then click create at the bottom. After a couple of minutes of provisioning, you will see the cluster created with one master node (4 CPUs, 15GB memory, 500GB standard persistent disk) and two worker nodes (2 CPUs, 15GB memory, 500GB standard persistent disk each).
Since we need to change the default setting a little bit, we need to add one more argument to the command, but it’s simple enough. Let’s create a cluster and give it the same name as the project ID, and set worker nodes to have 2 CPUs each.
gcloud dataproc clusters create ${PROJECT_ID} \--project=${PROJECT_ID} \--worker-machine-type='n1-standard-2' \--zone='europe-west1-b'
You can change the zone to be close to your bucket region.
Finally, we are ready to run the training on Google Dataproc. The Python script (pyspark_sa.py) for the training is included in the Git repository you cloned earlier. Since I commented on the script to explain what each line does, I will not go through the code. The code is a slightly refactored version of what I have done in Jupyter Notebook for my previous post. Below are a few of my previous posts, in case you want to know more in detail about PySpark or NLP feature extraction.
Sentiment Analysis with PySpark
Another Twitter Sentiment Analysis with Python-Part 4 (Count Vectorizer, Confusion Matrix)
Another Twitter Sentiment Analysis with Python-Part 5(TFIDF Vectorizer)
And let’s take a look at what the Python script looks like.
Since I commented inside the script to explain what each line does, I will not go through the code extensively. But in a nutshell, the above script will take three command line arguments: Cloud Storage location where the training and test data are stored, a Cloud storage directory to store prediction result of the test data, and finally a Cloud storage directory to store the trained model. When called, it will first do the preprocessing of the training data -> build a pipeline -> fit the pipeline -> and make predictions on the test data -> print the accuracy of the predictions -> save prediction result as CSV -> save fitted pipeline model -> load the saved model -> print the accuracy again on the test data (to see if the model is properly saved).
In order to run this job through the web console, we need to first upload the Python script to our cloud storage so that we can point the job to read the script. Let’s upload the script by running below command. (I’m assuming that you are still on pyspark_sa_gcp directory on your terminal)
gsutil cp pyspark_sa.py gs://${PROJECT_ID}/pyspark_nlp/
Now click into Dataproc on the web console, and click “Jobs” then click “SUBMIT JOB”.
From the above screenshot replace the blurred parts of the texts to your project ID, then click “submit” at the bottom. You can inspect the output of the machine by clicking into the job.
The job is finished after 15 minutes, and by looking at the output, it seems like the cluster struggled a bit, but nonetheless, the prediction looks fine and the model seems to be saved properly.
If you submit a job from the command-line, you don’t even need to upload your script to Cloud Storage. It will be able to grab a local file and move to the Dataproc cluster to execute. (Again I’m assuming that you are still on pyspark_sa_gcp directory on your terminal)
gcloud dataproc jobs submit pyspark pyspark_sa.py \--cluster=${PROJECT_ID} \-- gs://${PROJECT_ID}/pyspark_nlp/data/ gs://${PROJECT_ID}/pyspark_nlp/result gs://${PROJECT_ID}/pyspark_nlp/model
Again the cluster seemed to struggle a bit, but still got the result and model saved properly. (I have tried to submit the same job on my paid account with 4 CPUs worker nodes, then it didn’t throw any warnings)
Go to your bucket, then go into pyspark_nlp folder. You will see that the results of the above Spark job have been saved into “result” directory (for the prediction data frame), and “model” directory (fitted pipeline model).
Finally, don’t forget to delete the Dataproc cluster you have created to ensure it will not use up any more of your credit.
Through this post, I went through how to train Spark ML model on Google Dataproc and save the trained model for later use. What I showed here is only a small part of what GCP is capable of and I encourage you to explore other services on GCP and play around with it.
Thank you for reading. You can find the Git Repository of the scripts from the below link.
|
[
{
"code": null,
"e": 671,
"s": 172,
"text": "I recently had a chance to play around with Google Cloud Platform through a specialization course on Coursera; Data Engineering on Google Cloud Platform Specialization. Overall I learned a lot through the courses, and it was such a good opportunity to try various services of Google Cloud Platform(GCP) for free while going through the assignments. Even though I’m not using any of GCP’s services at work at the moment, if I have a chance I’d be happy to migrate some parts of my data works to GCP."
},
{
"code": null,
"e": 1273,
"s": 671,
"text": "However, one thing that the course lacks is room for your own creativity. The assignments of the course were more like tutorials than assignments. You basically follow along already written codes. Of course, you can still learn a lot by trying to read every single line of codes and understand what each line does in detail. Still, without applying what you have learned in your own problem-solving, it is difficult to make this knowledge completely yours. That’s also what the instructor Lak Lakshmanan advised at the end of the course. (Shout out to Lak Lakshmanan, thank you for the great courses!)"
},
{
"code": null,
"e": 1398,
"s": 1273,
"text": "*In addition to short code blocks I will attach, you can find the link for the whole Git Repository at the end of this post."
},
{
"code": null,
"e": 1426,
"s": 1398,
"text": "Homebrew (https://brew.sh/)"
},
{
"code": null,
"e": 1494,
"s": 1426,
"text": "Git (https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)"
},
{
"code": null,
"e": 1715,
"s": 1494,
"text": "So I have decided to do some personal mini projects making use of various GCP services. Luckily, if you haven’t tried GCP yet, Google generously offers a free trial which gives you $300 credit you can use over 12 months."
},
{
"code": null,
"e": 2249,
"s": 1715,
"text": "The first project I tried is Spark sentiment analysis model training on Google Dataproc. There are a couple of reasons why I chose it as my first project on GCP. I already wrote about PySpark sentiment analysis in one of my previous posts, which means I can use it as a starting point and easily make this a standalone Python program. The other reason is I just wanted to try Google Dataproc! I was fascinated by how easy and fast it is to spin up a cluster on GCP and couldn’t help myself from trying it outside the Coursera course."
},
{
"code": null,
"e": 2490,
"s": 2249,
"text": "If you have clicked “TRY GCP FREE”, and fill in information such as your billing account (Even though you set up a billing account, you won’t be charged unless you upgrade to a paid account), you will be directed to a page looks like below."
},
{
"code": null,
"e": 3027,
"s": 2490,
"text": "On the top menu bar, you can see “My First Project” next to Google Cloud Platform. In GCP, “project” is the base-level entity to use GCP services, enable billing, etc. On the first login, you can see that Google automatically created a “project” called “My First Project” for you. Click on it to see ID of the current project, copy it or write it down, this will be used later. By clicking into “Billing” on the left-side menu from the web console home screen, “My First Project” is automatically linked to the free credit you received."
},
{
"code": null,
"e": 3238,
"s": 3027,
"text": "In GCP, there are many different services; Compute Engine, Cloud Storage, BigQuery, Cloud SQL, Cloud Dataproc to name a few. In order to use any of these services in your project, you first have to enable them."
},
{
"code": null,
"e": 3422,
"s": 3238,
"text": "Put your mouse over “APIs & Services” on the left-side menu, then click into “Library”. For this project, we will enable three APIs: Cloud Dataproc, Compute Engine, and Cloud Storage."
},
{
"code": null,
"e": 3629,
"s": 3422,
"text": "In the API Library page, search the above mentioned three APIs one by one by typing the name in the search box. Clicking into the search result, and enable the API by clicking “ENABLE” button on the screen."
},
{
"code": null,
"e": 3882,
"s": 3629,
"text": "When I tried it myself, I only had to enable Cloud Dataproc API, since the other two (Compute Engine, Cloud Storage) were already enabled when I clicked into them. But if that’s not the case for you, please enable Compute Engine API, Cloud Storage API."
},
{
"code": null,
"e": 4112,
"s": 3882,
"text": "If this is your very first time to try GCP, you first might want to install the Google Cloud SDK so that you can interact with many services of GCP from the command-line. You can find more information on how to install from here."
},
{
"code": null,
"e": 4543,
"s": 4112,
"text": "By following instructions from the link, you will be prompted to log in (use the Google account you used to start the free trial), then to select a project and compute zone (project: choose the project you enable the APIs from the above steps if there are more than one, compute zone: To decrease network latency, you might want to choose a zone that is close to you. You can check the physical locations of each zone from here.)."
},
{
"code": null,
"e": 4664,
"s": 4543,
"text": "Since you have installed Google Cloud SDK, you can either create a bucket from the command-line or from the web console."
},
{
"code": null,
"e": 4767,
"s": 4664,
"text": "Click into “Storage” from left-side menu, then you’ll see a page like the above. Click “Create bucket”"
},
{
"code": null,
"e": 4982,
"s": 4767,
"text": "For convenience, enter project ID you checked at the end of “Creating a Free Trial Account on GCP” stage. You can just click “create” without changing any other details, or choose the same location as your project."
},
{
"code": null,
"e": 5229,
"s": 4982,
"text": "Replace your_project_id with the project ID that you copied and run the below line on your terminal to set BUCKET_NAME variable to your project ID and make it available to sub-processes. (A Bash script you need to run later will make use of this)"
},
{
"code": null,
"e": 5265,
"s": 5229,
"text": "export PROJECT_ID='your_project_id'"
},
{
"code": null,
"e": 5325,
"s": 5265,
"text": "Then create a bucket by running gsutil mb command as below."
},
{
"code": null,
"e": 5354,
"s": 5325,
"text": "gsutil mb gs://${PROJECT_ID}"
},
{
"code": null,
"e": 5588,
"s": 5354,
"text": "The above command will create a bucket with the default settings. If you want to create a bucket in a specific region or multi-region, you can give it -l option to specify the region. You can see available bucket locations from here."
},
{
"code": null,
"e": 5717,
"s": 5588,
"text": "#ex1) multi-region europegsutil mb -l eu gs://${PROJECT_ID}#ex)2 region europe-west1gsutil mb -l europe-west1 gs://${PROJECT_ID}"
},
{
"code": null,
"e": 5795,
"s": 5717,
"text": "Now clone the git repository I uploaded by running below command in terminal."
},
{
"code": null,
"e": 5852,
"s": 5795,
"text": "git clone https://github.com/tthustla/pyspark_sa_gcp.git"
},
{
"code": null,
"e": 5980,
"s": 5852,
"text": "Once you clone the repository, it will create a folder named pyspark_sa_gcp. Go into the folder and check what files are there."
},
{
"code": null,
"e": 6001,
"s": 5980,
"text": "cd pyspark_sa_gcp/ls"
},
{
"code": null,
"e": 6291,
"s": 6001,
"text": "You will see three files in the directory: data_prep.sh, pyspark_sa.py, train_test_split.py. In order to download the training data and prepare for training let’s run the Bash script data_prep.sh. Below is the content of the script and I have added comments to explain what each line does."
},
{
"code": null,
"e": 6606,
"s": 6291,
"text": "The original dataset for training is “Sentiment140”, which originated from Stanford University. The Dataset has 1.6million labelled tweets.50% of the data is with negative labels and the other 50% with positive labels. More info on the dataset can be found from the link. http://help.sentiment140.com/for-students/"
},
{
"code": null,
"e": 6734,
"s": 6606,
"text": "In the above Bash script, you can see it’s calling a Python script train_test_split.py. Let’s also take a look at what it does."
},
{
"code": null,
"e": 6933,
"s": 6734,
"text": "Now we can run the Bash script to prepare the data. Once it’s finished, it will have uploaded prepared data to the cloud storage bucket you created earlier. It will take 5~6 mins to upload the data."
},
{
"code": null,
"e": 6948,
"s": 6933,
"text": "./data_prep.sh"
},
{
"code": null,
"e": 7078,
"s": 6948,
"text": "Go to the Storage from the left side menu and click into your bucket -> pyspark_nlp -> data. You will see two files are uploaded."
},
{
"code": null,
"e": 7172,
"s": 7078,
"text": "Or you can also check the content of your bucket from your terminal by running below command."
},
{
"code": null,
"e": 7207,
"s": 7172,
"text": "gsutil ls -r gs://${PROJECT_ID}/**"
},
{
"code": null,
"e": 7579,
"s": 7207,
"text": "Cloud Dataproc is a Google cloud service for running Apache Spark and Apache Hadoop clusters. I have to say it is ridiculously simple and easy-to-use and it only takes a couple of minutes to spin up a cluster with Google Dataproc. Also, Google Dataproc offers autoscaling if you need, and you can adjust the cluster at any time, even when jobs are running on the cluster."
},
{
"code": null,
"e": 7764,
"s": 7579,
"text": "Go to Dataproc from the left side menu (you have to scroll down a bit. It’s under Big Data section) and click on “Clusters”. Click “Create clusters”, then you’ll see a page like below."
},
{
"code": null,
"e": 8537,
"s": 7764,
"text": "Give it a name (for convenience, I gave the project ID as its name), choose Region and Zone. To decrease the latency, it is a good idea to set the region to be the same as your bucket region. Here you need to change the default settings for worker nodes a little, as the free trial only gives you permission to run up to 8 cores. The default setting for a cluster is one master and two workers all with 4 CPUs each, which will exceed the 8 cores quota. So change the setting for your worker nodes to 2 CPUs, then click create at the bottom. After a couple of minutes of provisioning, you will see the cluster created with one master node (4 CPUs, 15GB memory, 500GB standard persistent disk) and two worker nodes (2 CPUs, 15GB memory, 500GB standard persistent disk each)."
},
{
"code": null,
"e": 8778,
"s": 8537,
"text": "Since we need to change the default setting a little bit, we need to add one more argument to the command, but it’s simple enough. Let’s create a cluster and give it the same name as the project ID, and set worker nodes to have 2 CPUs each."
},
{
"code": null,
"e": 8913,
"s": 8778,
"text": "gcloud dataproc clusters create ${PROJECT_ID} \\--project=${PROJECT_ID} \\--worker-machine-type='n1-standard-2' \\--zone='europe-west1-b'"
},
{
"code": null,
"e": 8972,
"s": 8913,
"text": "You can change the zone to be close to your bucket region."
},
{
"code": null,
"e": 9458,
"s": 8972,
"text": "Finally, we are ready to run the training on Google Dataproc. The Python script (pyspark_sa.py) for the training is included in the Git repository you cloned earlier. Since I commented on the script to explain what each line does, I will not go through the code. The code is a slightly refactored version of what I have done in Jupyter Notebook for my previous post. Below are a few of my previous posts, in case you want to know more in detail about PySpark or NLP feature extraction."
},
{
"code": null,
"e": 9490,
"s": 9458,
"text": "Sentiment Analysis with PySpark"
},
{
"code": null,
"e": 9581,
"s": 9490,
"text": "Another Twitter Sentiment Analysis with Python-Part 4 (Count Vectorizer, Confusion Matrix)"
},
{
"code": null,
"e": 9653,
"s": 9581,
"text": "Another Twitter Sentiment Analysis with Python-Part 5(TFIDF Vectorizer)"
},
{
"code": null,
"e": 9713,
"s": 9653,
"text": "And let’s take a look at what the Python script looks like."
},
{
"code": null,
"e": 10470,
"s": 9713,
"text": "Since I commented inside the script to explain what each line does, I will not go through the code extensively. But in a nutshell, the above script will take three command line arguments: Cloud Storage location where the training and test data are stored, a Cloud storage directory to store prediction result of the test data, and finally a Cloud storage directory to store the trained model. When called, it will first do the preprocessing of the training data -> build a pipeline -> fit the pipeline -> and make predictions on the test data -> print the accuracy of the predictions -> save prediction result as CSV -> save fitted pipeline model -> load the saved model -> print the accuracy again on the test data (to see if the model is properly saved)."
},
{
"code": null,
"e": 10761,
"s": 10470,
"text": "In order to run this job through the web console, we need to first upload the Python script to our cloud storage so that we can point the job to read the script. Let’s upload the script by running below command. (I’m assuming that you are still on pyspark_sa_gcp directory on your terminal)"
},
{
"code": null,
"e": 10817,
"s": 10761,
"text": "gsutil cp pyspark_sa.py gs://${PROJECT_ID}/pyspark_nlp/"
},
{
"code": null,
"e": 10903,
"s": 10817,
"text": "Now click into Dataproc on the web console, and click “Jobs” then click “SUBMIT JOB”."
},
{
"code": null,
"e": 11091,
"s": 10903,
"text": "From the above screenshot replace the blurred parts of the texts to your project ID, then click “submit” at the bottom. You can inspect the output of the machine by clicking into the job."
},
{
"code": null,
"e": 11287,
"s": 11091,
"text": "The job is finished after 15 minutes, and by looking at the output, it seems like the cluster struggled a bit, but nonetheless, the prediction looks fine and the model seems to be saved properly."
},
{
"code": null,
"e": 11557,
"s": 11287,
"text": "If you submit a job from the command-line, you don’t even need to upload your script to Cloud Storage. It will be able to grab a local file and move to the Dataproc cluster to execute. (Again I’m assuming that you are still on pyspark_sa_gcp directory on your terminal)"
},
{
"code": null,
"e": 11748,
"s": 11557,
"text": "gcloud dataproc jobs submit pyspark pyspark_sa.py \\--cluster=${PROJECT_ID} \\-- gs://${PROJECT_ID}/pyspark_nlp/data/ gs://${PROJECT_ID}/pyspark_nlp/result gs://${PROJECT_ID}/pyspark_nlp/model"
},
{
"code": null,
"e": 11960,
"s": 11748,
"text": "Again the cluster seemed to struggle a bit, but still got the result and model saved properly. (I have tried to submit the same job on my paid account with 4 CPUs worker nodes, then it didn’t throw any warnings)"
},
{
"code": null,
"e": 12185,
"s": 11960,
"text": "Go to your bucket, then go into pyspark_nlp folder. You will see that the results of the above Spark job have been saved into “result” directory (for the prediction data frame), and “model” directory (fitted pipeline model)."
},
{
"code": null,
"e": 12309,
"s": 12185,
"text": "Finally, don’t forget to delete the Dataproc cluster you have created to ensure it will not use up any more of your credit."
},
{
"code": null,
"e": 12576,
"s": 12309,
"text": "Through this post, I went through how to train Spark ML model on Google Dataproc and save the trained model for later use. What I showed here is only a small part of what GCP is capable of and I encourage you to explore other services on GCP and play around with it."
}
] |
Tryit Editor v3.7
|
Tryit: box-shadow with color
|
[] |
How to change an HTML element name using jQuery ? - GeeksforGeeks
|
07 Jul, 2021
Given an HTML document and the task is to replace an HTML element by another element. For example: we can change an element <b> with <h1> element without changing any other property.Approach:
Select the HTML element which need to be change.
Copy all attributes of previous element in an object.
Replace the previous element by new element.
Example 1: This example illustrates the above approach.
html
<!DOCTYPE HTML> <html> <head> <title> JQuery | Change an element type. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <br><br> <b style = "color:green; font-weight: bold;"> Welcome to GeeksforGeeks </b> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Click on the button to " + "replace an HTML element"; function GFG_Fun() { var attribute = { }; $.each($("b")[0].attributes, function(id, atr) { attribute[atr.nodeName] = atr.nodeValue; }); $("b").replaceWith(function () { return $("<h1 />", attribute).append($(this).contents()); }); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example using the above discussed approach but with a different way to copy attributes.
html
<!DOCTYPE HTML> <html> <head> <title> JQuery | Change an element type. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body id = "body" style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <br><br> <b style = "color:green; font-weight: bold;"> Welcome to GeeksforGeeks </b> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Click on the button to " + "replace an HTML element"; function GFG_Fun() { var oldElement = $("b"); var newElement = $("<h1>"); for(var i=0; i<oldElement[0].attributes.length; i++) { var Attr = oldElement[0].attributes[i].nodeName; var AttrVal = oldElement[0].attributes[i].nodeValue; newElement.attr(Attr, AttrVal); } newElement.html(oldElement.html()); oldElement.replaceWith(newElement); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
saurabh1990aror
jQuery-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 25494,
"s": 25300,
"text": "Given an HTML document and the task is to replace an HTML element by another element. For example: we can change an element <b> with <h1> element without changing any other property.Approach: "
},
{
"code": null,
"e": 25543,
"s": 25494,
"text": "Select the HTML element which need to be change."
},
{
"code": null,
"e": 25597,
"s": 25543,
"text": "Copy all attributes of previous element in an object."
},
{
"code": null,
"e": 25642,
"s": 25597,
"text": "Replace the previous element by new element."
},
{
"code": null,
"e": 25700,
"s": 25642,
"text": "Example 1: This example illustrates the above approach. "
},
{
"code": null,
"e": 25705,
"s": 25700,
"text": "html"
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | Change an element type. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <br><br> <b style = \"color:green; font-weight: bold;\"> Welcome to GeeksforGeeks </b> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Click on the button to \" + \"replace an HTML element\"; function GFG_Fun() { var attribute = { }; $.each($(\"b\")[0].attributes, function(id, atr) { attribute[atr.nodeName] = atr.nodeValue; }); $(\"b\").replaceWith(function () { return $(\"<h1 />\", attribute).append($(this).contents()); }); } </script> </body> </html>",
"e": 26879,
"s": 25705,
"text": null
},
{
"code": null,
"e": 26889,
"s": 26879,
"text": "Output: "
},
{
"code": null,
"e": 26922,
"s": 26889,
"text": "Before clicking on the button: "
},
{
"code": null,
"e": 26954,
"s": 26922,
"text": "After clicking on the button: "
},
{
"code": null,
"e": 27060,
"s": 26954,
"text": "Example 2: This example using the above discussed approach but with a different way to copy attributes. "
},
{
"code": null,
"e": 27065,
"s": 27060,
"text": "html"
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | Change an element type. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body id = \"body\" style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <br><br> <b style = \"color:green; font-weight: bold;\"> Welcome to GeeksforGeeks </b> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Click on the button to \" + \"replace an HTML element\"; function GFG_Fun() { var oldElement = $(\"b\"); var newElement = $(\"<h1>\"); for(var i=0; i<oldElement[0].attributes.length; i++) { var Attr = oldElement[0].attributes[i].nodeName; var AttrVal = oldElement[0].attributes[i].nodeValue; newElement.attr(Attr, AttrVal); } newElement.html(oldElement.html()); oldElement.replaceWith(newElement); } </script> </body> </html>",
"e": 28355,
"s": 27065,
"text": null
},
{
"code": null,
"e": 28365,
"s": 28355,
"text": "Output: "
},
{
"code": null,
"e": 28398,
"s": 28365,
"text": "Before clicking on the button: "
},
{
"code": null,
"e": 28430,
"s": 28398,
"text": "After clicking on the button: "
},
{
"code": null,
"e": 28448,
"s": 28432,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28460,
"s": 28448,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28471,
"s": 28460,
"text": "JavaScript"
},
{
"code": null,
"e": 28488,
"s": 28471,
"text": "Web Technologies"
},
{
"code": null,
"e": 28515,
"s": 28488,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28613,
"s": 28515,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28674,
"s": 28613,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28715,
"s": 28674,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28755,
"s": 28715,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28809,
"s": 28755,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28857,
"s": 28809,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28899,
"s": 28857,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28932,
"s": 28899,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28975,
"s": 28932,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29037,
"s": 28975,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
ASP.NET Core - Exceptions
|
In this chapter, we will discuss exceptions and error handling. When errors occur in your ASP.NET Core app, you can handle them in a variety of ways. Let us see an additional piece of middleware that is available through the diagnostics package. This piece of middleware will help us process errors.
To simulate an error, let us go to app.Run and see how the application behaves if we just throw an exception every time we hit this piece of middleware.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
namespace FirstAppDemo {
public class Startup {
public Startup() {
var builder = new ConfigurationBuilder()
.AddJsonFile("AppSettings.json");
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime.
// Use this method to add services to the container.
// For more information on how to configure your application,
// visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app) {
app.UseIISPlatformHandler();
app.UseRuntimeInfoPage();
app.Run(async (context) => {
throw new System.Exception("Throw Exception");
var msg = Configuration["message"];
await context.Response.WriteAsync(msg);
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
It will just throw an exception with a very generic message. Save Startup.cs page and run your application.
You will see that we failed to load this resource. There was a HTTP 500 error, an internal server error, and that is not very helpful. It might be nice to get some exception information.
Let us add another piece of middleware, which is the UseDeveloperExceptionPage.
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app) {
app.UseIISPlatformHandler();
app.UseDeveloperExceptionPage();
app.UseRuntimeInfoPage();
app.Run(async (context) => {
throw new System.Exception("Throw Exception");
var msg = Configuration["message"];
await context.Response.WriteAsync(msg);
});
}
This piece of middleware is a little bit different than the other pieces of middleware, the other pieces of middleware are typically looking at the incoming request and making some decision about that request.
This piece of middleware is a little bit different than the other pieces of middleware, the other pieces of middleware are typically looking at the incoming request and making some decision about that request.
The UseDeveloperExceptionPage doesn't care so much about the incoming requests as it does what happens later in the pipeline.
The UseDeveloperExceptionPage doesn't care so much about the incoming requests as it does what happens later in the pipeline.
It is going to just call into the next piece of middleware, but then it is going to wait to see if anything later in the pipeline generates an exception and if there is an exception, this piece of middleware will give you an error page with some additional information about that exception.
It is going to just call into the next piece of middleware, but then it is going to wait to see if anything later in the pipeline generates an exception and if there is an exception, this piece of middleware will give you an error page with some additional information about that exception.
Let us now run the application again. It will produce an output as shown in the following screenshot.
Now you will see some information that you would expect if there was an error in development. You will also get a stack trace and you can see that there was an unhandled exception thrown on line 37 of Startup.cs.
You can also see raw exception details and all of this information can be very useful for a developer. In fact, we probably only want to show this information when a developer is running the application.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2761,
"s": 2461,
"text": "In this chapter, we will discuss exceptions and error handling. When errors occur in your ASP.NET Core app, you can handle them in a variety of ways. Let us see an additional piece of middleware that is available through the diagnostics package. This piece of middleware will help us process errors."
},
{
"code": null,
"e": 2914,
"s": 2761,
"text": "To simulate an error, let us go to app.Run and see how the application behaves if we just throw an exception every time we hit this piece of middleware."
},
{
"code": null,
"e": 4359,
"s": 2914,
"text": "using Microsoft.AspNet.Builder; \nusing Microsoft.AspNet.Hosting; \nusing Microsoft.AspNet.Http; \n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Configuration; \n\nnamespace FirstAppDemo { \n public class Startup { \n public Startup() { \n var builder = new ConfigurationBuilder() \n .AddJsonFile(\"AppSettings.json\"); \n Configuration = builder.Build(); \n } \n public IConfiguration Configuration { get; set; } \n \n // This method gets called by the runtime. \n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID=398940 \n public void ConfigureServices(IServiceCollection services) { \n } \n \n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline.\n public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n app.UseRuntimeInfoPage(); \n \n app.Run(async (context) => { \n throw new System.Exception(\"Throw Exception\"); \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n } \n \n // Entry point for the application. \n public static void Main(string[] args) => WebApplication.Run<Startup>(args); \n } \n} "
},
{
"code": null,
"e": 4467,
"s": 4359,
"text": "It will just throw an exception with a very generic message. Save Startup.cs page and run your application."
},
{
"code": null,
"e": 4654,
"s": 4467,
"text": "You will see that we failed to load this resource. There was a HTTP 500 error, an internal server error, and that is not very helpful. It might be nice to get some exception information."
},
{
"code": null,
"e": 4734,
"s": 4654,
"text": "Let us add another piece of middleware, which is the UseDeveloperExceptionPage."
},
{
"code": null,
"e": 5183,
"s": 4734,
"text": "// This method gets called by the runtime. \n// Use this method to configure the HTTP request pipeline. \npublic void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n \n app.Run(async (context) => { \n throw new System.Exception(\"Throw Exception\"); \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n}"
},
{
"code": null,
"e": 5393,
"s": 5183,
"text": "This piece of middleware is a little bit different than the other pieces of middleware, the other pieces of middleware are typically looking at the incoming request and making some decision about that request."
},
{
"code": null,
"e": 5603,
"s": 5393,
"text": "This piece of middleware is a little bit different than the other pieces of middleware, the other pieces of middleware are typically looking at the incoming request and making some decision about that request."
},
{
"code": null,
"e": 5729,
"s": 5603,
"text": "The UseDeveloperExceptionPage doesn't care so much about the incoming requests as it does what happens later in the pipeline."
},
{
"code": null,
"e": 5855,
"s": 5729,
"text": "The UseDeveloperExceptionPage doesn't care so much about the incoming requests as it does what happens later in the pipeline."
},
{
"code": null,
"e": 6146,
"s": 5855,
"text": "It is going to just call into the next piece of middleware, but then it is going to wait to see if anything later in the pipeline generates an exception and if there is an exception, this piece of middleware will give you an error page with some additional information about that exception."
},
{
"code": null,
"e": 6437,
"s": 6146,
"text": "It is going to just call into the next piece of middleware, but then it is going to wait to see if anything later in the pipeline generates an exception and if there is an exception, this piece of middleware will give you an error page with some additional information about that exception."
},
{
"code": null,
"e": 6539,
"s": 6437,
"text": "Let us now run the application again. It will produce an output as shown in the following screenshot."
},
{
"code": null,
"e": 6752,
"s": 6539,
"text": "Now you will see some information that you would expect if there was an error in development. You will also get a stack trace and you can see that there was an unhandled exception thrown on line 37 of Startup.cs."
},
{
"code": null,
"e": 6956,
"s": 6752,
"text": "You can also see raw exception details and all of this information can be very useful for a developer. In fact, we probably only want to show this information when a developer is running the application."
},
{
"code": null,
"e": 6991,
"s": 6956,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7005,
"s": 6991,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7040,
"s": 7005,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7063,
"s": 7040,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 7097,
"s": 7063,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 7117,
"s": 7097,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7152,
"s": 7117,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7169,
"s": 7152,
"text": " University Code"
},
{
"code": null,
"e": 7204,
"s": 7169,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7221,
"s": 7204,
"text": " University Code"
},
{
"code": null,
"e": 7255,
"s": 7221,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7270,
"s": 7255,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 7277,
"s": 7270,
"text": " Print"
},
{
"code": null,
"e": 7288,
"s": 7277,
"text": " Add Notes"
}
] |
Check if the Matrix satisfies the given conditions - GeeksforGeeks
|
28 May, 2021
Given a matrix mat[][], the task is to check whether the matrix is valid or not. A valid matrix is the matrix that satisfies the given conditions:
For every row, it must contain a single distinct character.No two consecutive rows have a character in common.
For every row, it must contain a single distinct character.
No two consecutive rows have a character in common.
Examples:
Input: mat[][] = { {0, 0, 0}, {1, 1, 1}, {0, 0, 2}} Output: No The last row doesn’t consist of a single distinct character.
Input: mat[][] = { {8, 8, 8, 8, 8}, {4, 4, 4, 4, 4}, {6, 6, 6, 6, 6}, {5, 5, 5, 5, 5}, {8, 8, 8, 8, 8}} Output: Yes
Approach: First of all check the first row if it contains same characters or not. If it contains same characters then iterate the second row and compare the characters of the current row with the first element of the previous row, if the two elements are equal or the characters of the current row are different, return false. Repeat the above process for all the consecutive row.
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; // Storing the size of the matrixconst int M = 5, N = 5; // Function that returns true if// the matrix is validbool isPerfect(char board[M][N + 1]){ char m; for (int i = 0; i < M; i++) { // Get the current row string s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s[0] == m) return false; // Checking if all the characters of the // current row are same or not for (int j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s[0]; // Comparing all the elements // with the first element else { if (m != s[j]) return false; } } } return true;} // Driver codeint main(){ char board[M][N + 1] = { "88888", "44444", "66666", "55555", "88888" }; if (isPerfect(board)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachclass GFG{ // Storing the size of the matrix static final int M = 5, N = 5; // Function that returns true if // the matrix is valid static boolean isPerfect(String board[]) { char m = 0; for (int i = 0; i < M; i++) { // Get the current row String s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s.charAt(0) == m) return false; // Checking if all the characters of the // current row are same or not for (int j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s.charAt(0); // Comparing all the elements // with the first element else { if (m != s.charAt(j)) return false; } } } return true; } // Driver code public static void main (String[] args) { String board[] = { "88888", "44444", "66666", "55555", "88888" }; if (isPerfect(board)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Storing the size of the matrixM = 5N = 5 # Function that returns true if# the matrix is validdef isPerfect(board): m = '' for i in range(M): # Get the current row s = board[i] # Comparing first element # of the row with the element # of previous row if (i > 0 and s[0] == m): return False # Checking if all the characters of the # current row are same or not for j in range(N): # Storing the first character if (j == 0): m = s[0] # Comparing all the elements # with the first element else: if (m != s[j]): return False return True # Driver codeboard = ["88888", "44444", "66666", "55555", "88888"] if (isPerfect(board)): print("Yes")else: print("No") # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // Storing the size of the matrix static readonly int M = 5, N = 5; // Function that returns true if // the matrix is valid static bool isPerfect(String []board) { char m = '0'; for (int i = 0; i < M; i++) { // Get the current row String s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s[0] == m) return false; // Checking if all the characters of the // current row are same or not for (int j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s[0]; // Comparing all the elements // with the first element else { if (m != s[j]) return false; } } } return true; } // Driver code public static void Main (String[] args) { String []board = { "88888", "44444", "66666", "55555", "88888" }; if (isPerfect(board)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Storing the size of the matrixvar M = 5, N = 5; // Function that returns true if// the matrix is validfunction isPerfect(board){ var m; for(var i = 0; i < M; i++) { // Get the current row var s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s[0] == m) return false; // Checking if all the characters of the // current row are same or not for(var j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s[0]; // Comparing all the elements // with the first element else { if (m != s[j]) return false; } } } return true;} // Driver codevar board = [ "88888", "44444", "66666", "55555", "88888" ]; if (isPerfect(board)) document.write("Yes");else document.write("No"); // This code is contributed by itsok </script>
Yes
mohit kumar 29
ankthon
Rajput-Ji
itsok
C++ Programs
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Bits manipulation (Important tactics)
Top 10 Algorithms and Data Structures for Competitive Programming
|
[
{
"code": null,
"e": 24528,
"s": 24500,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 24676,
"s": 24528,
"text": "Given a matrix mat[][], the task is to check whether the matrix is valid or not. A valid matrix is the matrix that satisfies the given conditions: "
},
{
"code": null,
"e": 24787,
"s": 24676,
"text": "For every row, it must contain a single distinct character.No two consecutive rows have a character in common."
},
{
"code": null,
"e": 24847,
"s": 24787,
"text": "For every row, it must contain a single distinct character."
},
{
"code": null,
"e": 24899,
"s": 24847,
"text": "No two consecutive rows have a character in common."
},
{
"code": null,
"e": 24910,
"s": 24899,
"text": "Examples: "
},
{
"code": null,
"e": 25034,
"s": 24910,
"text": "Input: mat[][] = { {0, 0, 0}, {1, 1, 1}, {0, 0, 2}} Output: No The last row doesn’t consist of a single distinct character."
},
{
"code": null,
"e": 25152,
"s": 25034,
"text": "Input: mat[][] = { {8, 8, 8, 8, 8}, {4, 4, 4, 4, 4}, {6, 6, 6, 6, 6}, {5, 5, 5, 5, 5}, {8, 8, 8, 8, 8}} Output: Yes "
},
{
"code": null,
"e": 25533,
"s": 25152,
"text": "Approach: First of all check the first row if it contains same characters or not. If it contains same characters then iterate the second row and compare the characters of the current row with the first element of the previous row, if the two elements are equal or the characters of the current row are different, return false. Repeat the above process for all the consecutive row."
},
{
"code": null,
"e": 25586,
"s": 25533,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25590,
"s": 25586,
"text": "C++"
},
{
"code": null,
"e": 25595,
"s": 25590,
"text": "Java"
},
{
"code": null,
"e": 25603,
"s": 25595,
"text": "Python3"
},
{
"code": null,
"e": 25606,
"s": 25603,
"text": "C#"
},
{
"code": null,
"e": 25617,
"s": 25606,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Storing the size of the matrixconst int M = 5, N = 5; // Function that returns true if// the matrix is validbool isPerfect(char board[M][N + 1]){ char m; for (int i = 0; i < M; i++) { // Get the current row string s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s[0] == m) return false; // Checking if all the characters of the // current row are same or not for (int j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s[0]; // Comparing all the elements // with the first element else { if (m != s[j]) return false; } } } return true;} // Driver codeint main(){ char board[M][N + 1] = { \"88888\", \"44444\", \"66666\", \"55555\", \"88888\" }; if (isPerfect(board)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26832,
"s": 25617,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Storing the size of the matrix static final int M = 5, N = 5; // Function that returns true if // the matrix is valid static boolean isPerfect(String board[]) { char m = 0; for (int i = 0; i < M; i++) { // Get the current row String s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s.charAt(0) == m) return false; // Checking if all the characters of the // current row are same or not for (int j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s.charAt(0); // Comparing all the elements // with the first element else { if (m != s.charAt(j)) return false; } } } return true; } // Driver code public static void main (String[] args) { String board[] = { \"88888\", \"44444\", \"66666\", \"55555\", \"88888\" }; if (isPerfect(board)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by AnkitRai01",
"e": 28302,
"s": 26832,
"text": null
},
{
"code": "# Python3 implementation of the approach # Storing the size of the matrixM = 5N = 5 # Function that returns true if# the matrix is validdef isPerfect(board): m = '' for i in range(M): # Get the current row s = board[i] # Comparing first element # of the row with the element # of previous row if (i > 0 and s[0] == m): return False # Checking if all the characters of the # current row are same or not for j in range(N): # Storing the first character if (j == 0): m = s[0] # Comparing all the elements # with the first element else: if (m != s[j]): return False return True # Driver codeboard = [\"88888\", \"44444\", \"66666\", \"55555\", \"88888\"] if (isPerfect(board)): print(\"Yes\")else: print(\"No\") # This code is contributed by Mohit Kumar",
"e": 29270,
"s": 28302,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Storing the size of the matrix static readonly int M = 5, N = 5; // Function that returns true if // the matrix is valid static bool isPerfect(String []board) { char m = '0'; for (int i = 0; i < M; i++) { // Get the current row String s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s[0] == m) return false; // Checking if all the characters of the // current row are same or not for (int j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s[0]; // Comparing all the elements // with the first element else { if (m != s[j]) return false; } } } return true; } // Driver code public static void Main (String[] args) { String []board = { \"88888\", \"44444\", \"66666\", \"55555\", \"88888\" }; if (isPerfect(board)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji",
"e": 30730,
"s": 29270,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Storing the size of the matrixvar M = 5, N = 5; // Function that returns true if// the matrix is validfunction isPerfect(board){ var m; for(var i = 0; i < M; i++) { // Get the current row var s = board[i]; // Comparing first element // of the row with the element // of previous row if (i > 0 && s[0] == m) return false; // Checking if all the characters of the // current row are same or not for(var j = 0; j < N; j++) { // Storing the first character if (j == 0) m = s[0]; // Comparing all the elements // with the first element else { if (m != s[j]) return false; } } } return true;} // Driver codevar board = [ \"88888\", \"44444\", \"66666\", \"55555\", \"88888\" ]; if (isPerfect(board)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by itsok </script>",
"e": 31872,
"s": 30730,
"text": null
},
{
"code": null,
"e": 31876,
"s": 31872,
"text": "Yes"
},
{
"code": null,
"e": 31893,
"s": 31878,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31901,
"s": 31893,
"text": "ankthon"
},
{
"code": null,
"e": 31911,
"s": 31901,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31917,
"s": 31911,
"text": "itsok"
},
{
"code": null,
"e": 31930,
"s": 31917,
"text": "C++ Programs"
},
{
"code": null,
"e": 31954,
"s": 31930,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32052,
"s": 31954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32093,
"s": 32052,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 32114,
"s": 32093,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 32173,
"s": 32114,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 32185,
"s": 32173,
"text": "cout in C++"
},
{
"code": null,
"e": 32206,
"s": 32185,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 32249,
"s": 32206,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 32292,
"s": 32249,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 32333,
"s": 32292,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 32371,
"s": 32333,
"text": "Bits manipulation (Important tactics)"
}
] |
CICS - Temporary Storage
|
There are different scratch pads which are available in CICS for saving data or to transfer the data between transactions. There are five storage areas which are provided by CICS, which we will be discussing in this module.
The COMMAREA behaves like a scratch pad that can be used to pass data from one program to another program, either within the same transaction or from different transactions. It should be defined in the LINKAGE SECTION using DFHCOMMAREA name.
Any transaction in the CICS region can access Common Work Area and hence the format and use of it must be agreed upon by all transactions in the system that decides to use it. There is only one CWA in the entire CICS region.
Transaction Work Area is used to pass data between the application programs that are executed with in the same transaction. TWA exists only for the duration of transaction. Its size is defined in the Program Control Table.
Temporary Storage Queue (TSQ) is a feature that is provided by the Temporary Storage Control Program (TSP).
A TSQ is a queue of records that can be created, read and deleted by different tasks or programs in the same CICS region.
A TSQ is a queue of records that can be created, read and deleted by different tasks or programs in the same CICS region.
A queue identifier is used to identify TSQ.
A queue identifier is used to identify TSQ.
A record within a TSQ is identified by the relative position known as the item number.
A record within a TSQ is identified by the relative position known as the item number.
The records in TSQ, remains accessible until the entire TSQ is explicitly deleted.
The records in TSQ, remains accessible until the entire TSQ is explicitly deleted.
The records in TSQ can be read sequentially or directly.
The records in TSQ can be read sequentially or directly.
TSQs may be written in the main storage or the auxiliary storage in the DASD.
TSQs may be written in the main storage or the auxiliary storage in the DASD.
This command is used to add items to an existing TSQ. Also, we can create a new TSQ using this command. Following is the syntax of WRITEQ TS command −
EXEC CICS WRITEQ TS
QUEUE ('queue-name')
FROM (queue-record)
[LENGTH (queue-record-length)]
[ITEM (item-number)]
[REWRITE]
[MAIN /AUXILIARY]
END-EXEC.
Following are the details of parameters used in the WRITEQ TS command −
The QUEUE is identified by the name which is mentioned in this parameter.
The QUEUE is identified by the name which is mentioned in this parameter.
FROM and LENGTH options are used to specify the record that is to be written to the queue and its length.
FROM and LENGTH options are used to specify the record that is to be written to the queue and its length.
If the ITEM option is specified, CICS assigns an item number to the record in the queue, and sets the data area supplied in that option to the item number. If the record starts a new queue, the item number assigned is 1 and subsequent item numbers follow on sequentially.
If the ITEM option is specified, CICS assigns an item number to the record in the queue, and sets the data area supplied in that option to the item number. If the record starts a new queue, the item number assigned is 1 and subsequent item numbers follow on sequentially.
The REWRITE option is used to update a record already present in the queue.
The REWRITE option is used to update a record already present in the queue.
MAIN / AUXILIARY option is used to store records in main or auxiliary storage. Default is AUXILIARY.
MAIN / AUXILIARY option is used to store records in main or auxiliary storage. Default is AUXILIARY.
This command is used read the Temporary Storage Queue. Following is the syntax of READQ TS −
EXEC CICS READQ TS
QUEUE ('queue-name')
INTO (queue-record)
[LENGTH (queue-record-length)]
[ITEM (item-number)]
[NEXT]
END-EXEC.
This command is used delete the Temporary Storage Queue. Following is the syntax of DELETEQ TS −
EXEC CICS DELETEQ TS
QUEUE ('queue-name')
END-EXEC.
Transient Data Queue is transient in nature as it can be created and deleted quickly. It allows only sequential access.
The contents of the queue can be read only once as it gets destroyed once a read is performed and hence the name Transient.
The contents of the queue can be read only once as it gets destroyed once a read is performed and hence the name Transient.
It cannot be updated.
It cannot be updated.
It requires an entry in DCT.
It requires an entry in DCT.
This command is used to write Transient data queues and they are always written to a file. Following is the syntax of WRITEQ TD command −
EXEC CICS WRITEQ TD
QUEUE ('queue-name')
FROM (queue-record)
[LENGTH (queue-record-length)]
END-EXEC.
This command is used read the Transient data queue. Following is the syntax of READQ TD −
EXEC CICS READQ TD
QUEUE ('queue-name')
INTO (queue-record)
[LENGTH (queue-record-length)]
END-EXEC.
This command is used delete the Transient data queue. Following is the syntax of DELETEQ TD −
EXEC CICS DELETEQ TD
QUEUE ('queue-name')
END-EXEC.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2150,
"s": 1926,
"text": "There are different scratch pads which are available in CICS for saving data or to transfer the data between transactions. There are five storage areas which are provided by CICS, which we will be discussing in this module."
},
{
"code": null,
"e": 2392,
"s": 2150,
"text": "The COMMAREA behaves like a scratch pad that can be used to pass data from one program to another program, either within the same transaction or from different transactions. It should be defined in the LINKAGE SECTION using DFHCOMMAREA name."
},
{
"code": null,
"e": 2617,
"s": 2392,
"text": "Any transaction in the CICS region can access Common Work Area and hence the format and use of it must be agreed upon by all transactions in the system that decides to use it. There is only one CWA in the entire CICS region."
},
{
"code": null,
"e": 2840,
"s": 2617,
"text": "Transaction Work Area is used to pass data between the application programs that are executed with in the same transaction. TWA exists only for the duration of transaction. Its size is defined in the Program Control Table."
},
{
"code": null,
"e": 2948,
"s": 2840,
"text": "Temporary Storage Queue (TSQ) is a feature that is provided by the Temporary Storage Control Program (TSP)."
},
{
"code": null,
"e": 3070,
"s": 2948,
"text": "A TSQ is a queue of records that can be created, read and deleted by different tasks or programs in the same CICS region."
},
{
"code": null,
"e": 3192,
"s": 3070,
"text": "A TSQ is a queue of records that can be created, read and deleted by different tasks or programs in the same CICS region."
},
{
"code": null,
"e": 3236,
"s": 3192,
"text": "A queue identifier is used to identify TSQ."
},
{
"code": null,
"e": 3280,
"s": 3236,
"text": "A queue identifier is used to identify TSQ."
},
{
"code": null,
"e": 3367,
"s": 3280,
"text": "A record within a TSQ is identified by the relative position known as the item number."
},
{
"code": null,
"e": 3454,
"s": 3367,
"text": "A record within a TSQ is identified by the relative position known as the item number."
},
{
"code": null,
"e": 3537,
"s": 3454,
"text": "The records in TSQ, remains accessible until the entire TSQ is explicitly deleted."
},
{
"code": null,
"e": 3620,
"s": 3537,
"text": "The records in TSQ, remains accessible until the entire TSQ is explicitly deleted."
},
{
"code": null,
"e": 3677,
"s": 3620,
"text": "The records in TSQ can be read sequentially or directly."
},
{
"code": null,
"e": 3734,
"s": 3677,
"text": "The records in TSQ can be read sequentially or directly."
},
{
"code": null,
"e": 3812,
"s": 3734,
"text": "TSQs may be written in the main storage or the auxiliary storage in the DASD."
},
{
"code": null,
"e": 3890,
"s": 3812,
"text": "TSQs may be written in the main storage or the auxiliary storage in the DASD."
},
{
"code": null,
"e": 4041,
"s": 3890,
"text": "This command is used to add items to an existing TSQ. Also, we can create a new TSQ using this command. Following is the syntax of WRITEQ TS command −"
},
{
"code": null,
"e": 4211,
"s": 4041,
"text": "EXEC CICS WRITEQ TS\n QUEUE ('queue-name')\n FROM (queue-record)\n [LENGTH (queue-record-length)]\n [ITEM (item-number)]\n [REWRITE]\n [MAIN /AUXILIARY]\nEND-EXEC.\n"
},
{
"code": null,
"e": 4283,
"s": 4211,
"text": "Following are the details of parameters used in the WRITEQ TS command −"
},
{
"code": null,
"e": 4357,
"s": 4283,
"text": "The QUEUE is identified by the name which is mentioned in this parameter."
},
{
"code": null,
"e": 4431,
"s": 4357,
"text": "The QUEUE is identified by the name which is mentioned in this parameter."
},
{
"code": null,
"e": 4537,
"s": 4431,
"text": "FROM and LENGTH options are used to specify the record that is to be written to the queue and its length."
},
{
"code": null,
"e": 4643,
"s": 4537,
"text": "FROM and LENGTH options are used to specify the record that is to be written to the queue and its length."
},
{
"code": null,
"e": 4915,
"s": 4643,
"text": "If the ITEM option is specified, CICS assigns an item number to the record in the queue, and sets the data area supplied in that option to the item number. If the record starts a new queue, the item number assigned is 1 and subsequent item numbers follow on sequentially."
},
{
"code": null,
"e": 5187,
"s": 4915,
"text": "If the ITEM option is specified, CICS assigns an item number to the record in the queue, and sets the data area supplied in that option to the item number. If the record starts a new queue, the item number assigned is 1 and subsequent item numbers follow on sequentially."
},
{
"code": null,
"e": 5263,
"s": 5187,
"text": "The REWRITE option is used to update a record already present in the queue."
},
{
"code": null,
"e": 5339,
"s": 5263,
"text": "The REWRITE option is used to update a record already present in the queue."
},
{
"code": null,
"e": 5440,
"s": 5339,
"text": "MAIN / AUXILIARY option is used to store records in main or auxiliary storage. Default is AUXILIARY."
},
{
"code": null,
"e": 5541,
"s": 5440,
"text": "MAIN / AUXILIARY option is used to store records in main or auxiliary storage. Default is AUXILIARY."
},
{
"code": null,
"e": 5634,
"s": 5541,
"text": "This command is used read the Temporary Storage Queue. Following is the syntax of READQ TS −"
},
{
"code": null,
"e": 5779,
"s": 5634,
"text": "EXEC CICS READQ TS\n QUEUE ('queue-name')\n INTO (queue-record)\n [LENGTH (queue-record-length)]\n [ITEM (item-number)]\n [NEXT]\nEND-EXEC.\n"
},
{
"code": null,
"e": 5876,
"s": 5779,
"text": "This command is used delete the Temporary Storage Queue. Following is the syntax of DELETEQ TS −"
},
{
"code": null,
"e": 5932,
"s": 5876,
"text": "EXEC CICS DELETEQ TS\n QUEUE ('queue-name')\nEND-EXEC.\n"
},
{
"code": null,
"e": 6052,
"s": 5932,
"text": "Transient Data Queue is transient in nature as it can be created and deleted quickly. It allows only sequential access."
},
{
"code": null,
"e": 6176,
"s": 6052,
"text": "The contents of the queue can be read only once as it gets destroyed once a read is performed and hence the name Transient."
},
{
"code": null,
"e": 6300,
"s": 6176,
"text": "The contents of the queue can be read only once as it gets destroyed once a read is performed and hence the name Transient."
},
{
"code": null,
"e": 6322,
"s": 6300,
"text": "It cannot be updated."
},
{
"code": null,
"e": 6344,
"s": 6322,
"text": "It cannot be updated."
},
{
"code": null,
"e": 6373,
"s": 6344,
"text": "It requires an entry in DCT."
},
{
"code": null,
"e": 6402,
"s": 6373,
"text": "It requires an entry in DCT."
},
{
"code": null,
"e": 6540,
"s": 6402,
"text": "This command is used to write Transient data queues and they are always written to a file. Following is the syntax of WRITEQ TD command −"
},
{
"code": null,
"e": 6652,
"s": 6540,
"text": "EXEC CICS WRITEQ TD\n QUEUE ('queue-name')\n FROM (queue-record)\n [LENGTH (queue-record-length)]\nEND-EXEC.\n"
},
{
"code": null,
"e": 6742,
"s": 6652,
"text": "This command is used read the Transient data queue. Following is the syntax of READQ TD −"
},
{
"code": null,
"e": 6853,
"s": 6742,
"text": "EXEC CICS READQ TD\n QUEUE ('queue-name')\n INTO (queue-record)\n [LENGTH (queue-record-length)]\nEND-EXEC.\n"
},
{
"code": null,
"e": 6947,
"s": 6853,
"text": "This command is used delete the Transient data queue. Following is the syntax of DELETEQ TD −"
},
{
"code": null,
"e": 7003,
"s": 6947,
"text": "EXEC CICS DELETEQ TD\n QUEUE ('queue-name')\nEND-EXEC.\n"
},
{
"code": null,
"e": 7010,
"s": 7003,
"text": " Print"
},
{
"code": null,
"e": 7021,
"s": 7010,
"text": " Add Notes"
}
] |
Copy Files from Docker Container to Local Machine
|
If you are working on a project that requires frequent copying of files and folders either from container to your local machine or from the local machine to the container, docker provides an easy and simple way to do that. If you have already built a docker image which is of large size and contains a large number of files and in the midst of the project you want to copy files to and from the container, it’s highly inefficient to put the files in the docker build context and build images repeatedly. Instead, docker allows easy copying of files to and from containers.
In this article, we will learn about the commands that will allow us to do so. We will look for commands for copying the files from both local machine to container and vice versa.
If you want to copy a file from your container to your local machine, you can use the following command.
sudo docker cp <Container ID>:<Path of file inside the container> <Path in the local machine>
For example,
If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /usr/src/app/file.txt in the container to /home/username/Desktop/folder in the local machine, you can use the command -
sudo docker cp f4628571q5gc:/usr/src/app/file.txt home/username/Desktop/folder/
If you want to paste the file in the current directory of you local machine, you can simply use -
sudo docker cp f4628571q5gc:/usr/src/app/file.txt . (Don’t forget the dot)
If you want to copy all the files from a particular folder in container, to a folder in the local machine, use the following command -
sudo docker cp f4628571q5gc:/usr/src/app/ home/username/Desktop/folder/
If you want to copy a file from your local machine to a container, you can use the following command.
sudo docker cp <Path in the local machine> <Container ID>:<Path of file inside the container>
For example,
If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /home/username/Desktop/folder/file.txt in the local machine to /usr/src/app/ in the container, you can use the command -
sudo docker cp /home/username/Desktop/folder/file.txt f4628571q5gc:/usr/src/app/
If you want to copy all the files from a folder in your local machine to a folder in the container, use the following command -
sudo docker cp /home/username/Desktop/folder f4628571q5gc:/usr/src/app/
To conclude, after you have already built an image with a build context and you want to copy files and folders to and from the container, you can easily do that using the commands mentioned above.
|
[
{
"code": null,
"e": 1635,
"s": 1062,
"text": "If you are working on a project that requires frequent copying of files and folders either from container to your local machine or from the local machine to the container, docker provides an easy and simple way to do that. If you have already built a docker image which is of large size and contains a large number of files and in the midst of the project you want to copy files to and from the container, it’s highly inefficient to put the files in the docker build context and build images repeatedly. Instead, docker allows easy copying of files to and from containers."
},
{
"code": null,
"e": 1815,
"s": 1635,
"text": "In this article, we will learn about the commands that will allow us to do so. We will look for commands for copying the files from both local machine to container and vice versa."
},
{
"code": null,
"e": 1920,
"s": 1815,
"text": "If you want to copy a file from your container to your local machine, you can use the following command."
},
{
"code": null,
"e": 2014,
"s": 1920,
"text": "sudo docker cp <Container ID>:<Path of file inside the container> <Path in the local machine>"
},
{
"code": null,
"e": 2027,
"s": 2014,
"text": "For example,"
},
{
"code": null,
"e": 2239,
"s": 2027,
"text": "If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /usr/src/app/file.txt in the container to /home/username/Desktop/folder in the local machine, you can use the command -"
},
{
"code": null,
"e": 2319,
"s": 2239,
"text": "sudo docker cp f4628571q5gc:/usr/src/app/file.txt home/username/Desktop/folder/"
},
{
"code": null,
"e": 2417,
"s": 2319,
"text": "If you want to paste the file in the current directory of you local machine, you can simply use -"
},
{
"code": null,
"e": 2492,
"s": 2417,
"text": "sudo docker cp f4628571q5gc:/usr/src/app/file.txt . (Don’t forget the dot)"
},
{
"code": null,
"e": 2627,
"s": 2492,
"text": "If you want to copy all the files from a particular folder in container, to a folder in the local machine, use the following command -"
},
{
"code": null,
"e": 2699,
"s": 2627,
"text": "sudo docker cp f4628571q5gc:/usr/src/app/ home/username/Desktop/folder/"
},
{
"code": null,
"e": 2801,
"s": 2699,
"text": "If you want to copy a file from your local machine to a container, you can use the following command."
},
{
"code": null,
"e": 2895,
"s": 2801,
"text": "sudo docker cp <Path in the local machine> <Container ID>:<Path of file inside the container>"
},
{
"code": null,
"e": 2908,
"s": 2895,
"text": "For example,"
},
{
"code": null,
"e": 3121,
"s": 2908,
"text": "If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /home/username/Desktop/folder/file.txt in the local machine to /usr/src/app/ in the container, you can use the command -"
},
{
"code": null,
"e": 3202,
"s": 3121,
"text": "sudo docker cp /home/username/Desktop/folder/file.txt f4628571q5gc:/usr/src/app/"
},
{
"code": null,
"e": 3330,
"s": 3202,
"text": "If you want to copy all the files from a folder in your local machine to a folder in the container, use the following command -"
},
{
"code": null,
"e": 3402,
"s": 3330,
"text": "sudo docker cp /home/username/Desktop/folder f4628571q5gc:/usr/src/app/"
},
{
"code": null,
"e": 3599,
"s": 3402,
"text": "To conclude, after you have already built an image with a build context and you want to copy files and folders to and from the container, you can easily do that using the commands mentioned above."
}
] |
base64.b64encode() in Python
|
26 Mar, 2020
With the help of base64.b64encode() method, we can encode the string into the binary form.
Syntax : base64.b64encode(string)
Return : Return the encoded string.
Example #1 :In this example we can see that by using base64.b64encode() method, we are able to get the encoded string which can be in binary form by using this method.
# import base64from base64 import b64encode s = b'GeeksForGeeks'# Using base64.b64encode() methodgfg = b64encode(s) print(gfg)
Output :
b’R2Vla3NGb3JHZWVrcw==’
Example #2 :
# import base64from base64 import b64encode s = b'I love python'# Using base64.b64encode() methodgfg = b64encode(s) print(gfg)
Output :
b’SSBsb3ZlIHB5dGhvbg==’
Python base64-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "With the help of base64.b64encode() method, we can encode the string into the binary form."
},
{
"code": null,
"e": 153,
"s": 119,
"text": "Syntax : base64.b64encode(string)"
},
{
"code": null,
"e": 189,
"s": 153,
"text": "Return : Return the encoded string."
},
{
"code": null,
"e": 357,
"s": 189,
"text": "Example #1 :In this example we can see that by using base64.b64encode() method, we are able to get the encoded string which can be in binary form by using this method."
},
{
"code": "# import base64from base64 import b64encode s = b'GeeksForGeeks'# Using base64.b64encode() methodgfg = b64encode(s) print(gfg)",
"e": 486,
"s": 357,
"text": null
},
{
"code": null,
"e": 495,
"s": 486,
"text": "Output :"
},
{
"code": null,
"e": 519,
"s": 495,
"text": "b’R2Vla3NGb3JHZWVrcw==’"
},
{
"code": null,
"e": 532,
"s": 519,
"text": "Example #2 :"
},
{
"code": "# import base64from base64 import b64encode s = b'I love python'# Using base64.b64encode() methodgfg = b64encode(s) print(gfg)",
"e": 661,
"s": 532,
"text": null
},
{
"code": null,
"e": 670,
"s": 661,
"text": "Output :"
},
{
"code": null,
"e": 694,
"s": 670,
"text": "b’SSBsb3ZlIHB5dGhvbg==’"
},
{
"code": null,
"e": 715,
"s": 694,
"text": "Python base64-module"
},
{
"code": null,
"e": 722,
"s": 715,
"text": "Python"
}
] |
Creating a Vertical Stepper in React
|
20 Sep, 2021
Steppers display progress through a sequence of logical and numbered steps. They may also be used for navigation. Steppers may display a transient feedback message after a step is saved.
In this article we will learn , how to create a vertical stepper using react and material-ui.
Creating React-app
Step 1: Create react app using the following command.
npx create-react-app my-first-app
Step 2: Change directory to that folder by executing command:
cd my-first-app
Step 3: Install the necessary dependencies. Go to the directory ‘src’ and execute command prompt there and run command.
npm install @material-ui/core/Stepper
npm install @material-ui/core/Step
npm install @material-ui/core/StepLabel
Step 4: Run your app by executing below command in src
npm start
File Structure:
File Name: App.js
Importing < GeekStepper/> component in root component
Javascript
function App() { return ( <div className="App"> <GeekStepper /> </div> );} export default App;
File Name: StepperForm.jsx
In this file, we will implement Stepper. In this example; We will explain the process of article publishing in GeeksforGeeks. Articles goes through 3 states
Pending
Review
Publish
Stepper is created using material-ui in react. We have imported different ui-classes in this component like Stepper, StepLabel etc. Stepper is implemented using preActiveStep and ActiveStep . These steps are used to display the component of form which is active and to return back.
Javascript
import React from 'react';import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';import Stepper from '@material-ui/core/Stepper';import Step from '@material-ui/core/Step';import StepLabel from '@material-ui/core/StepLabel';import StepContent from '@material-ui/core/StepContent';import Button from '@material-ui/core/Button';import Paper from '@material-ui/core/Paper';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme: Theme) => createStyles({ root: { width: '100%', }, button: { marginTop: theme.spacing(1), marginRight: theme.spacing(1), }, actionsContainer: { marginBottom: theme.spacing(2), }, resetContainer: { padding: theme.spacing(3), }, }),); function getSteps() { return [<b style={{color:'red'}}>'Pending'</b>, <b style={{color:'orange'}}> 'Review'</b>, <b style={{color:'green'}}>'Published'</b>];} function getStepContent(step: number) { switch (step) { case 0: return `You submit an Article and it goes to Pending state `; case 1: return 'Article is reviewed'; case 2: return `Hey Geek!! Your Article is Published`; default: return 'Unknown step'; }} export default function GeekStepper() { const classes = useStyles(); const [activeStep, setActiveStep] = React.useState(0); const steps = getSteps(); const handleNext = () => { setActiveStep((prevActiveStep) => prevActiveStep + 1); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleReset = () => { setActiveStep(0); }; return ( <div className={classes.root}> <h1>GeeksforGeeks Article Publishing Process</h1> <Stepper activeStep={activeStep} orientation="vertical"> {steps.map((label, index) => ( <Step key={label}> <StepLabel>{label}</StepLabel> <StepContent> <Typography>{getStepContent(index)}</Typography> <div className={classes.actionsContainer}> <div> <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button} > Back </Button> <Button variant="contained" color="primary" onClick={handleNext} className={classes.button} > {activeStep === steps.length - 1 ? 'Finish' : 'Next'} </Button> </div> </div> </StepContent> </Step> ))} </Stepper> {activeStep === steps.length && ( <Paper square elevation={0} className={classes.resetContainer}> <Typography> All steps completed - your Article is Published </Typography> <Button onClick={handleReset} className={classes.button}> Reset </Button> </Paper> )} </div> );}
Step to run the application: Open the terminal and type the following command.
npm start
Output:
Blogathon-2021
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Sep, 2021"
},
{
"code": null,
"e": 215,
"s": 28,
"text": "Steppers display progress through a sequence of logical and numbered steps. They may also be used for navigation. Steppers may display a transient feedback message after a step is saved."
},
{
"code": null,
"e": 309,
"s": 215,
"text": "In this article we will learn , how to create a vertical stepper using react and material-ui."
},
{
"code": null,
"e": 328,
"s": 309,
"text": "Creating React-app"
},
{
"code": null,
"e": 382,
"s": 328,
"text": "Step 1: Create react app using the following command."
},
{
"code": null,
"e": 416,
"s": 382,
"text": "npx create-react-app my-first-app"
},
{
"code": null,
"e": 478,
"s": 416,
"text": "Step 2: Change directory to that folder by executing command:"
},
{
"code": null,
"e": 494,
"s": 478,
"text": "cd my-first-app"
},
{
"code": null,
"e": 616,
"s": 496,
"text": "Step 3: Install the necessary dependencies. Go to the directory ‘src’ and execute command prompt there and run command."
},
{
"code": null,
"e": 729,
"s": 616,
"text": "npm install @material-ui/core/Stepper\nnpm install @material-ui/core/Step\nnpm install @material-ui/core/StepLabel"
},
{
"code": null,
"e": 784,
"s": 729,
"text": "Step 4: Run your app by executing below command in src"
},
{
"code": null,
"e": 794,
"s": 784,
"text": "npm start"
},
{
"code": null,
"e": 810,
"s": 794,
"text": "File Structure:"
},
{
"code": null,
"e": 828,
"s": 810,
"text": "File Name: App.js"
},
{
"code": null,
"e": 882,
"s": 828,
"text": "Importing < GeekStepper/> component in root component"
},
{
"code": null,
"e": 893,
"s": 882,
"text": "Javascript"
},
{
"code": "function App() { return ( <div className=\"App\"> <GeekStepper /> </div> );} export default App;",
"e": 1002,
"s": 893,
"text": null
},
{
"code": null,
"e": 1029,
"s": 1002,
"text": "File Name: StepperForm.jsx"
},
{
"code": null,
"e": 1186,
"s": 1029,
"text": "In this file, we will implement Stepper. In this example; We will explain the process of article publishing in GeeksforGeeks. Articles goes through 3 states"
},
{
"code": null,
"e": 1194,
"s": 1186,
"text": "Pending"
},
{
"code": null,
"e": 1201,
"s": 1194,
"text": "Review"
},
{
"code": null,
"e": 1209,
"s": 1201,
"text": "Publish"
},
{
"code": null,
"e": 1491,
"s": 1209,
"text": "Stepper is created using material-ui in react. We have imported different ui-classes in this component like Stepper, StepLabel etc. Stepper is implemented using preActiveStep and ActiveStep . These steps are used to display the component of form which is active and to return back."
},
{
"code": null,
"e": 1502,
"s": 1491,
"text": "Javascript"
},
{
"code": "import React from 'react';import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';import Stepper from '@material-ui/core/Stepper';import Step from '@material-ui/core/Step';import StepLabel from '@material-ui/core/StepLabel';import StepContent from '@material-ui/core/StepContent';import Button from '@material-ui/core/Button';import Paper from '@material-ui/core/Paper';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme: Theme) => createStyles({ root: { width: '100%', }, button: { marginTop: theme.spacing(1), marginRight: theme.spacing(1), }, actionsContainer: { marginBottom: theme.spacing(2), }, resetContainer: { padding: theme.spacing(3), }, }),); function getSteps() { return [<b style={{color:'red'}}>'Pending'</b>, <b style={{color:'orange'}}> 'Review'</b>, <b style={{color:'green'}}>'Published'</b>];} function getStepContent(step: number) { switch (step) { case 0: return `You submit an Article and it goes to Pending state `; case 1: return 'Article is reviewed'; case 2: return `Hey Geek!! Your Article is Published`; default: return 'Unknown step'; }} export default function GeekStepper() { const classes = useStyles(); const [activeStep, setActiveStep] = React.useState(0); const steps = getSteps(); const handleNext = () => { setActiveStep((prevActiveStep) => prevActiveStep + 1); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleReset = () => { setActiveStep(0); }; return ( <div className={classes.root}> <h1>GeeksforGeeks Article Publishing Process</h1> <Stepper activeStep={activeStep} orientation=\"vertical\"> {steps.map((label, index) => ( <Step key={label}> <StepLabel>{label}</StepLabel> <StepContent> <Typography>{getStepContent(index)}</Typography> <div className={classes.actionsContainer}> <div> <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button} > Back </Button> <Button variant=\"contained\" color=\"primary\" onClick={handleNext} className={classes.button} > {activeStep === steps.length - 1 ? 'Finish' : 'Next'} </Button> </div> </div> </StepContent> </Step> ))} </Stepper> {activeStep === steps.length && ( <Paper square elevation={0} className={classes.resetContainer}> <Typography> All steps completed - your Article is Published </Typography> <Button onClick={handleReset} className={classes.button}> Reset </Button> </Paper> )} </div> );}",
"e": 4566,
"s": 1502,
"text": null
},
{
"code": null,
"e": 4645,
"s": 4566,
"text": "Step to run the application: Open the terminal and type the following command."
},
{
"code": null,
"e": 4655,
"s": 4645,
"text": "npm start"
},
{
"code": null,
"e": 4663,
"s": 4655,
"text": "Output:"
},
{
"code": null,
"e": 4678,
"s": 4663,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 4694,
"s": 4678,
"text": "React-Questions"
},
{
"code": null,
"e": 4704,
"s": 4694,
"text": "Blogathon"
},
{
"code": null,
"e": 4712,
"s": 4704,
"text": "ReactJS"
},
{
"code": null,
"e": 4729,
"s": 4712,
"text": "Web Technologies"
},
{
"code": null,
"e": 4827,
"s": 4729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4868,
"s": 4827,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 4906,
"s": 4868,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 4950,
"s": 4906,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 5010,
"s": 4950,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 5077,
"s": 5010,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 5120,
"s": 5077,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5165,
"s": 5120,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 5203,
"s": 5165,
"text": "Axios in React: A Guide for Beginners"
}
] |
Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and iota)
|
19 Apr, 2018
From C++11 onwards, some new and interesting algorithms are added in STL of C++. These algorithms operate on an array and are useful in saving time during coding and hence useful in competitive programming as well.
all_of()
This function operates on whole range of array elements and can save time to run a loop to check each elements one by one. It checks for a given property on every element and returns true when each element in range satisfies specified property, else returns false.
// C++ code to demonstrate working of all_of()#include<iostream>#include<algorithm> // for all_of()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, -6}; // Checking if all elements are positive all_of(ar, ar+6, [](int x) { return x>0; })? cout << "All are positive elements" : cout << "All are not positive elements"; return 0; }
Output:
All are not positive elements
In the above code, -6 being a negative element negates the condition and returns false.
any_of()
This function checks for a given range if there’s even one element satisfying a given property mentioned in function. Returns true if at least one element satisfies the property else returns false.
// C++ code to demonstrate working of any_of()#include<iostream>#include<algorithm> // for any_of()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, -6}; // Checking if any element is negative any_of(ar, ar+6, [](int x){ return x<0; })? cout << "There exists a negative element" : cout << "All are positive elements"; return 0; }
Output:
There exists a negative element
In above code, -6 makes the condition positive.
none_of()
This function returns true if none of elements satisfies the given condition else returns false.
// C++ code to demonstrate working of none_of()#include<iostream>#include<algorithm> // for none_of()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, 6}; // Checking if no element is negative none_of(ar, ar+6, [](int x){ return x<0; })? cout << "No negative elements" : cout << "There are negative elements"; return 0;}
Output:
No negative elements
Since all elements are positive, the function returns true.
copy_n()
copy_n() copies one array elements to new array. This type of copy creates a deep copy of array. This function takes 3 arguments, source array name, size of array and the target array name.
// C++ code to demonstrate working of copy_n()#include<iostream>#include<algorithm> // for copy_n()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, 6}; // Declaring second array int ar1[6]; // Using copy_n() to copy contents copy_n(ar, 6, ar1); // Displaying the copied array cout << "The new array after copying is : "; for (int i=0; i<6 ; i++) cout << ar1[i] << " "; return 0; }
Output:
The new array after copying is : 1 2 3 4 5 6
In the above code, the elements of ar are copied in ar1 using copy_n()
iota()
This function is used to assign continuous values to array. This function accepts 3 arguments, the array name, size, and the starting number.
// C++ code to demonstrate working of iota()#include<iostream>#include<numeric> // for iota()using namespace std;int main(){ // Initializing array with 0 values int ar[6] = {0}; // Using iota() to assign values iota(ar, ar+6, 20); // Displaying the new array cout << "The new array after assigning values is : "; for (int i=0; i<6 ; i++) cout << ar[i] << " "; return 0; }
Output:
The new array after assigning values is : 20 21 22 23 24 25
In the above code, continuous values are assigned to array using iota().
This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mohitw16
cpp-algorithm-library
cpp-array
CPP-Library
STL
C Language
C++
Competitive Programming
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2018"
},
{
"code": null,
"e": 267,
"s": 52,
"text": "From C++11 onwards, some new and interesting algorithms are added in STL of C++. These algorithms operate on an array and are useful in saving time during coding and hence useful in competitive programming as well."
},
{
"code": null,
"e": 276,
"s": 267,
"text": "all_of()"
},
{
"code": null,
"e": 541,
"s": 276,
"text": "This function operates on whole range of array elements and can save time to run a loop to check each elements one by one. It checks for a given property on every element and returns true when each element in range satisfies specified property, else returns false."
},
{
"code": "// C++ code to demonstrate working of all_of()#include<iostream>#include<algorithm> // for all_of()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, -6}; // Checking if all elements are positive all_of(ar, ar+6, [](int x) { return x>0; })? cout << \"All are positive elements\" : cout << \"All are not positive elements\"; return 0; }",
"e": 943,
"s": 541,
"text": null
},
{
"code": null,
"e": 951,
"s": 943,
"text": "Output:"
},
{
"code": null,
"e": 982,
"s": 951,
"text": "All are not positive elements\n"
},
{
"code": null,
"e": 1070,
"s": 982,
"text": "In the above code, -6 being a negative element negates the condition and returns false."
},
{
"code": null,
"e": 1079,
"s": 1070,
"text": "any_of()"
},
{
"code": null,
"e": 1277,
"s": 1079,
"text": "This function checks for a given range if there’s even one element satisfying a given property mentioned in function. Returns true if at least one element satisfies the property else returns false."
},
{
"code": "// C++ code to demonstrate working of any_of()#include<iostream>#include<algorithm> // for any_of()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, -6}; // Checking if any element is negative any_of(ar, ar+6, [](int x){ return x<0; })? cout << \"There exists a negative element\" : cout << \"All are positive elements\"; return 0; }",
"e": 1678,
"s": 1277,
"text": null
},
{
"code": null,
"e": 1686,
"s": 1678,
"text": "Output:"
},
{
"code": null,
"e": 1719,
"s": 1686,
"text": "There exists a negative element\n"
},
{
"code": null,
"e": 1767,
"s": 1719,
"text": "In above code, -6 makes the condition positive."
},
{
"code": null,
"e": 1777,
"s": 1767,
"text": "none_of()"
},
{
"code": null,
"e": 1874,
"s": 1777,
"text": "This function returns true if none of elements satisfies the given condition else returns false."
},
{
"code": "// C++ code to demonstrate working of none_of()#include<iostream>#include<algorithm> // for none_of()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, 6}; // Checking if no element is negative none_of(ar, ar+6, [](int x){ return x<0; })? cout << \"No negative elements\" : cout << \"There are negative elements\"; return 0;}",
"e": 2265,
"s": 1874,
"text": null
},
{
"code": null,
"e": 2273,
"s": 2265,
"text": "Output:"
},
{
"code": null,
"e": 2295,
"s": 2273,
"text": "No negative elements\n"
},
{
"code": null,
"e": 2355,
"s": 2295,
"text": "Since all elements are positive, the function returns true."
},
{
"code": null,
"e": 2364,
"s": 2355,
"text": "copy_n()"
},
{
"code": null,
"e": 2554,
"s": 2364,
"text": "copy_n() copies one array elements to new array. This type of copy creates a deep copy of array. This function takes 3 arguments, source array name, size of array and the target array name."
},
{
"code": "// C++ code to demonstrate working of copy_n()#include<iostream>#include<algorithm> // for copy_n()using namespace std;int main(){ // Initializing array int ar[6] = {1, 2, 3, 4, 5, 6}; // Declaring second array int ar1[6]; // Using copy_n() to copy contents copy_n(ar, 6, ar1); // Displaying the copied array cout << \"The new array after copying is : \"; for (int i=0; i<6 ; i++) cout << ar1[i] << \" \"; return 0; }",
"e": 3014,
"s": 2554,
"text": null
},
{
"code": null,
"e": 3022,
"s": 3014,
"text": "Output:"
},
{
"code": null,
"e": 3068,
"s": 3022,
"text": "The new array after copying is : 1 2 3 4 5 6\n"
},
{
"code": null,
"e": 3139,
"s": 3068,
"text": "In the above code, the elements of ar are copied in ar1 using copy_n()"
},
{
"code": null,
"e": 3146,
"s": 3139,
"text": "iota()"
},
{
"code": null,
"e": 3288,
"s": 3146,
"text": "This function is used to assign continuous values to array. This function accepts 3 arguments, the array name, size, and the starting number."
},
{
"code": "// C++ code to demonstrate working of iota()#include<iostream>#include<numeric> // for iota()using namespace std;int main(){ // Initializing array with 0 values int ar[6] = {0}; // Using iota() to assign values iota(ar, ar+6, 20); // Displaying the new array cout << \"The new array after assigning values is : \"; for (int i=0; i<6 ; i++) cout << ar[i] << \" \"; return 0; }",
"e": 3698,
"s": 3288,
"text": null
},
{
"code": null,
"e": 3706,
"s": 3698,
"text": "Output:"
},
{
"code": null,
"e": 3767,
"s": 3706,
"text": "The new array after assigning values is : 20 21 22 23 24 25\n"
},
{
"code": null,
"e": 3840,
"s": 3767,
"text": "In the above code, continuous values are assigned to array using iota()."
},
{
"code": null,
"e": 4141,
"s": 3840,
"text": "This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4266,
"s": 4141,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4275,
"s": 4266,
"text": "mohitw16"
},
{
"code": null,
"e": 4297,
"s": 4275,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 4307,
"s": 4297,
"text": "cpp-array"
},
{
"code": null,
"e": 4319,
"s": 4307,
"text": "CPP-Library"
},
{
"code": null,
"e": 4323,
"s": 4319,
"text": "STL"
},
{
"code": null,
"e": 4334,
"s": 4323,
"text": "C Language"
},
{
"code": null,
"e": 4338,
"s": 4334,
"text": "C++"
},
{
"code": null,
"e": 4362,
"s": 4338,
"text": "Competitive Programming"
},
{
"code": null,
"e": 4366,
"s": 4362,
"text": "STL"
},
{
"code": null,
"e": 4370,
"s": 4366,
"text": "CPP"
},
{
"code": null,
"e": 4468,
"s": 4370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4485,
"s": 4468,
"text": "Substring in C++"
},
{
"code": null,
"e": 4507,
"s": 4485,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 4552,
"s": 4507,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4577,
"s": 4552,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4625,
"s": 4577,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 4668,
"s": 4625,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4714,
"s": 4668,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4757,
"s": 4714,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4791,
"s": 4757,
"text": "vector erase() and clear() in C++"
}
] |
HTML Elements
|
30 May, 2022
In this article, we will know the HTML Elements, along with understanding the various available elements & their syntax through the examples. An HTML element is the collection of start and end tags with the content inserted in between them.
Syntax:
<tagname > Contents... </tagname>
Supported Tags: HTML Elements supports almost all HTML Tags.
i) Opening tag: It is used to tell the browser where the content material starts.
ii)Closing tag: It is used to tell the browser where the content material ends.
iii)Content: It is the actual content material inside the opening and closing tag.
Combining all these 3 parts results in an overall HTML Element.
Example:
The entire structure of HTML Element
Example 1: In this example <p> is a starting tag, </p> is an ending tag and it contains some content between the tags, which form an element
HTML
<!DOCTYPE html><html> <head> <title>HTML Elements</title> </head><body> <h2>Welcome To GeeksforGeeks</h2> <p>Hi Geeks!</p> </body> </html>
Output:
HTML elements example
Example 2: This example illustrates the use of the HTML paragraph element.
HTML
<!-- HTML code to illustrate HTML elements --><!DOCTYPE html><html><head> <title>HTML Elements</title></head> <body> <p>Welcome to GeeksforGeeks!</p> </body> </html>
Output:
Welcome to GeeksforGeeks!
Nested HTML Elements: The HTML element is use inside the another HTML Element is called nested HTML elements.
Example 3: This example describes the use of the Nested HTML elements. Here, <html> tag contains the <head> and <body>. The <head> and <body> tag contains another elements so it is called nested element.
HTML
<!DOCTYPE html><html><head> <title>HTML Elements</title></head> <body style="text-align: center"> <h1>GeeksforGeeks</h1> <p>Computer science portal</p> </body> </html>
Output:
Nested HTML element
Necessary to add end tag: It is necessary to add the end tag of an element. Otherwise, the displayed content may or may not be displayed correctly. It is a good practice if you add closing tags to the non-void HTML Elements but nowadays browsers are getting more and more advanced and forgiving in nature and that’s why if you somehow forget to apply the closing tag in the non-void Element, the browser will not throw any error but the problem will arise as you insert more and more HTML elements after that.
Example:
HTML
<!DOCTYPE html><html> <head> <title>HTML Elements</title> </head><body> <h2>Welcome To GeeksforGeeks</h2> <p>Hi Geeks! </body> </html>
This Image is showing the Browser’s Developer Tools and you can see that the missing closing tag of the paragraph element in the above-written code is automatically added by the browser without showing any error.
Developer Tools
The Final Output is:
WebPage
A web browser is forgiving but it doesn’t mean that you start ignoring the ending/closing tag of the HTML elements. It might show some unexpected behaviour or error in some cases. Like if you have more than one HTML element on your webpage then omitting the closing tag might result in clashing of the boundaries of different HTML elements. The browser won’t know where it ends. It will take the next tag and think it belongs to the previous tag without the closing tag.
Final Summary of the above text segment: Always put the closing tag to a non-void HTML element.
Example 4: This example describes the HTML element by specifying the end tag.
HTML
<!DOCTYPE html><html><head> <title>HTML Elements</title></head> <body> <!-- h1 tag contains the end tag --> <h1>GeeksforGeeks</h1> <!-- p tag contains the end tag --> <p>Computer science portal</p> </body></html>
Output:
HTML start & end tag example
Empty HTML Elements: HTML Elements without any content i.e, that do not print anything are called Empty elements. Empty HTML elements do not have an ending tag. For instance. <br>, <hr>, <link>, <input> etc are HTML elements.
Example 5: In this example <br> tag doesn’t print anything. It is used as a line break that breaks the line between <h2> and <p> tag.
HTML
<!DOCTYPE html><html><head> <title>Empty HTML Elements</title></head> <body> <h2>Welcome To GfG</h2> <br /> <p>Hello Geeks.</p> </body></html>
Output:
HTML empty element
shubhamyadav4
bhaskargeeksforgeeks
harsh464565
HTML-Basics
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 294,
"s": 53,
"text": "In this article, we will know the HTML Elements, along with understanding the various available elements & their syntax through the examples. An HTML element is the collection of start and end tags with the content inserted in between them."
},
{
"code": null,
"e": 303,
"s": 294,
"text": "Syntax: "
},
{
"code": null,
"e": 337,
"s": 303,
"text": "<tagname > Contents... </tagname>"
},
{
"code": null,
"e": 398,
"s": 337,
"text": "Supported Tags: HTML Elements supports almost all HTML Tags."
},
{
"code": null,
"e": 480,
"s": 398,
"text": "i) Opening tag: It is used to tell the browser where the content material starts."
},
{
"code": null,
"e": 560,
"s": 480,
"text": "ii)Closing tag: It is used to tell the browser where the content material ends."
},
{
"code": null,
"e": 643,
"s": 560,
"text": "iii)Content: It is the actual content material inside the opening and closing tag."
},
{
"code": null,
"e": 707,
"s": 643,
"text": "Combining all these 3 parts results in an overall HTML Element."
},
{
"code": null,
"e": 716,
"s": 707,
"text": "Example:"
},
{
"code": null,
"e": 753,
"s": 716,
"text": "The entire structure of HTML Element"
},
{
"code": null,
"e": 894,
"s": 753,
"text": "Example 1: In this example <p> is a starting tag, </p> is an ending tag and it contains some content between the tags, which form an element"
},
{
"code": null,
"e": 899,
"s": 894,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML Elements</title> </head><body> <h2>Welcome To GeeksforGeeks</h2> <p>Hi Geeks!</p> </body> </html>",
"e": 1058,
"s": 899,
"text": null
},
{
"code": null,
"e": 1066,
"s": 1058,
"text": "Output:"
},
{
"code": null,
"e": 1088,
"s": 1066,
"text": "HTML elements example"
},
{
"code": null,
"e": 1164,
"s": 1088,
"text": "Example 2: This example illustrates the use of the HTML paragraph element. "
},
{
"code": null,
"e": 1169,
"s": 1164,
"text": "HTML"
},
{
"code": "<!-- HTML code to illustrate HTML elements --><!DOCTYPE html><html><head> <title>HTML Elements</title></head> <body> <p>Welcome to GeeksforGeeks!</p> </body> </html>",
"e": 1344,
"s": 1169,
"text": null
},
{
"code": null,
"e": 1353,
"s": 1344,
"text": "Output: "
},
{
"code": null,
"e": 1379,
"s": 1353,
"text": "Welcome to GeeksforGeeks!"
},
{
"code": null,
"e": 1489,
"s": 1379,
"text": "Nested HTML Elements: The HTML element is use inside the another HTML Element is called nested HTML elements."
},
{
"code": null,
"e": 1693,
"s": 1489,
"text": "Example 3: This example describes the use of the Nested HTML elements. Here, <html> tag contains the <head> and <body>. The <head> and <body> tag contains another elements so it is called nested element."
},
{
"code": null,
"e": 1698,
"s": 1693,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>HTML Elements</title></head> <body style=\"text-align: center\"> <h1>GeeksforGeeks</h1> <p>Computer science portal</p> </body> </html>",
"e": 1878,
"s": 1698,
"text": null
},
{
"code": null,
"e": 1886,
"s": 1878,
"text": "Output:"
},
{
"code": null,
"e": 1906,
"s": 1886,
"text": "Nested HTML element"
},
{
"code": null,
"e": 2416,
"s": 1906,
"text": "Necessary to add end tag: It is necessary to add the end tag of an element. Otherwise, the displayed content may or may not be displayed correctly. It is a good practice if you add closing tags to the non-void HTML Elements but nowadays browsers are getting more and more advanced and forgiving in nature and that’s why if you somehow forget to apply the closing tag in the non-void Element, the browser will not throw any error but the problem will arise as you insert more and more HTML elements after that."
},
{
"code": null,
"e": 2425,
"s": 2416,
"text": "Example:"
},
{
"code": null,
"e": 2430,
"s": 2425,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML Elements</title> </head><body> <h2>Welcome To GeeksforGeeks</h2> <p>Hi Geeks! </body> </html>",
"e": 2584,
"s": 2430,
"text": null
},
{
"code": null,
"e": 2797,
"s": 2584,
"text": "This Image is showing the Browser’s Developer Tools and you can see that the missing closing tag of the paragraph element in the above-written code is automatically added by the browser without showing any error."
},
{
"code": null,
"e": 2813,
"s": 2797,
"text": "Developer Tools"
},
{
"code": null,
"e": 2835,
"s": 2813,
"text": "The Final Output is: "
},
{
"code": null,
"e": 2843,
"s": 2835,
"text": "WebPage"
},
{
"code": null,
"e": 3314,
"s": 2843,
"text": "A web browser is forgiving but it doesn’t mean that you start ignoring the ending/closing tag of the HTML elements. It might show some unexpected behaviour or error in some cases. Like if you have more than one HTML element on your webpage then omitting the closing tag might result in clashing of the boundaries of different HTML elements. The browser won’t know where it ends. It will take the next tag and think it belongs to the previous tag without the closing tag."
},
{
"code": null,
"e": 3410,
"s": 3314,
"text": "Final Summary of the above text segment: Always put the closing tag to a non-void HTML element."
},
{
"code": null,
"e": 3488,
"s": 3410,
"text": "Example 4: This example describes the HTML element by specifying the end tag."
},
{
"code": null,
"e": 3493,
"s": 3488,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>HTML Elements</title></head> <body> <!-- h1 tag contains the end tag --> <h1>GeeksforGeeks</h1> <!-- p tag contains the end tag --> <p>Computer science portal</p> </body></html>",
"e": 3755,
"s": 3493,
"text": null
},
{
"code": null,
"e": 3763,
"s": 3755,
"text": "Output:"
},
{
"code": null,
"e": 3792,
"s": 3763,
"text": "HTML start & end tag example"
},
{
"code": null,
"e": 4018,
"s": 3792,
"text": "Empty HTML Elements: HTML Elements without any content i.e, that do not print anything are called Empty elements. Empty HTML elements do not have an ending tag. For instance. <br>, <hr>, <link>, <input> etc are HTML elements."
},
{
"code": null,
"e": 4152,
"s": 4018,
"text": "Example 5: In this example <br> tag doesn’t print anything. It is used as a line break that breaks the line between <h2> and <p> tag."
},
{
"code": null,
"e": 4157,
"s": 4152,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Empty HTML Elements</title></head> <body> <h2>Welcome To GfG</h2> <br /> <p>Hello Geeks.</p> </body></html>",
"e": 4315,
"s": 4157,
"text": null
},
{
"code": null,
"e": 4323,
"s": 4315,
"text": "Output:"
},
{
"code": null,
"e": 4342,
"s": 4323,
"text": "HTML empty element"
},
{
"code": null,
"e": 4356,
"s": 4342,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 4377,
"s": 4356,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 4389,
"s": 4377,
"text": "harsh464565"
},
{
"code": null,
"e": 4401,
"s": 4389,
"text": "HTML-Basics"
},
{
"code": null,
"e": 4408,
"s": 4401,
"text": "Picked"
},
{
"code": null,
"e": 4413,
"s": 4408,
"text": "HTML"
},
{
"code": null,
"e": 4430,
"s": 4413,
"text": "Web Technologies"
},
{
"code": null,
"e": 4435,
"s": 4430,
"text": "HTML"
},
{
"code": null,
"e": 4533,
"s": 4435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4581,
"s": 4533,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4643,
"s": 4581,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4693,
"s": 4643,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4717,
"s": 4693,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4770,
"s": 4717,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4803,
"s": 4770,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4865,
"s": 4803,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4926,
"s": 4865,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4976,
"s": 4926,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
CLAHE Histogram Equalization – OpenCV
|
09 Nov, 2021
In this tutorial, we are going to see how to apply Contrast Limited Adaptive Histogram Equalization (CLAHE) to equalize images. CLAHE is a variant of Adaptive histogram equalization (AHE) which takes care of over-amplification of the contrast. CLAHE operates on small regions in the image, called tiles, rather than the entire image. The neighboring tiles are then combined using bilinear interpolation to remove the artificial boundaries. This algorithm can be applied to improve the contrast of images.
We can also apply CLAHE to color images, where usually it is applied on the luminance channel and the results after equalizing only the luminance channel of an HSV image are much better than equalizing all the channels of the BGR image. In this tutorial, we are going to learn how to apply CLAHE and process a given input image for histogram equalization.
Parameters :When applying CLAHE, there are two parameters to be remembered:clipLimit – This parameter sets the threshold for contrast limiting. The default value is 40. tileGridSize – This sets the number of tiles in the row and column. By default this is 8×8. It is used while the image is divided into tiles for applying CLAHE.
Code for above:
Python3
import cv2import numpy as np # Reading the image from the present directoryimage = cv2.imread("image.jpg")# Resizing the image for compatibilityimage = cv2.resize(image, (500, 600)) # The initial processing of the image# image = cv2.medianBlur(image, 3)image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # The declaration of CLAHE# clipLimit -> Threshold for contrast limitingclahe = cv2.createCLAHE(clipLimit = 5)final_img = clahe.apply(image_bw) + 30 # Ordinary thresholding the same image_, ordinary_img = cv2.threshold(image_bw, 155, 255, cv2.THRESH_BINARY) # Showing all the three imagescv2.imshow("ordinary threshold", ordinary_img)cv2.imshow("CLAHE image", final_img)
Input image:
input image
Output:
Ordinary Threshold
CLAHE Applied
stevekim121
Image-Processing
OpenCV
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 559,
"s": 54,
"text": "In this tutorial, we are going to see how to apply Contrast Limited Adaptive Histogram Equalization (CLAHE) to equalize images. CLAHE is a variant of Adaptive histogram equalization (AHE) which takes care of over-amplification of the contrast. CLAHE operates on small regions in the image, called tiles, rather than the entire image. The neighboring tiles are then combined using bilinear interpolation to remove the artificial boundaries. This algorithm can be applied to improve the contrast of images."
},
{
"code": null,
"e": 915,
"s": 559,
"text": "We can also apply CLAHE to color images, where usually it is applied on the luminance channel and the results after equalizing only the luminance channel of an HSV image are much better than equalizing all the channels of the BGR image. In this tutorial, we are going to learn how to apply CLAHE and process a given input image for histogram equalization."
},
{
"code": null,
"e": 1247,
"s": 915,
"text": "Parameters :When applying CLAHE, there are two parameters to be remembered:clipLimit – This parameter sets the threshold for contrast limiting. The default value is 40. tileGridSize – This sets the number of tiles in the row and column. By default this is 8×8. It is used while the image is divided into tiles for applying CLAHE. "
},
{
"code": null,
"e": 1264,
"s": 1247,
"text": "Code for above: "
},
{
"code": null,
"e": 1272,
"s": 1264,
"text": "Python3"
},
{
"code": "import cv2import numpy as np # Reading the image from the present directoryimage = cv2.imread(\"image.jpg\")# Resizing the image for compatibilityimage = cv2.resize(image, (500, 600)) # The initial processing of the image# image = cv2.medianBlur(image, 3)image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # The declaration of CLAHE# clipLimit -> Threshold for contrast limitingclahe = cv2.createCLAHE(clipLimit = 5)final_img = clahe.apply(image_bw) + 30 # Ordinary thresholding the same image_, ordinary_img = cv2.threshold(image_bw, 155, 255, cv2.THRESH_BINARY) # Showing all the three imagescv2.imshow(\"ordinary threshold\", ordinary_img)cv2.imshow(\"CLAHE image\", final_img)",
"e": 1947,
"s": 1272,
"text": null
},
{
"code": null,
"e": 1961,
"s": 1947,
"text": "Input image: "
},
{
"code": null,
"e": 1973,
"s": 1961,
"text": "input image"
},
{
"code": null,
"e": 1983,
"s": 1973,
"text": "Output: "
},
{
"code": null,
"e": 2002,
"s": 1983,
"text": "Ordinary Threshold"
},
{
"code": null,
"e": 2016,
"s": 2002,
"text": "CLAHE Applied"
},
{
"code": null,
"e": 2030,
"s": 2018,
"text": "stevekim121"
},
{
"code": null,
"e": 2047,
"s": 2030,
"text": "Image-Processing"
},
{
"code": null,
"e": 2054,
"s": 2047,
"text": "OpenCV"
},
{
"code": null,
"e": 2068,
"s": 2054,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 2075,
"s": 2068,
"text": "Python"
},
{
"code": null,
"e": 2173,
"s": 2075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2191,
"s": 2173,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2233,
"s": 2191,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2281,
"s": 2255,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2313,
"s": 2281,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2342,
"s": 2313,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2369,
"s": 2342,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2390,
"s": 2369,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2413,
"s": 2390,
"text": "Introduction To PYTHON"
}
] |
Placement new operator in C++
|
In this section we will see what is the placement new operator in C++. This placement new is another variation of new operator. The normal new operator performs two things. It allocates memory, and then constructs an object in allocated memory.
The new operator allocates memory in the heap section and constructs objects there. But for the placement new operator, it constructs object at the given address. To deallocate memory, we can use delete keyword if the memory is allocated using new operator. But for placement new there is no placement delete feature.
So in a nutshell, placement new allows you to "construct" an object on memory that's already allocated to a given variable. This is useful for optimizations as it is faster to not reallocate and reuse the same memory that is already assigned to it. It can be used as follows:
new (address) (type) initializer
We can specify an address where we want a new object of given type to be constructed. For example.
Live Demo
#include<iostream>
using namespace std;
int main() {
int a = 5;
cout << "a = " << a << endl;
cout << "&a = " << &a << endl;
// Placement new changes the value of X to 100
int *m = new (&a) int(10);
cout << "\nAfter using placement new:" << endl;
cout << "a = " << a << endl;
cout << "m = " << m << endl;
cout << "&a = " << &a << endl;
return 0;
}
a = 5
&a = 0x22fe34
After using placement new:
a = 10
m = 0x22fe34
&a = 0x22fe34
|
[
{
"code": null,
"e": 1432,
"s": 1187,
"text": "In this section we will see what is the placement new operator in C++. This placement new is another variation of new operator. The normal new operator performs two things. It allocates memory, and then constructs an object in allocated memory."
},
{
"code": null,
"e": 1750,
"s": 1432,
"text": "The new operator allocates memory in the heap section and constructs objects there. But for the placement new operator, it constructs object at the given address. To deallocate memory, we can use delete keyword if the memory is allocated using new operator. But for placement new there is no placement delete feature."
},
{
"code": null,
"e": 2026,
"s": 1750,
"text": "So in a nutshell, placement new allows you to \"construct\" an object on memory that's already allocated to a given variable. This is useful for optimizations as it is faster to not reallocate and reuse the same memory that is already assigned to it. It can be used as follows:"
},
{
"code": null,
"e": 2059,
"s": 2026,
"text": "new (address) (type) initializer"
},
{
"code": null,
"e": 2158,
"s": 2059,
"text": "We can specify an address where we want a new object of given type to be constructed. For example."
},
{
"code": null,
"e": 2169,
"s": 2158,
"text": " Live Demo"
},
{
"code": null,
"e": 2546,
"s": 2169,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int a = 5;\n cout << \"a = \" << a << endl;\n cout << \"&a = \" << &a << endl;\n // Placement new changes the value of X to 100\n int *m = new (&a) int(10);\n cout << \"\\nAfter using placement new:\" << endl;\n cout << \"a = \" << a << endl;\n cout << \"m = \" << m << endl;\n cout << \"&a = \" << &a << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2627,
"s": 2546,
"text": "a = 5\n&a = 0x22fe34\nAfter using placement new:\na = 10\nm = 0x22fe34\n&a = 0x22fe34"
}
] |
How to call loading function with React useEffect?
|
05 Jan, 2021
The useEffect runs by default after every render of the component. When placing useEffect in our component we tell React that we want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.
If we pass only a callback, the callback will run after each render. If we just want to run the useEffect function after the initial render, as a second argument, we can give it an empty array. If we pass a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed.
For example, the callback will run after the first render and after any render that one of varOne or varTwo is changed for the following code:
useEffect(() => console.log('Hi '), [varOne, varTwo])
If we pass the second argument an empty array after each render’s React will compare the array and will see nothing was changed and callback will be called only after the first render.
Syntax:
const MyComponent = (props) {
useEffect(() => {
loadDataOnlyOnce();
}, []);
return <div> {/* jsx code */} </div>;
}
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Filename: App.js
Javascript
import React, { useEffect, useState } from "react"; const App = (props) => { const [btnText, updatebtnText] = useState("") const loadDataOnlyOnce = () => { updatebtnText("Hello kapil") } // This function will called only once useEffect(() => { loadDataOnlyOnce(); }, []) return ( <div style={{ margin: 200 }}> <button onClick={() => updatebtnText("Hi")} > {btnText} </button> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
After clicking button, the text changes
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
JavaScript | fetch() Method
Lodash _.groupBy() Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "The useEffect runs by default after every render of the component. When placing useEffect in our component we tell React that we want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates. "
},
{
"code": null,
"e": 621,
"s": 277,
"text": "If we pass only a callback, the callback will run after each render. If we just want to run the useEffect function after the initial render, as a second argument, we can give it an empty array. If we pass a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. "
},
{
"code": null,
"e": 764,
"s": 621,
"text": "For example, the callback will run after the first render and after any render that one of varOne or varTwo is changed for the following code:"
},
{
"code": null,
"e": 818,
"s": 764,
"text": "useEffect(() => console.log('Hi '), [varOne, varTwo])"
},
{
"code": null,
"e": 1003,
"s": 818,
"text": "If we pass the second argument an empty array after each render’s React will compare the array and will see nothing was changed and callback will be called only after the first render."
},
{
"code": null,
"e": 1011,
"s": 1003,
"text": "Syntax:"
},
{
"code": null,
"e": 1137,
"s": 1011,
"text": "const MyComponent = (props) {\n useEffect(() => {\n loadDataOnlyOnce();\n }, []);\n return <div> {/* jsx code */} </div>;\n}"
},
{
"code": null,
"e": 1165,
"s": 1137,
"text": "Creating React Application:"
},
{
"code": null,
"e": 1229,
"s": 1165,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1261,
"s": 1229,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1361,
"s": 1261,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1375,
"s": 1361,
"text": "cd foldername"
},
{
"code": null,
"e": 1427,
"s": 1375,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1445,
"s": 1427,
"text": "Project Structure"
},
{
"code": null,
"e": 1462,
"s": 1445,
"text": "Filename: App.js"
},
{
"code": null,
"e": 1473,
"s": 1462,
"text": "Javascript"
},
{
"code": "import React, { useEffect, useState } from \"react\"; const App = (props) => { const [btnText, updatebtnText] = useState(\"\") const loadDataOnlyOnce = () => { updatebtnText(\"Hello kapil\") } // This function will called only once useEffect(() => { loadDataOnlyOnce(); }, []) return ( <div style={{ margin: 200 }}> <button onClick={() => updatebtnText(\"Hi\")} > {btnText} </button> </div> );} export default App;",
"e": 1927,
"s": 1473,
"text": null
},
{
"code": null,
"e": 2040,
"s": 1927,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2050,
"s": 2040,
"text": "npm start"
},
{
"code": null,
"e": 2059,
"s": 2050,
"text": "Output: "
},
{
"code": null,
"e": 2099,
"s": 2059,
"text": "After clicking button, the text changes"
},
{
"code": null,
"e": 2106,
"s": 2099,
"text": "Picked"
},
{
"code": null,
"e": 2115,
"s": 2106,
"text": "react-js"
},
{
"code": null,
"e": 2126,
"s": 2115,
"text": "JavaScript"
},
{
"code": null,
"e": 2224,
"s": 2126,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2285,
"s": 2224,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2325,
"s": 2285,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2366,
"s": 2325,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2408,
"s": 2366,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2430,
"s": 2408,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2478,
"s": 2430,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 2505,
"s": 2478,
"text": "Lodash _.debounce() Method"
},
{
"code": null,
"e": 2541,
"s": 2505,
"text": "JavaScript String includes() Method"
},
{
"code": null,
"e": 2569,
"s": 2541,
"text": "JavaScript | fetch() Method"
}
] |
How to display warning before leaving the web page with unsaved changes using JavaScript ?
|
23 Nov, 2020
The onbeforeunload event handler is used for processing beforeunload events. This event is fired whenever a window is about to unload its resources. The result of this event depends on the user selection to proceed or cancel the action. This event can be used to check whether the user has left a form incomplete or unsaved by following this approach.
Every form field on the page is used to update their respective variable by calling a function. These variables are checked whenever beforeunload is fired, thereby checking if the user is trying to leave the page without saving changes. It would not alert the user if the form is empty as the user has not started filling the form.
Syntax:
// Event listener for the 'beforeunload' event
window.addEventListener('beforeunload', function (e) {
// Check if any of the input fields are filled
if (fname !== '' || lname !== '' || subject !== '') {
// Cancel the event and show alert that
// the unsaved changes would be lost
e.preventDefault();
e.returnValue = '';
}
});
Example:
HTML
<!DOCTYPE html><html> <head> <style> .container { border: 2px dotted; width: 60%; border-radius: 5px; padding: 10px; } input, textarea { width: 90%; padding: 10px; margin: 10px; } .submit-btn { background-color: green; color: white; padding: 10px; } </style></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <p> The page will notify if the user has started filling the form and tries to navigate away from it. </p> <div class="container"> <h2>A Demo Contact Form</h2> <form action="#"> <label>First Name</label> <!-- Create all the input boxes and assign there respective functions to update the content in a variable --> <input type="text" id="fname" name="firstname" onchange="updateFname()"> <label>Last Name</label> <input type="text" id="lname" name="lastname" onchange="updateLname()"> <label>Subject</label> <textarea id="subject" name="subject" style="height:100px" onchange="updateSubject()"> </textarea> <button class="submit-btn" onclick="return false;"> Submit </button> </form> </div> <script type="text/javascript"> // Variables to store the input text let fname = ''; let lname = ''; let subject = ''; // Functions to update the input text updateFname = () => { fname = document .getElementById('fname').value; } updateLname = () => { lname = document .getElementById('lname').value; } updateSubject = () => { subject = document .getElementById('subject').value; } // Event listener for the // 'beforeunload' event window.addEventListener('beforeunload', function (e) { // Check if any of the input // fields are filled if (fname !== '' || lname !== '' || subject !== '') { // Cancel the event and // show alert that the unsaved // changes would be lost e.preventDefault(); e.returnValue = ''; } }); </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
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
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 381,
"s": 28,
"text": "The onbeforeunload event handler is used for processing beforeunload events. This event is fired whenever a window is about to unload its resources. The result of this event depends on the user selection to proceed or cancel the action. This event can be used to check whether the user has left a form incomplete or unsaved by following this approach. "
},
{
"code": null,
"e": 713,
"s": 381,
"text": "Every form field on the page is used to update their respective variable by calling a function. These variables are checked whenever beforeunload is fired, thereby checking if the user is trying to leave the page without saving changes. It would not alert the user if the form is empty as the user has not started filling the form."
},
{
"code": null,
"e": 721,
"s": 713,
"text": "Syntax:"
},
{
"code": null,
"e": 1094,
"s": 721,
"text": "// Event listener for the 'beforeunload' event\nwindow.addEventListener('beforeunload', function (e) {\n\n // Check if any of the input fields are filled\n if (fname !== '' || lname !== '' || subject !== '') {\n\n // Cancel the event and show alert that\n // the unsaved changes would be lost\n e.preventDefault();\n e.returnValue = '';\n }\n});\n"
},
{
"code": null,
"e": 1103,
"s": 1094,
"text": "Example:"
},
{
"code": null,
"e": 1108,
"s": 1103,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .container { border: 2px dotted; width: 60%; border-radius: 5px; padding: 10px; } input, textarea { width: 90%; padding: 10px; margin: 10px; } .submit-btn { background-color: green; color: white; padding: 10px; } </style></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> The page will notify if the user has started filling the form and tries to navigate away from it. </p> <div class=\"container\"> <h2>A Demo Contact Form</h2> <form action=\"#\"> <label>First Name</label> <!-- Create all the input boxes and assign there respective functions to update the content in a variable --> <input type=\"text\" id=\"fname\" name=\"firstname\" onchange=\"updateFname()\"> <label>Last Name</label> <input type=\"text\" id=\"lname\" name=\"lastname\" onchange=\"updateLname()\"> <label>Subject</label> <textarea id=\"subject\" name=\"subject\" style=\"height:100px\" onchange=\"updateSubject()\"> </textarea> <button class=\"submit-btn\" onclick=\"return false;\"> Submit </button> </form> </div> <script type=\"text/javascript\"> // Variables to store the input text let fname = ''; let lname = ''; let subject = ''; // Functions to update the input text updateFname = () => { fname = document .getElementById('fname').value; } updateLname = () => { lname = document .getElementById('lname').value; } updateSubject = () => { subject = document .getElementById('subject').value; } // Event listener for the // 'beforeunload' event window.addEventListener('beforeunload', function (e) { // Check if any of the input // fields are filled if (fname !== '' || lname !== '' || subject !== '') { // Cancel the event and // show alert that the unsaved // changes would be lost e.preventDefault(); e.returnValue = ''; } }); </script></body> </html>",
"e": 3753,
"s": 1108,
"text": null
},
{
"code": null,
"e": 3761,
"s": 3753,
"text": "Output:"
},
{
"code": null,
"e": 3770,
"s": 3761,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3780,
"s": 3770,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3796,
"s": 3780,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3803,
"s": 3796,
"text": "Picked"
},
{
"code": null,
"e": 3827,
"s": 3803,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3831,
"s": 3827,
"text": "CSS"
},
{
"code": null,
"e": 3836,
"s": 3831,
"text": "HTML"
},
{
"code": null,
"e": 3847,
"s": 3836,
"text": "JavaScript"
},
{
"code": null,
"e": 3866,
"s": 3847,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3883,
"s": 3866,
"text": "Web Technologies"
},
{
"code": null,
"e": 3888,
"s": 3883,
"text": "HTML"
},
{
"code": null,
"e": 3986,
"s": 3888,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4025,
"s": 3986,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4064,
"s": 4025,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4103,
"s": 4064,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 4140,
"s": 4103,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 4169,
"s": 4140,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 4193,
"s": 4169,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4246,
"s": 4193,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4306,
"s": 4246,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 4367,
"s": 4306,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python | sympy.Matrix().row_insert()
|
25 Jun, 2019
With the help of Matrix().row_insert() method, we can insert a row in a matrix having dimension nxm, where dimension of inserted row is 1xm.
Syntax : Matrix().row_insert()Return : Return a new matrix.
Example #1 :In this example, we are able to insert a row in a matrix by using Matrix().row_insert() method.
# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the row_insert() method for matrixnew_mat = gfg_mat.row_insert(1, Matrix([[3, 4]])) print(new_mat)
Output :
Matrix([[1, 2], [3, 4], [2, 1]])
Example #2 :
# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the row_insert() method for matrixnew_mat = gfg_mat.row_insert(2, Matrix([[13, 24]])) print(new_mat)
Output :
Matrix([[1, 2], [2, 1], [13, 24]])
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "With the help of Matrix().row_insert() method, we can insert a row in a matrix having dimension nxm, where dimension of inserted row is 1xm."
},
{
"code": null,
"e": 229,
"s": 169,
"text": "Syntax : Matrix().row_insert()Return : Return a new matrix."
},
{
"code": null,
"e": 337,
"s": 229,
"text": "Example #1 :In this example, we are able to insert a row in a matrix by using Matrix().row_insert() method."
},
{
"code": "# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the row_insert() method for matrixnew_mat = gfg_mat.row_insert(1, Matrix([[3, 4]])) print(new_mat)",
"e": 551,
"s": 337,
"text": null
},
{
"code": null,
"e": 560,
"s": 551,
"text": "Output :"
},
{
"code": null,
"e": 593,
"s": 560,
"text": "Matrix([[1, 2], [3, 4], [2, 1]])"
},
{
"code": null,
"e": 606,
"s": 593,
"text": "Example #2 :"
},
{
"code": "# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the row_insert() method for matrixnew_mat = gfg_mat.row_insert(2, Matrix([[13, 24]])) print(new_mat)",
"e": 822,
"s": 606,
"text": null
},
{
"code": null,
"e": 831,
"s": 822,
"text": "Output :"
},
{
"code": null,
"e": 866,
"s": 831,
"text": "Matrix([[1, 2], [2, 1], [13, 24]])"
},
{
"code": null,
"e": 872,
"s": 866,
"text": "SymPy"
},
{
"code": null,
"e": 879,
"s": 872,
"text": "Python"
},
{
"code": null,
"e": 977,
"s": 879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1009,
"s": 977,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1036,
"s": 1009,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1057,
"s": 1036,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1080,
"s": 1057,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1136,
"s": 1080,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1178,
"s": 1136,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1209,
"s": 1178,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1251,
"s": 1209,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1290,
"s": 1251,
"text": "Python | Get unique values from a list"
}
] |
How to add a new element to HTML DOM in JavaScript?
|
To add a new element to the HTML DOM, we have to create it first and then we need to append it to the existing element.
1) First, create a div section and add some text to it using <p> tags.
2) Create an element <p> using document.createElement("p").
3) Create a text, using document.createTextNode(), so as to insert it in the above-created element("p").
4) Using appendChild() try to append the created element, along with text, to the existing div tag.
Thus a new element is created(<p>) and appended to the existing element(<div>).
In the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output.
Live Demo
<html>
<body>
<div id="new">
<p id="p1">Tutorix</p>
<p id="p2">Tutorialspoint</p>
</div>
<script>
var tag = document.createElement("p");
var text = document.createTextNode("Tutorix is the best e-learning platform");
tag.appendChild(text);
var element = document.getElementById("new");
element.appendChild(tag);
</script>
</body>
</html>
Tutorix
Tutorialspoint
Tutorix is the best e-learning platform
|
[
{
"code": null,
"e": 1307,
"s": 1187,
"text": "To add a new element to the HTML DOM, we have to create it first and then we need to append it to the existing element."
},
{
"code": null,
"e": 1379,
"s": 1307,
"text": "1) First, create a div section and add some text to it using <p> tags. "
},
{
"code": null,
"e": 1439,
"s": 1379,
"text": "2) Create an element <p> using document.createElement(\"p\")."
},
{
"code": null,
"e": 1544,
"s": 1439,
"text": "3) Create a text, using document.createTextNode(), so as to insert it in the above-created element(\"p\")."
},
{
"code": null,
"e": 1644,
"s": 1544,
"text": "4) Using appendChild() try to append the created element, along with text, to the existing div tag."
},
{
"code": null,
"e": 1724,
"s": 1644,
"text": "Thus a new element is created(<p>) and appended to the existing element(<div>)."
},
{
"code": null,
"e": 1895,
"s": 1724,
"text": "In the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output. "
},
{
"code": null,
"e": 1905,
"s": 1895,
"text": "Live Demo"
},
{
"code": null,
"e": 2257,
"s": 1905,
"text": "<html>\n<body>\n<div id=\"new\">\n<p id=\"p1\">Tutorix</p>\n<p id=\"p2\">Tutorialspoint</p>\n</div>\n<script>\n var tag = document.createElement(\"p\");\n var text = document.createTextNode(\"Tutorix is the best e-learning platform\");\n tag.appendChild(text);\n var element = document.getElementById(\"new\");\n element.appendChild(tag);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2322,
"s": 2257,
"text": "Tutorix\n\nTutorialspoint\n\nTutorix is the best e-learning platform"
}
] |
Python | Create Test DataSets using Sklearn
|
11 Feb, 2022
Python’s Sklearn library provides a great sample dataset generator which will help you to create your own custom dataset. It’s fast and very easy to use. Following are the types of samples it provides.For all the above methods you need to import sklearn.datasets.samples_generator.
Python3
# importing librariesfrom sklearn.datasets import make_blobs # matplotlib for plotingfrom matplotlib import pyplot as pltfrom matplotlib import style
Python3
# Creating Test DataSets using sklearn.datasets.make_blobsfrom sklearn.datasets import make_blobsfrom matplotlib import pyplot as pltfrom matplotlib import style style.use("fivethirtyeight") X, y = make_blobs(n_samples = 100, centers = 3, cluster_std = 1, n_features = 2) plt.scatter(X[:, 0], X[:, 1], s = 40, color = 'g')plt.xlabel("X")plt.ylabel("Y") plt.show()plt.clf()
Output:
make_blobs with 3 centers
Python3
# Creating Test DataSets using sklearn.datasets.make_moonfrom sklearn.datasets import make_moonsfrom matplotlib import pyplot as pltfrom matplotlib import style X, y = make_moons(n_samples = 1000, noise = 0.1)plt.scatter(X[:, 0], X[:, 1], s = 40, color ='g')plt.xlabel("X")plt.ylabel("Y") plt.show()plt.clf()
Output:
make_moons with 1000 data points
Python3
# Creating Test DataSets using sklearn.datasets.make_circlesfrom sklearn.datasets import make_circlesfrom matplotlib import pyplot as pltfrom matplotlib import style style.use("fivethirtyeight") X, y = make_circles(n_samples = 100, noise = 0.02)plt.scatter(X[:, 0], X[:, 1], s = 40, color ='g')plt.xlabel("X")plt.ylabel("Y") plt.show()plt.clf()
Output:
make _circle with 100 data points
acenayeem01
devbrat0srivastava
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Random Forest Regression in Python
ML | Underfitting and Overfitting
ML | Monte Carlo Tree Search (MCTS)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 338,
"s": 54,
"text": "Python’s Sklearn library provides a great sample dataset generator which will help you to create your own custom dataset. It’s fast and very easy to use. Following are the types of samples it provides.For all the above methods you need to import sklearn.datasets.samples_generator. "
},
{
"code": null,
"e": 346,
"s": 338,
"text": "Python3"
},
{
"code": "# importing librariesfrom sklearn.datasets import make_blobs # matplotlib for plotingfrom matplotlib import pyplot as pltfrom matplotlib import style",
"e": 496,
"s": 346,
"text": null
},
{
"code": null,
"e": 504,
"s": 496,
"text": "Python3"
},
{
"code": "# Creating Test DataSets using sklearn.datasets.make_blobsfrom sklearn.datasets import make_blobsfrom matplotlib import pyplot as pltfrom matplotlib import style style.use(\"fivethirtyeight\") X, y = make_blobs(n_samples = 100, centers = 3, cluster_std = 1, n_features = 2) plt.scatter(X[:, 0], X[:, 1], s = 40, color = 'g')plt.xlabel(\"X\")plt.ylabel(\"Y\") plt.show()plt.clf()",
"e": 891,
"s": 504,
"text": null
},
{
"code": null,
"e": 901,
"s": 891,
"text": "Output: "
},
{
"code": null,
"e": 927,
"s": 901,
"text": "make_blobs with 3 centers"
},
{
"code": null,
"e": 939,
"s": 931,
"text": "Python3"
},
{
"code": "# Creating Test DataSets using sklearn.datasets.make_moonfrom sklearn.datasets import make_moonsfrom matplotlib import pyplot as pltfrom matplotlib import style X, y = make_moons(n_samples = 1000, noise = 0.1)plt.scatter(X[:, 0], X[:, 1], s = 40, color ='g')plt.xlabel(\"X\")plt.ylabel(\"Y\") plt.show()plt.clf()",
"e": 1248,
"s": 939,
"text": null
},
{
"code": null,
"e": 1258,
"s": 1248,
"text": "Output: "
},
{
"code": null,
"e": 1291,
"s": 1258,
"text": "make_moons with 1000 data points"
},
{
"code": null,
"e": 1303,
"s": 1295,
"text": "Python3"
},
{
"code": "# Creating Test DataSets using sklearn.datasets.make_circlesfrom sklearn.datasets import make_circlesfrom matplotlib import pyplot as pltfrom matplotlib import style style.use(\"fivethirtyeight\") X, y = make_circles(n_samples = 100, noise = 0.02)plt.scatter(X[:, 0], X[:, 1], s = 40, color ='g')plt.xlabel(\"X\")plt.ylabel(\"Y\") plt.show()plt.clf()",
"e": 1648,
"s": 1303,
"text": null
},
{
"code": null,
"e": 1658,
"s": 1648,
"text": "Output: "
},
{
"code": null,
"e": 1692,
"s": 1658,
"text": "make _circle with 100 data points"
},
{
"code": null,
"e": 1706,
"s": 1694,
"text": "acenayeem01"
},
{
"code": null,
"e": 1725,
"s": 1706,
"text": "devbrat0srivastava"
},
{
"code": null,
"e": 1742,
"s": 1725,
"text": "Machine Learning"
},
{
"code": null,
"e": 1759,
"s": 1742,
"text": "Machine Learning"
},
{
"code": null,
"e": 1857,
"s": 1759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1880,
"s": 1857,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 1903,
"s": 1880,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 1943,
"s": 1903,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 1967,
"s": 1943,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 2005,
"s": 1967,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 2046,
"s": 2005,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 2079,
"s": 2046,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 2114,
"s": 2079,
"text": "Random Forest Regression in Python"
},
{
"code": null,
"e": 2148,
"s": 2114,
"text": "ML | Underfitting and Overfitting"
}
] |
Changing Class Members in Python
|
14 Dec, 2021
In the previous fact, we have seen that Python doesn’t have the static keyword. All variables that are assigned a value in the class declaration are class variables.
We should be careful when changing the value of a class variable. If we try to change a class variable using an object, a new instance (or non-static) variable for that particular object is created and this variable shadows the class variables. Below is a Python program to demonstrate the same.
Python3
# Class for Computer Science Studentclass CSStudent: stream = 'cse' # Class Variable def __init__(self, name, roll): self.name = name self.roll = roll # Driver program to test the functionality# Creating objects of CSStudent classa = CSStudent("Geek", 1)b = CSStudent("Nerd", 2) print ("Initially")print ("a.stream =", a.stream )print ("b.stream =", b.stream ) # This thing doesn't change class(static) variable# Instead creates instance variable for the object# 'a' that shadows class member.a.stream = "ece" print ("\nAfter changing a.stream")print ("a.stream =", a.stream )print ("b.stream =", b.stream )
Output:
Initially
a.stream = cse
b.stream = cse
After changing a.stream
a.stream = ece
b.stream = cse
We should change class variables using class names only.
Python3
# Program to show how to make changes to the# class variable in Python # Class for Computer Science Studentclass CSStudent: stream = 'cse' # Class Variable def __init__(self, name, roll): self.name = name self.roll = roll # New object for further implementationa = CSStudent("check", 3)print "a.stream =", a.stream # Correct way to change the value of class variableCSStudent.stream = "mec"print "\nClass variable changes to mec" # New object for further implementationb = CSStudent("carter", 4) print "\nValue of variable steam for each object"print "a.stream =", a.streamprint "b.stream =", b.stream
Output:
a.stream = cse
Class variable changes to mec
Value of variable steam for each object
a.stream = mec
b.stream = mec
This article is contributed by Nikhil Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
blackmath
ugs18091cseakash
punamsingh628700
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 218,
"s": 52,
"text": "In the previous fact, we have seen that Python doesn’t have the static keyword. All variables that are assigned a value in the class declaration are class variables."
},
{
"code": null,
"e": 514,
"s": 218,
"text": "We should be careful when changing the value of a class variable. If we try to change a class variable using an object, a new instance (or non-static) variable for that particular object is created and this variable shadows the class variables. Below is a Python program to demonstrate the same."
},
{
"code": null,
"e": 522,
"s": 514,
"text": "Python3"
},
{
"code": "# Class for Computer Science Studentclass CSStudent: stream = 'cse' # Class Variable def __init__(self, name, roll): self.name = name self.roll = roll # Driver program to test the functionality# Creating objects of CSStudent classa = CSStudent(\"Geek\", 1)b = CSStudent(\"Nerd\", 2) print (\"Initially\")print (\"a.stream =\", a.stream )print (\"b.stream =\", b.stream ) # This thing doesn't change class(static) variable# Instead creates instance variable for the object# 'a' that shadows class member.a.stream = \"ece\" print (\"\\nAfter changing a.stream\")print (\"a.stream =\", a.stream )print (\"b.stream =\", b.stream )",
"e": 1154,
"s": 522,
"text": null
},
{
"code": null,
"e": 1163,
"s": 1154,
"text": "Output: "
},
{
"code": null,
"e": 1258,
"s": 1163,
"text": "Initially\na.stream = cse\nb.stream = cse\n\nAfter changing a.stream\na.stream = ece\nb.stream = cse"
},
{
"code": null,
"e": 1316,
"s": 1258,
"text": "We should change class variables using class names only. "
},
{
"code": null,
"e": 1324,
"s": 1316,
"text": "Python3"
},
{
"code": "# Program to show how to make changes to the# class variable in Python # Class for Computer Science Studentclass CSStudent: stream = 'cse' # Class Variable def __init__(self, name, roll): self.name = name self.roll = roll # New object for further implementationa = CSStudent(\"check\", 3)print \"a.stream =\", a.stream # Correct way to change the value of class variableCSStudent.stream = \"mec\"print \"\\nClass variable changes to mec\" # New object for further implementationb = CSStudent(\"carter\", 4) print \"\\nValue of variable steam for each object\"print \"a.stream =\", a.streamprint \"b.stream =\", b.stream",
"e": 1950,
"s": 1324,
"text": null
},
{
"code": null,
"e": 1959,
"s": 1950,
"text": "Output: "
},
{
"code": null,
"e": 2076,
"s": 1959,
"text": "a.stream = cse\n\nClass variable changes to mec\n\nValue of variable steam for each object\na.stream = mec\nb.stream = mec"
},
{
"code": null,
"e": 2473,
"s": 2076,
"text": "This article is contributed by Nikhil Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 2483,
"s": 2473,
"text": "blackmath"
},
{
"code": null,
"e": 2500,
"s": 2483,
"text": "ugs18091cseakash"
},
{
"code": null,
"e": 2517,
"s": 2500,
"text": "punamsingh628700"
},
{
"code": null,
"e": 2524,
"s": 2517,
"text": "Python"
}
] |
Minimum and Maximum prime numbers in an array
|
21 May, 2021
Given an array arr[] of N positive integers. The task is to find the minimum and maximum prime elements in the given array. Examples:
Input: arr[] = 1, 3, 4, 5, 7
Output: Minimum : 3
Maximum : 7
Input: arr[] = 1, 2, 3, 4, 5, 6, 7, 11
Output: Minimum : 2
Maximum : 11
Naive Approach: Take a variable min and max. Initialize min with INT_MAX and max with INT_MIN.Traverse the array and keep checking for every element if it is prime or not and update the minimum and maximum prime element at the same time. Efficient Approach: Generate all primes upto maximum element of the array using sieve of Eratosthenes and store them in a hash. Now traverse the array and find the minimum and maximum element which are prime using the hash table.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find minimum and maximum// prime number in given array.#include <bits/stdc++.h>using namespace std; // Function to find count of primevoid prime(int arr[], int n){ // Find maximum value in the array int max_val = *max_element(arr, arr + n); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Minimum and Maximum prime number int minimum = INT_MAX; int maximum = INT_MIN; for (int i = 0; i < n; i++) if (prime[arr[i]]) { minimum = min(minimum, arr[i]); maximum = max(maximum, arr[i]); } cout << "Minimum : " << minimum << endl; cout << "Maximum : " << maximum << endl;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); prime(arr, n); return 0;}
// Java program to find minimum and maximum// prime number in given array.import java.util.*; class GFG { // Function to find count of primestatic void prime(int arr[], int n){ // Find maximum value in the array int max_val = Arrays.stream(arr).max().getAsInt(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. Vector<Boolean> prime = new Vector<Boolean>(); for(int i= 0;i<max_val+1;i++) prime.add(Boolean.TRUE); // Remaining part of SIEVE prime.add(0, Boolean.FALSE); prime.add(1, Boolean.FALSE); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime.get(p) == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.add(i, Boolean.FALSE); } } // Minimum and Maximum prime number int minimum = Integer.MAX_VALUE; int maximum = Integer.MIN_VALUE; for (int i = 0; i < n; i++) if (prime.get(arr[i])) { minimum = Math.min(minimum, arr[i]); maximum = Math.max(maximum, arr[i]); } System.out.println("Minimum : " + minimum) ; System.out.println("Maximum : " + maximum );} // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.length; prime(arr, n); }}/*This code is contributed by 29AjayKumar*/
# Python3 program to find minimum and# maximum prime number in given array.import math as mt # Function to find count of primedef Prime(arr, n): # Find maximum value in the array max_val = max(arr) # USE SIEVE TO FIND ALL PRIME NUMBERS # LESS THAN OR EQUAL TO max_val # Create a boolean array "prime[0..n]". # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True for i in range(max_val + 1)] # Remaining part of SIEVE prime[0] = False prime[1] = False for p in range(2, mt.ceil(mt.sqrt(max_val))): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(2 * p, max_val + 1, p): prime[i] = False # Minimum and Maximum prime number minimum = 10**9 maximum = -10**9 for i in range(n): if (prime[arr[i]] == True): minimum = min(minimum, arr[i]) maximum = max(maximum, arr[i]) print("Minimum : ", minimum ) print("Maximum : ", maximum ) # Driver codearr = [1, 2, 3, 4, 5, 6, 7]n = len(arr) Prime(arr, n) # This code is contributed by# Mohit kumar 29
// A C# program to find minimum and maximum// prime number in given array.using System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to find count of primestatic void prime(int []arr, int n){ // Find maximum value in the array int max_val = arr.Max(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. List<bool>prime = new List<bool>(); for(int i = 0; i < max_val + 1;i++) prime.Add(true); // Remaining part of SIEVE prime.Insert(0, false); prime.Insert(1, false); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.Insert(i, false); } } // Minimum and Maximum prime number int minimum = int.MaxValue; int maximum = int.MinValue; for (int i = 0; i < n; i++) if (prime[arr[i]]) { minimum = Math.Min(minimum, arr[i]); maximum = Math.Max(maximum, arr[i]); } Console.WriteLine("Minimum : " + minimum) ; Console.WriteLine("Maximum : " + maximum );} // Driver code public static void Main() { int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.Length; prime(arr, n); }} /* This code contributed by PrinciRaj1992 */
<script>// Javascript program to find minimum and maximum// prime number in given array. // Function to find count of primefunction prime(arr, n){ // Find maximum value in the array let max_val = arr.sort((b, a) => a - b)[0]; // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = new Array(max_val + 1).fill(true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (let p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Minimum and Maximum prime number let minimum = Number.MAX_SAFE_INTEGER; let maximum = Number.MIN_SAFE_INTEGER; for (let i = 0; i < n; i++) if (prime[arr[i]]) { minimum = Math.min(minimum, arr[i]); maximum = Math.max(maximum, arr[i]); } document.write("Minimum : " + minimum + "<br>"); document.write("Maximum : " + maximum + "<br>");} // Driver code let arr = [1, 2, 3, 4, 5, 6, 7];let n = arr.length; prime(arr, n); // This code is contributed by Saurabh Jaiswal</script>
Minimum : 2
Maximum : 7
Time complexity : O(n*log(log(n)))
29AjayKumar
VishalBachchas
mohit kumar 29
princiraj1992
_saurabh_jaiswal
Prime Number
sieve
Technical Scripter 2018
Arrays
Technical Scripter
Arrays
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way
Introduction to Data Structures
Find Second largest element in an array
Search an element in a sorted and rotated array
Find the Missing Number
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 189,
"s": 53,
"text": "Given an array arr[] of N positive integers. The task is to find the minimum and maximum prime elements in the given array. Examples: "
},
{
"code": null,
"e": 339,
"s": 189,
"text": "Input: arr[] = 1, 3, 4, 5, 7\nOutput: Minimum : 3\n Maximum : 7\n\nInput: arr[] = 1, 2, 3, 4, 5, 6, 7, 11\nOutput: Minimum : 2\n Maximum : 11"
},
{
"code": null,
"e": 857,
"s": 341,
"text": "Naive Approach: Take a variable min and max. Initialize min with INT_MAX and max with INT_MIN.Traverse the array and keep checking for every element if it is prime or not and update the minimum and maximum prime element at the same time. Efficient Approach: Generate all primes upto maximum element of the array using sieve of Eratosthenes and store them in a hash. Now traverse the array and find the minimum and maximum element which are prime using the hash table.Below is the implementation of above approach: "
},
{
"code": null,
"e": 861,
"s": 857,
"text": "C++"
},
{
"code": null,
"e": 866,
"s": 861,
"text": "Java"
},
{
"code": null,
"e": 874,
"s": 866,
"text": "Python3"
},
{
"code": null,
"e": 877,
"s": 874,
"text": "C#"
},
{
"code": null,
"e": 888,
"s": 877,
"text": "Javascript"
},
{
"code": "// CPP program to find minimum and maximum// prime number in given array.#include <bits/stdc++.h>using namespace std; // Function to find count of primevoid prime(int arr[], int n){ // Find maximum value in the array int max_val = *max_element(arr, arr + n); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Minimum and Maximum prime number int minimum = INT_MAX; int maximum = INT_MIN; for (int i = 0; i < n; i++) if (prime[arr[i]]) { minimum = min(minimum, arr[i]); maximum = max(maximum, arr[i]); } cout << \"Minimum : \" << minimum << endl; cout << \"Maximum : \" << maximum << endl;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); prime(arr, n); return 0;}",
"e": 2239,
"s": 888,
"text": null
},
{
"code": "// Java program to find minimum and maximum// prime number in given array.import java.util.*; class GFG { // Function to find count of primestatic void prime(int arr[], int n){ // Find maximum value in the array int max_val = Arrays.stream(arr).max().getAsInt(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. Vector<Boolean> prime = new Vector<Boolean>(); for(int i= 0;i<max_val+1;i++) prime.add(Boolean.TRUE); // Remaining part of SIEVE prime.add(0, Boolean.FALSE); prime.add(1, Boolean.FALSE); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime.get(p) == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.add(i, Boolean.FALSE); } } // Minimum and Maximum prime number int minimum = Integer.MAX_VALUE; int maximum = Integer.MIN_VALUE; for (int i = 0; i < n; i++) if (prime.get(arr[i])) { minimum = Math.min(minimum, arr[i]); maximum = Math.max(maximum, arr[i]); } System.out.println(\"Minimum : \" + minimum) ; System.out.println(\"Maximum : \" + maximum );} // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.length; prime(arr, n); }}/*This code is contributed by 29AjayKumar*/",
"e": 3823,
"s": 2239,
"text": null
},
{
"code": "# Python3 program to find minimum and# maximum prime number in given array.import math as mt # Function to find count of primedef Prime(arr, n): # Find maximum value in the array max_val = max(arr) # USE SIEVE TO FIND ALL PRIME NUMBERS # LESS THAN OR EQUAL TO max_val # Create a boolean array \"prime[0..n]\". # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True for i in range(max_val + 1)] # Remaining part of SIEVE prime[0] = False prime[1] = False for p in range(2, mt.ceil(mt.sqrt(max_val))): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(2 * p, max_val + 1, p): prime[i] = False # Minimum and Maximum prime number minimum = 10**9 maximum = -10**9 for i in range(n): if (prime[arr[i]] == True): minimum = min(minimum, arr[i]) maximum = max(maximum, arr[i]) print(\"Minimum : \", minimum ) print(\"Maximum : \", maximum ) # Driver codearr = [1, 2, 3, 4, 5, 6, 7]n = len(arr) Prime(arr, n) # This code is contributed by# Mohit kumar 29",
"e": 5034,
"s": 3823,
"text": null
},
{
"code": "// A C# program to find minimum and maximum// prime number in given array.using System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to find count of primestatic void prime(int []arr, int n){ // Find maximum value in the array int max_val = arr.Max(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. List<bool>prime = new List<bool>(); for(int i = 0; i < max_val + 1;i++) prime.Add(true); // Remaining part of SIEVE prime.Insert(0, false); prime.Insert(1, false); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.Insert(i, false); } } // Minimum and Maximum prime number int minimum = int.MaxValue; int maximum = int.MinValue; for (int i = 0; i < n; i++) if (prime[arr[i]]) { minimum = Math.Min(minimum, arr[i]); maximum = Math.Max(maximum, arr[i]); } Console.WriteLine(\"Minimum : \" + minimum) ; Console.WriteLine(\"Maximum : \" + maximum );} // Driver code public static void Main() { int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.Length; prime(arr, n); }} /* This code contributed by PrinciRaj1992 */",
"e": 6609,
"s": 5034,
"text": null
},
{
"code": "<script>// Javascript program to find minimum and maximum// prime number in given array. // Function to find count of primefunction prime(arr, n){ // Find maximum value in the array let max_val = arr.sort((b, a) => a - b)[0]; // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = new Array(max_val + 1).fill(true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (let p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Minimum and Maximum prime number let minimum = Number.MAX_SAFE_INTEGER; let maximum = Number.MIN_SAFE_INTEGER; for (let i = 0; i < n; i++) if (prime[arr[i]]) { minimum = Math.min(minimum, arr[i]); maximum = Math.max(maximum, arr[i]); } document.write(\"Minimum : \" + minimum + \"<br>\"); document.write(\"Maximum : \" + maximum + \"<br>\");} // Driver code let arr = [1, 2, 3, 4, 5, 6, 7];let n = arr.length; prime(arr, n); // This code is contributed by Saurabh Jaiswal</script>",
"e": 7989,
"s": 6609,
"text": null
},
{
"code": null,
"e": 8013,
"s": 7989,
"text": "Minimum : 2\nMaximum : 7"
},
{
"code": null,
"e": 8051,
"s": 8015,
"text": "Time complexity : O(n*log(log(n))) "
},
{
"code": null,
"e": 8063,
"s": 8051,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8078,
"s": 8063,
"text": "VishalBachchas"
},
{
"code": null,
"e": 8093,
"s": 8078,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8107,
"s": 8093,
"text": "princiraj1992"
},
{
"code": null,
"e": 8124,
"s": 8107,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 8137,
"s": 8124,
"text": "Prime Number"
},
{
"code": null,
"e": 8143,
"s": 8137,
"text": "sieve"
},
{
"code": null,
"e": 8167,
"s": 8143,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 8174,
"s": 8167,
"text": "Arrays"
},
{
"code": null,
"e": 8193,
"s": 8174,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8200,
"s": 8193,
"text": "Arrays"
},
{
"code": null,
"e": 8213,
"s": 8200,
"text": "Prime Number"
},
{
"code": null,
"e": 8219,
"s": 8213,
"text": "sieve"
},
{
"code": null,
"e": 8317,
"s": 8219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8349,
"s": 8317,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8372,
"s": 8349,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 8457,
"s": 8372,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 8513,
"s": 8457,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 8540,
"s": 8513,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 8585,
"s": 8540,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 8617,
"s": 8585,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8657,
"s": 8617,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 8705,
"s": 8657,
"text": "Search an element in a sorted and rotated array"
}
] |
Tryit Editor v3.7
|
HTML Web Storage
Tryit: HTML local storage
|
[
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Web Storage"
}
] |
How to check if a "lateInit" variable has been initialized in Kotlin?
|
Any variable which is initialized after its declaration is known as a "late
initialized variable". In conventional programming languages, any non-NULL
type of variable need to be initialized in the constructor. But sometimes, by
mistake, developers forget to do these NULL checks which causes a
programming error. In order to avoid this situation, Kotlin introduced a new
modifier called as "lateInit". Along with this modifier, Kotlin provides a couple of methods to check whether this variable is initialized or not.
In order to create a "lateInit" variable, we just need to add the keyword
"lateInit" as an access modifier of that variable. Following are the couple of
conditions that need to be followed in order to use "lateInit" in Kotlin −
Use "lateInit" with a mutable variable. That means, we need use "var" keyword with "lateInit".
Use "lateInit" with a mutable variable. That means, we need use "var" keyword with "lateInit".
"lateInit" is only allowed with non-NULLable data types.
"lateInit" is only allowed with non-NULLable data types.
"lateInit" does not work with primitive data types.
"lateInit" does not work with primitive data types.
"lateInit" can be used when the variable property does not have any getter and setter methods.
"lateInit" can be used when the variable property does not have any getter and setter methods.
In this example, we will declare a variable as a "lateInit" variable and we will be using our Kotlin library function to check whether the variable is initialized or not.
class Tutorial {
lateinit var name : String
fun checkLateInit(){
println(this::name.isInitialized)
// it will print false as the value is not initialized
// initializing name
name = "www.tutorialspoint.com/"
println(this::name.isInitialized)
// It will return true
}
}
fun main() {
var obj=Tutorial();
obj.checkLateInit();
}
Once you execute the code, it will generate the following output −
false
true
In the second case, the variable name is initialized, hence it returns True.
|
[
{
"code": null,
"e": 1581,
"s": 1062,
"text": "Any variable which is initialized after its declaration is known as a \"late\ninitialized variable\". In conventional programming languages, any non-NULL\ntype of variable need to be initialized in the constructor. But sometimes, by\nmistake, developers forget to do these NULL checks which causes a\nprogramming error. In order to avoid this situation, Kotlin introduced a new\nmodifier called as \"lateInit\". Along with this modifier, Kotlin provides a couple of methods to check whether this variable is initialized or not."
},
{
"code": null,
"e": 1809,
"s": 1581,
"text": "In order to create a \"lateInit\" variable, we just need to add the keyword\n\"lateInit\" as an access modifier of that variable. Following are the couple of\nconditions that need to be followed in order to use \"lateInit\" in Kotlin −"
},
{
"code": null,
"e": 1904,
"s": 1809,
"text": "Use \"lateInit\" with a mutable variable. That means, we need use \"var\" keyword with \"lateInit\"."
},
{
"code": null,
"e": 1999,
"s": 1904,
"text": "Use \"lateInit\" with a mutable variable. That means, we need use \"var\" keyword with \"lateInit\"."
},
{
"code": null,
"e": 2056,
"s": 1999,
"text": "\"lateInit\" is only allowed with non-NULLable data types."
},
{
"code": null,
"e": 2113,
"s": 2056,
"text": "\"lateInit\" is only allowed with non-NULLable data types."
},
{
"code": null,
"e": 2165,
"s": 2113,
"text": "\"lateInit\" does not work with primitive data types."
},
{
"code": null,
"e": 2217,
"s": 2165,
"text": "\"lateInit\" does not work with primitive data types."
},
{
"code": null,
"e": 2312,
"s": 2217,
"text": "\"lateInit\" can be used when the variable property does not have any getter and setter methods."
},
{
"code": null,
"e": 2407,
"s": 2312,
"text": "\"lateInit\" can be used when the variable property does not have any getter and setter methods."
},
{
"code": null,
"e": 2578,
"s": 2407,
"text": "In this example, we will declare a variable as a \"lateInit\" variable and we will be using our Kotlin library function to check whether the variable is initialized or not."
},
{
"code": null,
"e": 2958,
"s": 2578,
"text": "class Tutorial {\n\n lateinit var name : String\n\n fun checkLateInit(){\n println(this::name.isInitialized)\n // it will print false as the value is not initialized\n\n // initializing name\n name = \"www.tutorialspoint.com/\"\n println(this::name.isInitialized)\n // It will return true\n }\n}\n\nfun main() {\n var obj=Tutorial();\n obj.checkLateInit();\n}"
},
{
"code": null,
"e": 3025,
"s": 2958,
"text": "Once you execute the code, it will generate the following output −"
},
{
"code": null,
"e": 3036,
"s": 3025,
"text": "false\ntrue"
},
{
"code": null,
"e": 3113,
"s": 3036,
"text": "In the second case, the variable name is initialized, hence it returns True."
}
] |
Flex - RadioButton Control
|
The RadioButton control allows the user make a single choice within a set of mutually exclusive choices.
Following is the declaration for spark.components.RadioButton class −
public class RadioButton
extends ToggleButtonBase
implements IFocusManagerGroup
enabled : Boolean
[override] The RadioButton component is enabled if the RadioButtonGroup is enabled and the RadioButton itself is enabled.
group : RadioButtonGroup
The RadioButtonGroup component to which this RadioButton belongs.
groupName : String
Specifies the name of the group to which this RadioButton component belongs, or specifies the value of the id property of a RadioButtonGroup component if this RadioButton is part of a group defined by a RadioButtonGroup component.
value : Object
Optional user-defined value that is associated with a RadioButton component.
RadioButton()
Constructor.
This class inherits methods from the following classes −
spark.components.supportClasses.ToggleButtonBase
spark.components.supportClasses.ButtonBase
spark.components.supportClasses.SkinnableComponent
mx.core.UIComponent
mx.core.FlexSprite
flash.display.Sprite
flash.display.DisplayObjectContainer
flash.display.InteractiveObject
flash.display.DisplayObject
flash.events.EventDispatcher
Object
Let us follow the following steps to check usage of RadioButton control in a Flex application by creating a test application −
Following is the content of the modified mxml file src/com.tutorialspoint/HelloWorld.mxml.
<?xml version = "1.0" encoding = "utf-8"?>
<s:Application xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx"
width = "100%" height = "100%" minWidth = "500" minHeight = "500">
<fx:Style source = "/com/tutorialspoint/client/Style.css" />
<fx:Script>
<![CDATA[
[Bindable]
private var selectedOption:String = "";
protected function option_clickHandler(event:MouseEvent):void {
var radioButton:RadioButton = event.target as RadioButton;
switch (radioButton.id) {
case option1.id:
selectedOption = option1.label;
break;
case option2.id:
selectedOption = option2.label;
break;
case option3.id:
selectedOption = option3.label;
break;
case option4.id:
selectedOption = option4.label;
break;
}
}
]]>
</fx:Script>
<s:BorderContainer width = "550" height = "400" id = "mainContainer"
styleName = "container">
<s:VGroup width = "100%" height = "100%" gap = "50"
horizontalAlign = "center" verticalAlign = "middle">
<s:Label id = "lblHeader" text = "Form Controls Demonstration"
fontSize = "40" color = "0x777777" styleName = "heading" />
<s:Panel id = "radioButtonPanel" title = "Using RadioButton"
width = "420" height = "200" >
<s:layout>
<s:VerticalLayout gap = "10" verticalAlign = "middle"
horizontalAlign = "center" />
</s:layout>
<s:RadioButton groupName = "options" id = "option1"
label = "item #1" width="150"
click = "option_clickHandler(event)" />
<s:RadioButton groupName = "options" id = "option2"
label = "item #2" width="150"
click = "option_clickHandler(event)" />
<s:RadioButton groupName = "options" id = "option3"
label = "item #3" width="150"
click = "option_clickHandler(event)" />
<s:RadioButton groupName = "options" id = "option4"
label = "item #4" width = "150"
click = "option_clickHandler(event)" />
<s:Label id = "selectedOptionLabel" fontWeight = "bold"
text = "Item selected: {selectedOption}" width = "150" />
</s:Panel>
</s:VGroup>
</s:BorderContainer>
</s:Application>
Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, it will produce the following result: [ Try it online ]
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
12 Lectures
1 hours
Prof. Paul Cline, Ed.D
87 Lectures
11 hours
Code And Create
30 Lectures
1 hours
Faigy Liebermann
11 Lectures
1.5 hours
Prof Krishna N Sharma
32 Lectures
34 mins
Prof Krishna N Sharma
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2152,
"s": 2047,
"text": "The RadioButton control allows the user make a single choice within a set of mutually exclusive choices."
},
{
"code": null,
"e": 2222,
"s": 2152,
"text": "Following is the declaration for spark.components.RadioButton class −"
},
{
"code": null,
"e": 2312,
"s": 2222,
"text": "public class RadioButton \n extends ToggleButtonBase\n implements IFocusManagerGroup"
},
{
"code": null,
"e": 2330,
"s": 2312,
"text": "enabled : Boolean"
},
{
"code": null,
"e": 2452,
"s": 2330,
"text": "[override] The RadioButton component is enabled if the RadioButtonGroup is enabled and the RadioButton itself is enabled."
},
{
"code": null,
"e": 2477,
"s": 2452,
"text": "group : RadioButtonGroup"
},
{
"code": null,
"e": 2543,
"s": 2477,
"text": "The RadioButtonGroup component to which this RadioButton belongs."
},
{
"code": null,
"e": 2562,
"s": 2543,
"text": "groupName : String"
},
{
"code": null,
"e": 2793,
"s": 2562,
"text": "Specifies the name of the group to which this RadioButton component belongs, or specifies the value of the id property of a RadioButtonGroup component if this RadioButton is part of a group defined by a RadioButtonGroup component."
},
{
"code": null,
"e": 2808,
"s": 2793,
"text": "value : Object"
},
{
"code": null,
"e": 2885,
"s": 2808,
"text": "Optional user-defined value that is associated with a RadioButton component."
},
{
"code": null,
"e": 2899,
"s": 2885,
"text": "RadioButton()"
},
{
"code": null,
"e": 2912,
"s": 2899,
"text": "Constructor."
},
{
"code": null,
"e": 2969,
"s": 2912,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 3018,
"s": 2969,
"text": "spark.components.supportClasses.ToggleButtonBase"
},
{
"code": null,
"e": 3061,
"s": 3018,
"text": "spark.components.supportClasses.ButtonBase"
},
{
"code": null,
"e": 3112,
"s": 3061,
"text": "spark.components.supportClasses.SkinnableComponent"
},
{
"code": null,
"e": 3132,
"s": 3112,
"text": "mx.core.UIComponent"
},
{
"code": null,
"e": 3151,
"s": 3132,
"text": "mx.core.FlexSprite"
},
{
"code": null,
"e": 3172,
"s": 3151,
"text": "flash.display.Sprite"
},
{
"code": null,
"e": 3209,
"s": 3172,
"text": "flash.display.DisplayObjectContainer"
},
{
"code": null,
"e": 3241,
"s": 3209,
"text": "flash.display.InteractiveObject"
},
{
"code": null,
"e": 3269,
"s": 3241,
"text": "flash.display.DisplayObject"
},
{
"code": null,
"e": 3298,
"s": 3269,
"text": "flash.events.EventDispatcher"
},
{
"code": null,
"e": 3305,
"s": 3298,
"text": "Object"
},
{
"code": null,
"e": 3432,
"s": 3305,
"text": "Let us follow the following steps to check usage of RadioButton control in a Flex application by creating a test application −"
},
{
"code": null,
"e": 3523,
"s": 3432,
"text": "Following is the content of the modified mxml file src/com.tutorialspoint/HelloWorld.mxml."
},
{
"code": null,
"e": 6189,
"s": 3523,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<s:Application xmlns:fx = \"http://ns.adobe.com/mxml/2009\"\n xmlns:s = \"library://ns.adobe.com/flex/spark\"\n xmlns:mx = \"library://ns.adobe.com/flex/mx\"\n width = \"100%\" height = \"100%\" minWidth = \"500\" minHeight = \"500\">\n \n <fx:Style source = \"/com/tutorialspoint/client/Style.css\" />\n <fx:Script>\n <![CDATA[\n [Bindable]\n private var selectedOption:String = \"\";\n protected function option_clickHandler(event:MouseEvent):void {\n var radioButton:RadioButton = event.target as RadioButton;\n switch (radioButton.id) {\n case option1.id:\n selectedOption = option1.label;\n break;\n case option2.id:\n selectedOption = option2.label;\n break;\n case option3.id:\n selectedOption = option3.label;\n break;\n case option4.id:\n selectedOption = option4.label;\n break;\n }\t\t\t\n }\n ]]>\n </fx:Script>\n \n <s:BorderContainer width = \"550\" height = \"400\" id = \"mainContainer\" \n styleName = \"container\">\n <s:VGroup width = \"100%\" height = \"100%\" gap = \"50\" \n horizontalAlign = \"center\" verticalAlign = \"middle\">\n <s:Label id = \"lblHeader\" text = \"Form Controls Demonstration\" \n fontSize = \"40\" color = \"0x777777\" styleName = \"heading\" />\n \n <s:Panel id = \"radioButtonPanel\" title = \"Using RadioButton\" \n width = \"420\" height = \"200\" >\n <s:layout>\n <s:VerticalLayout gap = \"10\" verticalAlign = \"middle\"\n horizontalAlign = \"center\" />\t\n </s:layout>\n \n <s:RadioButton groupName = \"options\" id = \"option1\" \n label = \"item #1\" width=\"150\" \n click = \"option_clickHandler(event)\" />\n <s:RadioButton groupName = \"options\" id = \"option2\" \n label = \"item #2\" width=\"150\" \n click = \"option_clickHandler(event)\" />\n <s:RadioButton groupName = \"options\" id = \"option3\" \n label = \"item #3\" width=\"150\" \n click = \"option_clickHandler(event)\" />\n <s:RadioButton groupName = \"options\" id = \"option4\" \n label = \"item #4\" width = \"150\" \n click = \"option_clickHandler(event)\" />\n <s:Label id = \"selectedOptionLabel\" fontWeight = \"bold\" \n text = \"Item selected: {selectedOption}\" width = \"150\" />\n </s:Panel>\n </s:VGroup>\t \n </s:BorderContainer>\t\n</s:Application>"
},
{
"code": null,
"e": 6438,
"s": 6189,
"text": "Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, it will produce the following result: [ Try it online ]"
},
{
"code": null,
"e": 6473,
"s": 6438,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6504,
"s": 6473,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6537,
"s": 6504,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6561,
"s": 6537,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 6595,
"s": 6561,
"text": "\n 87 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6612,
"s": 6595,
"text": " Code And Create"
},
{
"code": null,
"e": 6645,
"s": 6612,
"text": "\n 30 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6663,
"s": 6645,
"text": " Faigy Liebermann"
},
{
"code": null,
"e": 6698,
"s": 6663,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6721,
"s": 6698,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 6753,
"s": 6721,
"text": "\n 32 Lectures \n 34 mins\n"
},
{
"code": null,
"e": 6776,
"s": 6753,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 6783,
"s": 6776,
"text": " Print"
},
{
"code": null,
"e": 6794,
"s": 6783,
"text": " Add Notes"
}
] |
The Best Exploratory Data Analysis with Pandas Profiling | by Matt Przybyla | Towards Data Science
|
IntroductionOverviewVariablesInteractionsCorrelationsMissing ValuesSampleSummaryReferences
Introduction
Overview
Variables
Interactions
Correlations
Missing Values
Sample
Summary
References
There are countless ways to perform exploratory data analysis (EDA) in Python (and in R). I do most of mine in the popular Jupyter Notebook. Once I realized there was a library that could summarize my dataset with just one line of code, I made sure to utilize it for every project, reaping countless benefits from the ease of this EDA tool. The EDA step should be performed first before executing any Machine Learning models for all Data Scientists, therefore, the kind and intelligent developers from Pandas Profiling [2] have made it easy to view your dataset in a beautiful format, while also describing the information well in your dataset.
The Pandas Profiling report serves as this excellent EDA tool that can offer the following benefits: overview, variables, interactions, correlations, missing values, and a sample of your data. I will be using randomly generated data to serve as an example of this useful tool.
The overview tab in the report provides a quick glance at how many variables and observations you have or the number of rows and columns. It will also perform a calculation to see how many of your missing cells there are compared to the whole dataframe column. Additionally, it will point out duplicate rows as well and calculate that percentage. This tab is most similar to part of the describe function from Pandas, while providing a better user-interface (UI) experience.
The overview is broken into dataset statistics and variable types. You can also refer to warnings and reproduction for more specific information on your data.
I will be discussing variables, which are also referred to as columns or features of your dataframe
To achieve more granularity in your descriptive statistics, the variables tab is the way to go. You can look at distinct, missing, aggregations or calculations like mean, min, and max of your dataframe features or variables. You can also see the type of data you are working with (i.e., NUM). Not pictured is when you click on ‘Toggle details’. This toggle prompts a whole plethora of more usable statistics. The details include:
Statistics — quantile and descriptive
quantile
Minimum5th percentileQ1MedianQ395th percentileMaximumRangeInterquartile range (IQR)
descriptive
Standard deviationCoefficient of variation (CV)KurtosisMeanMedian Absolute Deviation (MAD)SkewnessSumVarianceMonotonicity
These statistics also provide similar information from the describe function I see most Data Scientists using today, however, there are a few more and it presents them in an easy-to-view format.
Histograms
The histograms provide for an easily digestible visual of your variables. You can expect to see the frequency of your variable on the y-axis and fixed-size bins (bins=15 is the default) on the x-axis.
Common Values
The common values will provide the value, count, and frequency that are most common for your variable.
Extreme Values
The extreme values will provide the value, count, and frequency that are in the minimum and maximum values of your dataframe.
The interactions feature of the profiling report is unique in that you can choose from your list of columns to either be on the x-axis or y-xis provided. For example, pictured above is variable A against variable A, which is why you see overlapping. You can easily switch to other variables or columns to achieve a different plot and an excellent representation of your data points.
Sometimes making fancier or colorful correlation plots can be time-consuming if you make them from line-by-line Python code. However, with this correlation plot, you can easily visualize the relationships between variables in your data, which are also nicely color-coded. There are four main plots that you can display:
Pearson’s r
Spearman’s ρ
Kendall’s τ
Phik (φk)
You may only be used to one of these correlation methods, so the other ones may sound confusing or not usable. Therefore, the correlation plot also comes provided with a toggle for details onto the meaning of each correlation you can visualize — this feature really helps when you need a refresher on correlation, as well as when you are deciding between which plot(s) to use for your analysis
As you can see from the plot above, the report tool also includes missing values. You can see how much of each variable is missing, including the count, and matrix. It is a nice way to visualize your data before you perform any models with it. You would preferably want to see a plot like the above, meaning you have no missing values.
Sample acts similarly to the head and tail function where it returns your dataframe’s first few rows or last rows. In this example, you can see the first rows and last rows as well. I use this tab when I want a sense of where my data started and where it ended — I recommend ranking or ordering to see more benefit out of this tab, as you can see the range of your data, with a visual respective representation.
I hope this article provided you with some inspiration for your next exploratory data analysis. Being a Data Scientist can be overwhelming and EDA is often forgotten or not practiced as much as model-building. With the Pandas Profiling report, you can perform EDA with minimal code, providing useful statistics and visualizes as well. That way, you can focus on the fun part of Data Science and Machine Learning, the model process.
To summarize, the main features of Pandas Profiling report include overview, variables, interactions, correlations, missing values, and a sample of your data.
Here is the code I used to install and import libraries, as well as to generate some dummy data for the example, and finally, the one line of code used to generate the Pandas Profile report based on your Pandas dataframe [10].
# install library #!pip install pandas_profilingimport pandas_profilingimport pandas as pdimport numpy as np# create data df = pd.DataFrame(np.random.randint(0,200,size=(15, 6)), columns=list('ABCDEF'))# run your report!df.profile_report()# I did get an error and had to reinstall matplotlib to fix
Please feel free to comment down below if you have any questions or have used this feature before. There is still some information I did not describe, but you can find more of that information on the link I provided from above.
Thank you for reading, I hope you enjoyed!
[1] M.Przybyla, Screenshot of Pandas Profile Report correlations example, (2020)
[2] pandas-profiling, GitHub for documentation and all contributors, (2020)
[3] M.Przybyla, Screenshot of Overview example, (2020)
[4] M.Przybyla, Screenshot of Variables example, (2020)
[5] M.Przybyla, Screenshot of Interactions example, (2020)
[6] M.Przybyla, Screenshot of Correlations example, (2020)
[7] M.Przybyla, Screenshot of Missing Values example, (2020)
[8] M.Przybyla, Screenshot of Sample example, (2020)
[9] Photo by Elena Loshina on Unsplash, (2018)
[1] M.Przybyla, Pandas Profile report code from example, (2020)
|
[
{
"code": null,
"e": 262,
"s": 171,
"text": "IntroductionOverviewVariablesInteractionsCorrelationsMissing ValuesSampleSummaryReferences"
},
{
"code": null,
"e": 275,
"s": 262,
"text": "Introduction"
},
{
"code": null,
"e": 284,
"s": 275,
"text": "Overview"
},
{
"code": null,
"e": 294,
"s": 284,
"text": "Variables"
},
{
"code": null,
"e": 307,
"s": 294,
"text": "Interactions"
},
{
"code": null,
"e": 320,
"s": 307,
"text": "Correlations"
},
{
"code": null,
"e": 335,
"s": 320,
"text": "Missing Values"
},
{
"code": null,
"e": 342,
"s": 335,
"text": "Sample"
},
{
"code": null,
"e": 350,
"s": 342,
"text": "Summary"
},
{
"code": null,
"e": 361,
"s": 350,
"text": "References"
},
{
"code": null,
"e": 1006,
"s": 361,
"text": "There are countless ways to perform exploratory data analysis (EDA) in Python (and in R). I do most of mine in the popular Jupyter Notebook. Once I realized there was a library that could summarize my dataset with just one line of code, I made sure to utilize it for every project, reaping countless benefits from the ease of this EDA tool. The EDA step should be performed first before executing any Machine Learning models for all Data Scientists, therefore, the kind and intelligent developers from Pandas Profiling [2] have made it easy to view your dataset in a beautiful format, while also describing the information well in your dataset."
},
{
"code": null,
"e": 1283,
"s": 1006,
"text": "The Pandas Profiling report serves as this excellent EDA tool that can offer the following benefits: overview, variables, interactions, correlations, missing values, and a sample of your data. I will be using randomly generated data to serve as an example of this useful tool."
},
{
"code": null,
"e": 1758,
"s": 1283,
"text": "The overview tab in the report provides a quick glance at how many variables and observations you have or the number of rows and columns. It will also perform a calculation to see how many of your missing cells there are compared to the whole dataframe column. Additionally, it will point out duplicate rows as well and calculate that percentage. This tab is most similar to part of the describe function from Pandas, while providing a better user-interface (UI) experience."
},
{
"code": null,
"e": 1917,
"s": 1758,
"text": "The overview is broken into dataset statistics and variable types. You can also refer to warnings and reproduction for more specific information on your data."
},
{
"code": null,
"e": 2017,
"s": 1917,
"text": "I will be discussing variables, which are also referred to as columns or features of your dataframe"
},
{
"code": null,
"e": 2447,
"s": 2017,
"text": "To achieve more granularity in your descriptive statistics, the variables tab is the way to go. You can look at distinct, missing, aggregations or calculations like mean, min, and max of your dataframe features or variables. You can also see the type of data you are working with (i.e., NUM). Not pictured is when you click on ‘Toggle details’. This toggle prompts a whole plethora of more usable statistics. The details include:"
},
{
"code": null,
"e": 2485,
"s": 2447,
"text": "Statistics — quantile and descriptive"
},
{
"code": null,
"e": 2494,
"s": 2485,
"text": "quantile"
},
{
"code": null,
"e": 2578,
"s": 2494,
"text": "Minimum5th percentileQ1MedianQ395th percentileMaximumRangeInterquartile range (IQR)"
},
{
"code": null,
"e": 2590,
"s": 2578,
"text": "descriptive"
},
{
"code": null,
"e": 2712,
"s": 2590,
"text": "Standard deviationCoefficient of variation (CV)KurtosisMeanMedian Absolute Deviation (MAD)SkewnessSumVarianceMonotonicity"
},
{
"code": null,
"e": 2907,
"s": 2712,
"text": "These statistics also provide similar information from the describe function I see most Data Scientists using today, however, there are a few more and it presents them in an easy-to-view format."
},
{
"code": null,
"e": 2918,
"s": 2907,
"text": "Histograms"
},
{
"code": null,
"e": 3119,
"s": 2918,
"text": "The histograms provide for an easily digestible visual of your variables. You can expect to see the frequency of your variable on the y-axis and fixed-size bins (bins=15 is the default) on the x-axis."
},
{
"code": null,
"e": 3133,
"s": 3119,
"text": "Common Values"
},
{
"code": null,
"e": 3236,
"s": 3133,
"text": "The common values will provide the value, count, and frequency that are most common for your variable."
},
{
"code": null,
"e": 3251,
"s": 3236,
"text": "Extreme Values"
},
{
"code": null,
"e": 3377,
"s": 3251,
"text": "The extreme values will provide the value, count, and frequency that are in the minimum and maximum values of your dataframe."
},
{
"code": null,
"e": 3760,
"s": 3377,
"text": "The interactions feature of the profiling report is unique in that you can choose from your list of columns to either be on the x-axis or y-xis provided. For example, pictured above is variable A against variable A, which is why you see overlapping. You can easily switch to other variables or columns to achieve a different plot and an excellent representation of your data points."
},
{
"code": null,
"e": 4080,
"s": 3760,
"text": "Sometimes making fancier or colorful correlation plots can be time-consuming if you make them from line-by-line Python code. However, with this correlation plot, you can easily visualize the relationships between variables in your data, which are also nicely color-coded. There are four main plots that you can display:"
},
{
"code": null,
"e": 4092,
"s": 4080,
"text": "Pearson’s r"
},
{
"code": null,
"e": 4105,
"s": 4092,
"text": "Spearman’s ρ"
},
{
"code": null,
"e": 4117,
"s": 4105,
"text": "Kendall’s τ"
},
{
"code": null,
"e": 4127,
"s": 4117,
"text": "Phik (φk)"
},
{
"code": null,
"e": 4521,
"s": 4127,
"text": "You may only be used to one of these correlation methods, so the other ones may sound confusing or not usable. Therefore, the correlation plot also comes provided with a toggle for details onto the meaning of each correlation you can visualize — this feature really helps when you need a refresher on correlation, as well as when you are deciding between which plot(s) to use for your analysis"
},
{
"code": null,
"e": 4857,
"s": 4521,
"text": "As you can see from the plot above, the report tool also includes missing values. You can see how much of each variable is missing, including the count, and matrix. It is a nice way to visualize your data before you perform any models with it. You would preferably want to see a plot like the above, meaning you have no missing values."
},
{
"code": null,
"e": 5269,
"s": 4857,
"text": "Sample acts similarly to the head and tail function where it returns your dataframe’s first few rows or last rows. In this example, you can see the first rows and last rows as well. I use this tab when I want a sense of where my data started and where it ended — I recommend ranking or ordering to see more benefit out of this tab, as you can see the range of your data, with a visual respective representation."
},
{
"code": null,
"e": 5701,
"s": 5269,
"text": "I hope this article provided you with some inspiration for your next exploratory data analysis. Being a Data Scientist can be overwhelming and EDA is often forgotten or not practiced as much as model-building. With the Pandas Profiling report, you can perform EDA with minimal code, providing useful statistics and visualizes as well. That way, you can focus on the fun part of Data Science and Machine Learning, the model process."
},
{
"code": null,
"e": 5860,
"s": 5701,
"text": "To summarize, the main features of Pandas Profiling report include overview, variables, interactions, correlations, missing values, and a sample of your data."
},
{
"code": null,
"e": 6087,
"s": 5860,
"text": "Here is the code I used to install and import libraries, as well as to generate some dummy data for the example, and finally, the one line of code used to generate the Pandas Profile report based on your Pandas dataframe [10]."
},
{
"code": null,
"e": 6386,
"s": 6087,
"text": "# install library #!pip install pandas_profilingimport pandas_profilingimport pandas as pdimport numpy as np# create data df = pd.DataFrame(np.random.randint(0,200,size=(15, 6)), columns=list('ABCDEF'))# run your report!df.profile_report()# I did get an error and had to reinstall matplotlib to fix"
},
{
"code": null,
"e": 6614,
"s": 6386,
"text": "Please feel free to comment down below if you have any questions or have used this feature before. There is still some information I did not describe, but you can find more of that information on the link I provided from above."
},
{
"code": null,
"e": 6657,
"s": 6614,
"text": "Thank you for reading, I hope you enjoyed!"
},
{
"code": null,
"e": 6738,
"s": 6657,
"text": "[1] M.Przybyla, Screenshot of Pandas Profile Report correlations example, (2020)"
},
{
"code": null,
"e": 6814,
"s": 6738,
"text": "[2] pandas-profiling, GitHub for documentation and all contributors, (2020)"
},
{
"code": null,
"e": 6869,
"s": 6814,
"text": "[3] M.Przybyla, Screenshot of Overview example, (2020)"
},
{
"code": null,
"e": 6925,
"s": 6869,
"text": "[4] M.Przybyla, Screenshot of Variables example, (2020)"
},
{
"code": null,
"e": 6984,
"s": 6925,
"text": "[5] M.Przybyla, Screenshot of Interactions example, (2020)"
},
{
"code": null,
"e": 7043,
"s": 6984,
"text": "[6] M.Przybyla, Screenshot of Correlations example, (2020)"
},
{
"code": null,
"e": 7104,
"s": 7043,
"text": "[7] M.Przybyla, Screenshot of Missing Values example, (2020)"
},
{
"code": null,
"e": 7157,
"s": 7104,
"text": "[8] M.Przybyla, Screenshot of Sample example, (2020)"
},
{
"code": null,
"e": 7204,
"s": 7157,
"text": "[9] Photo by Elena Loshina on Unsplash, (2018)"
}
] |
Google Guice - First Application
|
Let's create a sample console based application where we'll demonstrate dependency injection using Guice binding mechanism step by step.
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).to(SpellCheckerImpl.class);
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck(){
spellChecker.checkSpelling();
}
}
Injector injector = Guice.createInjector(new TextEditorModule());
TextEditor editor = injector.getInstance(TextEditor.class);
editor.makeSpellCheck();
Create a java class named GuiceTester.
GuiceTester.java
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
public class GuiceTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new TextEditorModule());
TextEditor editor = injector.getInstance(TextEditor.class);
editor.makeSpellCheck();
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck(){
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).to(SpellCheckerImpl.class);
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
Compile and run the file, you will see the following output.
Inside checkSpelling.
27 Lectures
1.5 hours
Lemuel Ogbunude
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2239,
"s": 2102,
"text": "Let's create a sample console based application where we'll demonstrate dependency injection using Guice binding mechanism step by step."
},
{
"code": null,
"e": 2324,
"s": 2239,
"text": "//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}"
},
{
"code": null,
"e": 2510,
"s": 2324,
"text": "//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}"
},
{
"code": null,
"e": 2687,
"s": 2510,
"text": "//Binding Module\nclass TextEditorModule extends AbstractModule {\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}"
},
{
"code": null,
"e": 2926,
"s": 2687,
"text": "class TextEditor {\n private SpellChecker spellChecker;\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 2992,
"s": 2926,
"text": "Injector injector = Guice.createInjector(new TextEditorModule());"
},
{
"code": null,
"e": 3052,
"s": 2992,
"text": "TextEditor editor = injector.getInstance(TextEditor.class);"
},
{
"code": null,
"e": 3078,
"s": 3052,
"text": "editor.makeSpellCheck(); "
},
{
"code": null,
"e": 3117,
"s": 3078,
"text": "Create a java class named GuiceTester."
},
{
"code": null,
"e": 3134,
"s": 3117,
"text": "GuiceTester.java"
},
{
"code": null,
"e": 4221,
"s": 3134,
"text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck(); \n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}"
},
{
"code": null,
"e": 4282,
"s": 4221,
"text": "Compile and run the file, you will see the following output."
},
{
"code": null,
"e": 4305,
"s": 4282,
"text": "Inside checkSpelling.\n"
},
{
"code": null,
"e": 4340,
"s": 4305,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4357,
"s": 4340,
"text": " Lemuel Ogbunude"
},
{
"code": null,
"e": 4364,
"s": 4357,
"text": " Print"
},
{
"code": null,
"e": 4375,
"s": 4364,
"text": " Add Notes"
}
] |
Can we have multiple type parameters in generic methods in Java?
|
Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.
To define a generic class you need to specify the type parameter you are using in the angle brackets “<>” after the class name and you can treat this as datatype of the instance variable an proceed with the code.
Example − Generic class
class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}
Usage − While instantiating the generic class you need to specify the object name after the class within the angular brackets. Thus, chose the type of the type parameter dynamically and pass the required object as a parameter.
public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
std1.display();
Student<String> std2 = new Student<String>("25");
std2.display();
Student<Integer> std3 = new Student<Integer>(25);
std3.display();
}
}
Example generic methods
Similar to generic classes you can also define generic methods in Java. These methods use their own type parameters. Just like local variables, the scope of the type parameters of the methods lies within the method.
While defining generic methods you need to specify the type parameter in the angular brackets and use it as a local variable.
Live Demo
public class GenericMethod {
<T>void sampleMethod(T[] array) {
for(int i=0; i<array.length; i++) {
System.out.println(array[i]);
}
}
public static void main(String args[]) {
GenericMethod obj = new GenericMethod();
Integer intArray[] = {45, 26, 89, 96};
obj.sampleMethod(intArray);
String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"};
obj.sampleMethod(stringArray);
}
}
45
26
89
96
Krishna
Raju
Seema
Geeta
You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
Live Demo
import java.util.Arrays;
public class GenericMethod {
public static <T, E> void sampleMethod(T[] array, E ele ) {
System.out.println(Arrays.toString(array));
System.out.println(ele);
}
public static void main(String args[]) {
Integer [] intArray = {24, 56, 89, 75, 36};
String str = "hello";
sampleMethod(intArray, str);
}
}
[24, 56, 89, 75, 36]
hello
Live Demo
class Student<T, S> {
T t;
S s;
Student(T t, S s){
this.t = t;
this.s = s;
}
public void display() {
System.out.println("Value of "+this.t+" is: "+this.s);
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<String, String> std1 = new Student<String, String>("Name", "Raju");
Student<String, Integer> std2 = new Student<String, Integer>("Age", 20);
Student<String, Float> std3 = new Student<String, Float>("Percentage", 96.5f);
std1.display();
std2.display();
std3.display();
}
}
Value of Name is: Raju
Value of Age is: 20
Value of Percentage is: 96.5
|
[
{
"code": null,
"e": 1430,
"s": 1062,
"text": "Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype."
},
{
"code": null,
"e": 1643,
"s": 1430,
"text": "To define a generic class you need to specify the type parameter you are using in the angle brackets “<>” after the class name and you can treat this as datatype of the instance variable an proceed with the code."
},
{
"code": null,
"e": 1667,
"s": 1643,
"text": "Example − Generic class"
},
{
"code": null,
"e": 1828,
"s": 1667,
"text": "class Student<T>{\n T age;\n Student(T age){\n this.age = age;\n }\n public void display() {\n System.out.println(\"Value of age: \"+this.age);\n }\n}"
},
{
"code": null,
"e": 2055,
"s": 1828,
"text": "Usage − While instantiating the generic class you need to specify the object name after the class within the angular brackets. Thus, chose the type of the type parameter dynamically and pass the required object as a parameter."
},
{
"code": null,
"e": 2370,
"s": 2055,
"text": "public class GenericsExample {\n public static void main(String args[]) {\n Student<Float> std1 = new Student<Float>(25.5f);\n std1.display();\n Student<String> std2 = new Student<String>(\"25\");\n std2.display();\n Student<Integer> std3 = new Student<Integer>(25);\n std3.display();\n }\n}"
},
{
"code": null,
"e": 2394,
"s": 2370,
"text": "Example generic methods"
},
{
"code": null,
"e": 2610,
"s": 2394,
"text": "Similar to generic classes you can also define generic methods in Java. These methods use their own type parameters. Just like local variables, the scope of the type parameters of the methods lies within the method."
},
{
"code": null,
"e": 2736,
"s": 2610,
"text": "While defining generic methods you need to specify the type parameter in the angular brackets and use it as a local variable."
},
{
"code": null,
"e": 2747,
"s": 2736,
"text": " Live Demo"
},
{
"code": null,
"e": 3189,
"s": 2747,
"text": "public class GenericMethod {\n <T>void sampleMethod(T[] array) {\n for(int i=0; i<array.length; i++) {\n System.out.println(array[i]);\n }\n }\n public static void main(String args[]) {\n GenericMethod obj = new GenericMethod();\n Integer intArray[] = {45, 26, 89, 96};\n obj.sampleMethod(intArray);\n String stringArray[] = {\"Krishna\", \"Raju\", \"Seema\", \"Geeta\"};\n obj.sampleMethod(stringArray);\n }\n}"
},
{
"code": null,
"e": 3226,
"s": 3189,
"text": "45\n26\n89\n96\nKrishna\nRaju\nSeema\nGeeta"
},
{
"code": null,
"e": 3388,
"s": 3226,
"text": "You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma."
},
{
"code": null,
"e": 3399,
"s": 3388,
"text": " Live Demo"
},
{
"code": null,
"e": 3769,
"s": 3399,
"text": "import java.util.Arrays;\npublic class GenericMethod {\n public static <T, E> void sampleMethod(T[] array, E ele ) {\n System.out.println(Arrays.toString(array));\n System.out.println(ele);\n }\n public static void main(String args[]) {\n Integer [] intArray = {24, 56, 89, 75, 36};\n String str = \"hello\";\n sampleMethod(intArray, str);\n }\n}"
},
{
"code": null,
"e": 3796,
"s": 3769,
"text": "[24, 56, 89, 75, 36]\nhello"
},
{
"code": null,
"e": 3807,
"s": 3796,
"text": " Live Demo"
},
{
"code": null,
"e": 4397,
"s": 3807,
"text": "class Student<T, S> {\n T t;\n S s;\n Student(T t, S s){\n this.t = t;\n this.s = s;\n }\n public void display() {\n System.out.println(\"Value of \"+this.t+\" is: \"+this.s);\n }\n}\npublic class GenericsExample {\n public static void main(String args[]) {\n Student<String, String> std1 = new Student<String, String>(\"Name\", \"Raju\");\n Student<String, Integer> std2 = new Student<String, Integer>(\"Age\", 20);\n Student<String, Float> std3 = new Student<String, Float>(\"Percentage\", 96.5f);\n std1.display();\n std2.display();\n std3.display();\n }\n}"
},
{
"code": null,
"e": 4469,
"s": 4397,
"text": "Value of Name is: Raju\nValue of Age is: 20\nValue of Percentage is: 96.5"
}
] |
SVN - Environment Setup
|
Subversion is a popular open-source version control tool. It is open-source and available for free over the internet. It comes by default with most of the GNU/Linux distributions, so it might be already installed on your system. To check whether it is installed or not use following command.
[jerry@CentOS ~]$ svn --version
If Subversion client is not installed, then command will report error, otherwise it will display the version of the installed software.
[jerry@CentOS ~]$ svn --version
-bash: svn: command not found
If you are using RPM-based GNU/Linux, then use yum command for installation. After successful installation, execute the svn --version command.
[jerry@CentOS ~]$ su -
Password:
[root@CentOS ~]# yum install subversion
[jerry@CentOS ~]$ svn --version
svn, version 1.6.11 (r934486)
compiled Jun 23 2012, 00:44:03
And if you are using Debian-based GNU/Linux, then use apt command for installation.
[jerry@Ubuntu]$ sudo apt-get update
[sudo] password for jerry:
[jerry@Ubuntu]$ sudo apt-get install subversion
[jerry@Ubuntu]$ svn --version
svn, version 1.7.5 (r1336830)
compiled Jun 21 2013, 22:11:49
We have seen how to install Subversion client on GNU/Linux. Let us see how to create a new repository and allow access to the users.
On server we have to install Apache httpd module and svnadmin tool.
[jerry@CentOS ~]$ su -
Password:
[root@CentOS ~]# yum install mod_dav_svn subversion
The mod_dav_svn package allows access to a repository using HTTP, via Apache httpd server and subversion package installs svnadmin tool.
The subversion reads its configuration from /etc/httpd/conf.d/subversion.conf file. After adding configuration, subversion.conf file looks as follows:
LoadModule dav_svn_module modules/mod_dav_svn.so
LoadModule authz_svn_module modules/mod_authz_svn.so
<Location /svn>
DAV svn
SVNParentPath /var/www/svn
AuthType Basic
AuthName "Authorization Realm"
AuthUserFile /etc/svn-users
Require valid-user
</Location>
Let us create Subversion users and grant them access to the repository. htpasswd command is used to create and update the plain-text files which are used to store usernames and passwords for basic authentication of HTTP users. '-c' options creates password file, if password file already exists, it is overwritten. That is why use '-c' option only the first time. '-m' option enables MD5 encryption for passwords.
Let us create user tom.
[root@CentOS ~]# htpasswd -cm /etc/svn-users tom
New password:
Re-type new password:
Adding password for user tom
Let us create user jerry
[root@CentOS ~]# htpasswd -m /etc/svn-users jerry
New password:
Re-type new password:
Adding password for user jerry
[root@CentOS ~]#
Create Subversion parent directory to store all the work (see /etc/httpd/conf.d/subversion.conf).
[root@CentOS ~]# mkdir /var/www/svn
[root@CentOS ~]# cd /var/www/svn/
Create a project repository named project_repo. svnadmin command will create a new repository and a few other directories inside that to store the metadata.
[root@CentOS svn]# svnadmin create project_repo
[root@CentOS svn]# ls -l project_repo
total 24
drwxr-xr-x. 2 root root 4096 Aug 4 22:30 conf
drwxr-sr-x. 6 root root 4096 Aug 4 22:30 db
-r--r--r--. 1 root root 2 Aug 4 22:30 format
drwxr-xr-x. 2 root root 4096 Aug 4 22:30 hooks
drwxr-xr-x. 2 root root 4096 Aug 4 22:30 locks
-rw-r--r--. 1 root root 229 Aug 4 22:30 README.txt
Let us change the user and group ownership of the repository.
[root@CentOS svn]# chown -R apache.apache project_repo/
Check whether SELinux is enabled or not using the SELinux status tool.
[root@CentOS svn]# sestatus
SELinux status: enabled
SELinuxfs mount: /selinux
Current mode: enforcing
Mode from config file: enforcing
Policy version: 24
Policy from config file: targeted
For our server, SELinux is enabled, so we have to change the SELinux security context.
[root@CentOS svn]# chcon -R -t httpd_sys_content_t /var/www/svn/project_repo/
To allow commits over HTTP, execute the following command.
[root@CentOS svn]# chcon -R -t httpd_sys_rw_content_t /var/www/svn/project_repo/
Restart the Apache server and we are done with the configuration of Apache server.
[root@CentOS svn]# service httpd restart
Stopping httpd: [FAILED]
Starting httpd: httpd: apr_sockaddr_info_get() failed for CentOS
httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
[ OK ]
[root@CentOS svn]# service httpd status
httpd (pid 1372) is running...
[root@CentOS svn]#
We have configured the Apache server successfully, now we will configure the repository. To provide repository access to only authentic users and to use the default authorization file; append the following lines to project_repo/conf/svnserve.conf file.
anon-access = none
authz-db = authz
Conventionally, every Subversion project has trunk, tags, and branches directories directly under the project's root directory.
The trunk is a directory where all the main development happens and is usually checked out by the developers to work on the project.
The tags directory is used to store named snapshots of the project. When creating a production release, the team will tag the code that goes into the release.
The branches directory is used when you want to pursue different lines of development.
Let us create the trunk, tags, and branches directory structure under the project repository.
[root@CentOS svn]# mkdir /tmp/svn-template
[root@CentOS svn]# mkdir /tmp/svn-template/trunk
[root@CentOS svn]# mkdir /tmp/svn-template/branches
[root@CentOS svn]# mkdir /tmp/svn-template/tags
Now import the directories from /tmp/svn-template to the repository.
[root@CentOS svn]# svn import -m 'Create trunk, branches, tags directory structure' /tmp/svn-template/
Adding /tmp/svn-template/trunk
Adding /tmp/svn-template/branches
Adding /tmp/svn-template/tags
Committed revision 1.
[root@CentOS svn]#
This is done! We have successfully created the repository and allowed access to Tom and Jerry. From now, they can perform all the supported operations to the repository.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2068,
"s": 1776,
"text": "Subversion is a popular open-source version control tool. It is open-source and available for free over the internet. It comes by default with most of the GNU/Linux distributions, so it might be already installed on your system. To check whether it is installed or not use following command."
},
{
"code": null,
"e": 2101,
"s": 2068,
"text": "[jerry@CentOS ~]$ svn --version\n"
},
{
"code": null,
"e": 2237,
"s": 2101,
"text": "If Subversion client is not installed, then command will report error, otherwise it will display the version of the installed software."
},
{
"code": null,
"e": 2300,
"s": 2237,
"text": "[jerry@CentOS ~]$ svn --version\n-bash: svn: command not found\n"
},
{
"code": null,
"e": 2443,
"s": 2300,
"text": "If you are using RPM-based GNU/Linux, then use yum command for installation. After successful installation, execute the svn --version command."
},
{
"code": null,
"e": 2612,
"s": 2443,
"text": "[jerry@CentOS ~]$ su -\nPassword: \n[root@CentOS ~]# yum install subversion\n\n[jerry@CentOS ~]$ svn --version\nsvn, version 1.6.11 (r934486)\ncompiled Jun 23 2012, 00:44:03\n"
},
{
"code": null,
"e": 2696,
"s": 2612,
"text": "And if you are using Debian-based GNU/Linux, then use apt command for installation."
},
{
"code": null,
"e": 2901,
"s": 2696,
"text": "[jerry@Ubuntu]$ sudo apt-get update\n[sudo] password for jerry:\n\n[jerry@Ubuntu]$ sudo apt-get install subversion\n\n[jerry@Ubuntu]$ svn --version\nsvn, version 1.7.5 (r1336830)\ncompiled Jun 21 2013, 22:11:49\n"
},
{
"code": null,
"e": 3034,
"s": 2901,
"text": "We have seen how to install Subversion client on GNU/Linux. Let us see how to create a new repository and allow access to the users."
},
{
"code": null,
"e": 3103,
"s": 3034,
"text": "On server we have to install Apache httpd module and svnadmin tool."
},
{
"code": null,
"e": 3190,
"s": 3103,
"text": "[jerry@CentOS ~]$ su -\nPassword: \n[root@CentOS ~]# yum install mod_dav_svn subversion\n"
},
{
"code": null,
"e": 3327,
"s": 3190,
"text": "The mod_dav_svn package allows access to a repository using HTTP, via Apache httpd server and subversion package installs svnadmin tool."
},
{
"code": null,
"e": 3478,
"s": 3327,
"text": "The subversion reads its configuration from /etc/httpd/conf.d/subversion.conf file. After adding configuration, subversion.conf file looks as follows:"
},
{
"code": null,
"e": 3761,
"s": 3478,
"text": "LoadModule dav_svn_module modules/mod_dav_svn.so\nLoadModule authz_svn_module modules/mod_authz_svn.so\n\n<Location /svn>\n DAV svn\n SVNParentPath /var/www/svn\n AuthType Basic\n AuthName \"Authorization Realm\"\n AuthUserFile /etc/svn-users\n Require valid-user\n</Location>"
},
{
"code": null,
"e": 4175,
"s": 3761,
"text": "Let us create Subversion users and grant them access to the repository. htpasswd command is used to create and update the plain-text files which are used to store usernames and passwords for basic authentication of HTTP users. '-c' options creates password file, if password file already exists, it is overwritten. That is why use '-c' option only the first time. '-m' option enables MD5 encryption for passwords."
},
{
"code": null,
"e": 4199,
"s": 4175,
"text": "Let us create user tom."
},
{
"code": null,
"e": 4316,
"s": 4199,
"text": "[root@CentOS ~]# htpasswd -cm /etc/svn-users tom\nNew password: \nRe-type new password: \nAdding password for user tom\n"
},
{
"code": null,
"e": 4341,
"s": 4316,
"text": "Let us create user jerry"
},
{
"code": null,
"e": 4479,
"s": 4341,
"text": "[root@CentOS ~]# htpasswd -m /etc/svn-users jerry\nNew password: \nRe-type new password: \nAdding password for user jerry\n[root@CentOS ~]# \n"
},
{
"code": null,
"e": 4577,
"s": 4479,
"text": "Create Subversion parent directory to store all the work (see /etc/httpd/conf.d/subversion.conf)."
},
{
"code": null,
"e": 4648,
"s": 4577,
"text": "[root@CentOS ~]# mkdir /var/www/svn\n[root@CentOS ~]# cd /var/www/svn/\n"
},
{
"code": null,
"e": 4805,
"s": 4648,
"text": "Create a project repository named project_repo. svnadmin command will create a new repository and a few other directories inside that to store the metadata."
},
{
"code": null,
"e": 5192,
"s": 4805,
"text": "[root@CentOS svn]# svnadmin create project_repo\n\n[root@CentOS svn]# ls -l project_repo\ntotal 24\ndrwxr-xr-x. 2 root root 4096 Aug 4 22:30 conf\ndrwxr-sr-x. 6 root root 4096 Aug 4 22:30 db\n-r--r--r--. 1 root root 2 Aug 4 22:30 format\ndrwxr-xr-x. 2 root root 4096 Aug 4 22:30 hooks\ndrwxr-xr-x. 2 root root 4096 Aug 4 22:30 locks\n-rw-r--r--. 1 root root 229 Aug 4 22:30 README.txt\n"
},
{
"code": null,
"e": 5254,
"s": 5192,
"text": "Let us change the user and group ownership of the repository."
},
{
"code": null,
"e": 5311,
"s": 5254,
"text": "[root@CentOS svn]# chown -R apache.apache project_repo/\n"
},
{
"code": null,
"e": 5382,
"s": 5311,
"text": "Check whether SELinux is enabled or not using the SELinux status tool."
},
{
"code": null,
"e": 5652,
"s": 5382,
"text": "[root@CentOS svn]# sestatus\nSELinux status: enabled\nSELinuxfs mount: /selinux\nCurrent mode: enforcing\nMode from config file: enforcing\nPolicy version: 24\nPolicy from config file: targeted\n"
},
{
"code": null,
"e": 5739,
"s": 5652,
"text": "For our server, SELinux is enabled, so we have to change the SELinux security context."
},
{
"code": null,
"e": 5818,
"s": 5739,
"text": "[root@CentOS svn]# chcon -R -t httpd_sys_content_t /var/www/svn/project_repo/\n"
},
{
"code": null,
"e": 5877,
"s": 5818,
"text": "To allow commits over HTTP, execute the following command."
},
{
"code": null,
"e": 5959,
"s": 5877,
"text": "[root@CentOS svn]# chcon -R -t httpd_sys_rw_content_t /var/www/svn/project_repo/\n"
},
{
"code": null,
"e": 6042,
"s": 5959,
"text": "Restart the Apache server and we are done with the configuration of Apache server."
},
{
"code": null,
"e": 6485,
"s": 6042,
"text": "[root@CentOS svn]# service httpd restart\nStopping httpd: [FAILED]\nStarting httpd: httpd: apr_sockaddr_info_get() failed for CentOS\nhttpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName\n [ OK ]\n[root@CentOS svn]# service httpd status\nhttpd (pid 1372) is running...\n[root@CentOS svn]#\n"
},
{
"code": null,
"e": 6738,
"s": 6485,
"text": "We have configured the Apache server successfully, now we will configure the repository. To provide repository access to only authentic users and to use the default authorization file; append the following lines to project_repo/conf/svnserve.conf file."
},
{
"code": null,
"e": 6775,
"s": 6738,
"text": "anon-access = none\nauthz-db = authz\n"
},
{
"code": null,
"e": 6903,
"s": 6775,
"text": "Conventionally, every Subversion project has trunk, tags, and branches directories directly under the project's root directory."
},
{
"code": null,
"e": 7036,
"s": 6903,
"text": "The trunk is a directory where all the main development happens and is usually checked out by the developers to work on the project."
},
{
"code": null,
"e": 7195,
"s": 7036,
"text": "The tags directory is used to store named snapshots of the project. When creating a production release, the team will tag the code that goes into the release."
},
{
"code": null,
"e": 7282,
"s": 7195,
"text": "The branches directory is used when you want to pursue different lines of development."
},
{
"code": null,
"e": 7377,
"s": 7282,
"text": "Let us create the trunk, tags, and branches directory structure under the project repository."
},
{
"code": null,
"e": 7570,
"s": 7377,
"text": "[root@CentOS svn]# mkdir /tmp/svn-template\n[root@CentOS svn]# mkdir /tmp/svn-template/trunk\n[root@CentOS svn]# mkdir /tmp/svn-template/branches\n[root@CentOS svn]# mkdir /tmp/svn-template/tags\n"
},
{
"code": null,
"e": 7639,
"s": 7570,
"text": "Now import the directories from /tmp/svn-template to the repository."
},
{
"code": null,
"e": 7904,
"s": 7639,
"text": "[root@CentOS svn]# svn import -m 'Create trunk, branches, tags directory structure' /tmp/svn-template/ \nAdding /tmp/svn-template/trunk\nAdding /tmp/svn-template/branches\nAdding /tmp/svn-template/tags\nCommitted revision 1.\n[root@CentOS svn]#\n"
},
{
"code": null,
"e": 8074,
"s": 7904,
"text": "This is done! We have successfully created the repository and allowed access to Tom and Jerry. From now, they can perform all the supported operations to the repository."
},
{
"code": null,
"e": 8081,
"s": 8074,
"text": " Print"
},
{
"code": null,
"e": 8092,
"s": 8081,
"text": " Add Notes"
}
] |
Contrast Enhancement of Grayscale Images Using Morphological Operators | by Shivanee Jaiswal | Towards Data Science
|
Contrast Enhancement is a very common image processing technique for enhancing features in low contrast images. Several methods like Contrast Stretching, Histogram Equalization, Adaptive Histogram Equalization, Contrast-Limited Adaptive Histogram Equalization or CLAHE, etc. have been used for enhancing the contrast of images. In this article, we will look at another method of Contrast Enhancement which is performed using a combination of Morphological Transformations.
Morphological Transformations or Morphological Operators are simple image transformations that are usually applied on binary images, but can be applied to grayscale images as well. There are various types of Morphological Transformations like Erosion, Dilation, Opening, Closing, Gradient, Top Hat and the Black Hat. The two main components of these transformations are the input image and a kernel which is known as Structuring Element (SE). Before we jump on to the different types of Morphological Transformations in detail, let us understand the Structuring Element.
The Structuring Element (SE) is the neighborhood around each pixel that is examined while performing the morphological operations. Structuring Element can be of different shapes and sizes, and changing it can significantly impact the performance of the transformation.
There are three shapes of the Structuring Element provided by OpenCV — Rectangular, Elliptical and Cross-Shaped. The figure below shows these three shapes.
The different types of Morphological Operators are:
Erosion — According to the OpenCV Documentation, the Erosion operator works similar to soil erosion. It “erodes”, or in simpler words, removes the boundaries of the foreground object in the image. The pixels at the boundary of the foreground object are removed. It reduces the size of the object in the image.Dilation — Dilation works exactly opposite to erosion. It “dilates” or expands the boundaries of the foreground object which in turn increases the size of the object in the image. This is useful if we want to join broken parts of the foreground object.Opening — The Opening operation is used in noise removal. It is done by first applying the erosion operation, followed by the dilation operation. The erosion operation first removes all the small noisy areas from the image and then dilation is applied to restore the original size of the object.Closing — The Closing is the opposite of Opening, which means that dilation is applied first followed by erosion. This is useful for joining or filling small spots that are present in the foreground object, while retaining the size of the object.Gradient — Morphological Gradient of an image is obtained by subtracting the erosion result from the dilation result. The result of the Gradient operation is the outline of the foreground object in the image.Top Hat / White Hat— Top Hat Transform, also known as the White Hat Transform, is obtained by removing or subtracting the Opening of the image from the original image. This operator gives us the bright features in the image that are smaller than the Structuring Element.Black Hat / Bottom Hat— The Black Hat Transform, also known as the Bottom Hat Transform, is obtained by removing or subtracting the Closing of the image from the original image. This operator gives us the dark features in the image that are smaller than the Structuring Element.
Erosion — According to the OpenCV Documentation, the Erosion operator works similar to soil erosion. It “erodes”, or in simpler words, removes the boundaries of the foreground object in the image. The pixels at the boundary of the foreground object are removed. It reduces the size of the object in the image.
Dilation — Dilation works exactly opposite to erosion. It “dilates” or expands the boundaries of the foreground object which in turn increases the size of the object in the image. This is useful if we want to join broken parts of the foreground object.
Opening — The Opening operation is used in noise removal. It is done by first applying the erosion operation, followed by the dilation operation. The erosion operation first removes all the small noisy areas from the image and then dilation is applied to restore the original size of the object.
Closing — The Closing is the opposite of Opening, which means that dilation is applied first followed by erosion. This is useful for joining or filling small spots that are present in the foreground object, while retaining the size of the object.
Gradient — Morphological Gradient of an image is obtained by subtracting the erosion result from the dilation result. The result of the Gradient operation is the outline of the foreground object in the image.
Top Hat / White Hat— Top Hat Transform, also known as the White Hat Transform, is obtained by removing or subtracting the Opening of the image from the original image. This operator gives us the bright features in the image that are smaller than the Structuring Element.
Black Hat / Bottom Hat— The Black Hat Transform, also known as the Bottom Hat Transform, is obtained by removing or subtracting the Closing of the image from the original image. This operator gives us the dark features in the image that are smaller than the Structuring Element.
Note: The Top Hat and the Black Hat transforms are more suited for grayscale images.
Contrast Enhancement, in simple words, requires the following to be done:
Making the bright regions in the image brighter.Making the dark regions in the image darker.
Making the bright regions in the image brighter.
Making the dark regions in the image darker.
As we had seen earlier, the result of the Top Hat Transform is an image consisting of all the bright features in the input image and the result of the Black Hat Transform is an image consisting of all the dark features in the input image. Thus, for the purpose of Contrast Enhancement, we will need the Top and the Black Hat Transforms of the input image.
After obtaining the Top and Black Hat Transforms of the input image, we will add the Top Hat Transform to the input image in order to make its bright regions brighter, and subtract the Black Hat Transform from the input image to make its dark regions darker.
The step mentioned above can be represented as an equation shown below:
where R is the result image, I is the input image, T and B are the Top Hat and the Black Hat transforms respectively.
The flowchart below depicts the steps we will follow to enhance the contrast.
We will implement this Contrast Enhancement technique using Python and OpenCV. We will need to first install opencv-python using pip.
pip install opencv-python
After installing OpenCV, we will import the library in our code.
import cv2 as cv
We will use the below image for our code, which is taken from the COVID-19 Image Repository on GitHub.
The image data in this repository has been collected from the Institute for Diagnostic and Interventional Radiology, Hannover Medical School, Hannover, Germany and are licensed under the Creative Commons Attribution 3.0 Unported.
I have scaled down the image by 50% to reduce the size of the image.
To read this image, we will use the imread function by OpenCV.
filename = # path to the image fileimg = cv.imread(filename,0)
Now that we have our image, we will obtain the Top and the Black Hat Transforms of this image. Before this, we need to construct our Structuring Element or the kernel. We can use the getStructuringElement function provided by OpenCV for this purpose.
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(5,5))
In the above snippet, we have constructed an elliptical Structuring Element of size (5,5). You can experiment by changing these parameters and observe the effect on the output.
The next step is to get the transforms of the input image using the kernel we constructed in the previous step.
# Top Hat TransformtopHat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)# Black Hat TransformblackHat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)
Once we have our transforms, we will apply the equation that we had seen earlier.
res = img + topHat - blackHat
We can see the contrast of the input image has improved a bit. Some of the minute features, that were not prominent in the input image, are now visible. However, this technique also adds some noise to the image if the Structuring Element is not chosen carefully.
For example, the image below shows the output when an elliptical Structuring Element was chosen of size (15,15). The minute features in the lungs and the edges of the bones are now more prominent and clear than the earlier output, but we can see some noisy areas in the output image, near the boundaries of the body, i.e. the white patches in the background.
As you go on increasing the size of the Structuring Element, the foreground features will become more prominent but the background will start becoming more and more noisy. The output below with Structuring Element of size (35,35) has more noisy area in the background.
Thus, we saw how to enhance the contrast of grayscale images using a combination of Top Hat and Black Hat Morphological Operations. Some of the minute features were greatly enhanced and became more prominent in our output image as seen above.
This method might not work as efficiently as the original Contrast Stretching method due to the noise it introduces in the image, as we go on increasing the size of our Structuring Element.As the Structuring Element is basically the size of the neighborhood to consider while applying the transformations, the output will also depend on the size of the input image. For example, a (35,35) kernel for an image of size 1000 x 1000 will form a smaller region as compared to a (35,35) kernel for a 250 x 250 image. Thus, resizing the image will also affect the output of this method.As Top and Black Hat Transforms give us the brighter and darker features respectively that are smaller than the Structuring Element, this method of Contrast Enhancement will work well if the size of the features to enhance are smaller than the size of our chosen Structuring Element. Thus, it becomes difficult to accurately enhance the contrast of larger features, as greater sizes of our kernel will introduce larger noisy areas in our image background.
This method might not work as efficiently as the original Contrast Stretching method due to the noise it introduces in the image, as we go on increasing the size of our Structuring Element.
As the Structuring Element is basically the size of the neighborhood to consider while applying the transformations, the output will also depend on the size of the input image. For example, a (35,35) kernel for an image of size 1000 x 1000 will form a smaller region as compared to a (35,35) kernel for a 250 x 250 image. Thus, resizing the image will also affect the output of this method.
As Top and Black Hat Transforms give us the brighter and darker features respectively that are smaller than the Structuring Element, this method of Contrast Enhancement will work well if the size of the features to enhance are smaller than the size of our chosen Structuring Element. Thus, it becomes difficult to accurately enhance the contrast of larger features, as greater sizes of our kernel will introduce larger noisy areas in our image background.
Thank you for reading! :) You can connect with me on LinkedIn if you have any questions.
OpenCV: Morphological Transformations https://docs.opencv.org/3.4/d9/d61/tutorial_py_morphological_ops.htmlKushol R., Nishat R. M., Rahman A. B. M. A., Salekin M. M., “Contrast Enhancement of Medical X-Ray Image Using Morphological Operators with Optimal Structuring Element,” arXiv:1905.08545v1 [cs.CV] 27 May 2019Hinrich B. Winther, Hans Laser, Svetlana Gerbel, Sabine K. Maschke, Jan B. Hinrichs, Jens Vogel-Claussen, Frank K. Wacker, Marius M. Höper, Bernhard C. Meyer, “COVID-19 Image Repository,” DOI: 10.6084/m9.figshare.12275009
OpenCV: Morphological Transformations https://docs.opencv.org/3.4/d9/d61/tutorial_py_morphological_ops.html
Kushol R., Nishat R. M., Rahman A. B. M. A., Salekin M. M., “Contrast Enhancement of Medical X-Ray Image Using Morphological Operators with Optimal Structuring Element,” arXiv:1905.08545v1 [cs.CV] 27 May 2019
Hinrich B. Winther, Hans Laser, Svetlana Gerbel, Sabine K. Maschke, Jan B. Hinrichs, Jens Vogel-Claussen, Frank K. Wacker, Marius M. Höper, Bernhard C. Meyer, “COVID-19 Image Repository,” DOI: 10.6084/m9.figshare.12275009
|
[
{
"code": null,
"e": 639,
"s": 166,
"text": "Contrast Enhancement is a very common image processing technique for enhancing features in low contrast images. Several methods like Contrast Stretching, Histogram Equalization, Adaptive Histogram Equalization, Contrast-Limited Adaptive Histogram Equalization or CLAHE, etc. have been used for enhancing the contrast of images. In this article, we will look at another method of Contrast Enhancement which is performed using a combination of Morphological Transformations."
},
{
"code": null,
"e": 1210,
"s": 639,
"text": "Morphological Transformations or Morphological Operators are simple image transformations that are usually applied on binary images, but can be applied to grayscale images as well. There are various types of Morphological Transformations like Erosion, Dilation, Opening, Closing, Gradient, Top Hat and the Black Hat. The two main components of these transformations are the input image and a kernel which is known as Structuring Element (SE). Before we jump on to the different types of Morphological Transformations in detail, let us understand the Structuring Element."
},
{
"code": null,
"e": 1479,
"s": 1210,
"text": "The Structuring Element (SE) is the neighborhood around each pixel that is examined while performing the morphological operations. Structuring Element can be of different shapes and sizes, and changing it can significantly impact the performance of the transformation."
},
{
"code": null,
"e": 1635,
"s": 1479,
"text": "There are three shapes of the Structuring Element provided by OpenCV — Rectangular, Elliptical and Cross-Shaped. The figure below shows these three shapes."
},
{
"code": null,
"e": 1687,
"s": 1635,
"text": "The different types of Morphological Operators are:"
},
{
"code": null,
"e": 3546,
"s": 1687,
"text": "Erosion — According to the OpenCV Documentation, the Erosion operator works similar to soil erosion. It “erodes”, or in simpler words, removes the boundaries of the foreground object in the image. The pixels at the boundary of the foreground object are removed. It reduces the size of the object in the image.Dilation — Dilation works exactly opposite to erosion. It “dilates” or expands the boundaries of the foreground object which in turn increases the size of the object in the image. This is useful if we want to join broken parts of the foreground object.Opening — The Opening operation is used in noise removal. It is done by first applying the erosion operation, followed by the dilation operation. The erosion operation first removes all the small noisy areas from the image and then dilation is applied to restore the original size of the object.Closing — The Closing is the opposite of Opening, which means that dilation is applied first followed by erosion. This is useful for joining or filling small spots that are present in the foreground object, while retaining the size of the object.Gradient — Morphological Gradient of an image is obtained by subtracting the erosion result from the dilation result. The result of the Gradient operation is the outline of the foreground object in the image.Top Hat / White Hat— Top Hat Transform, also known as the White Hat Transform, is obtained by removing or subtracting the Opening of the image from the original image. This operator gives us the bright features in the image that are smaller than the Structuring Element.Black Hat / Bottom Hat— The Black Hat Transform, also known as the Bottom Hat Transform, is obtained by removing or subtracting the Closing of the image from the original image. This operator gives us the dark features in the image that are smaller than the Structuring Element."
},
{
"code": null,
"e": 3856,
"s": 3546,
"text": "Erosion — According to the OpenCV Documentation, the Erosion operator works similar to soil erosion. It “erodes”, or in simpler words, removes the boundaries of the foreground object in the image. The pixels at the boundary of the foreground object are removed. It reduces the size of the object in the image."
},
{
"code": null,
"e": 4109,
"s": 3856,
"text": "Dilation — Dilation works exactly opposite to erosion. It “dilates” or expands the boundaries of the foreground object which in turn increases the size of the object in the image. This is useful if we want to join broken parts of the foreground object."
},
{
"code": null,
"e": 4405,
"s": 4109,
"text": "Opening — The Opening operation is used in noise removal. It is done by first applying the erosion operation, followed by the dilation operation. The erosion operation first removes all the small noisy areas from the image and then dilation is applied to restore the original size of the object."
},
{
"code": null,
"e": 4652,
"s": 4405,
"text": "Closing — The Closing is the opposite of Opening, which means that dilation is applied first followed by erosion. This is useful for joining or filling small spots that are present in the foreground object, while retaining the size of the object."
},
{
"code": null,
"e": 4861,
"s": 4652,
"text": "Gradient — Morphological Gradient of an image is obtained by subtracting the erosion result from the dilation result. The result of the Gradient operation is the outline of the foreground object in the image."
},
{
"code": null,
"e": 5132,
"s": 4861,
"text": "Top Hat / White Hat— Top Hat Transform, also known as the White Hat Transform, is obtained by removing or subtracting the Opening of the image from the original image. This operator gives us the bright features in the image that are smaller than the Structuring Element."
},
{
"code": null,
"e": 5411,
"s": 5132,
"text": "Black Hat / Bottom Hat— The Black Hat Transform, also known as the Bottom Hat Transform, is obtained by removing or subtracting the Closing of the image from the original image. This operator gives us the dark features in the image that are smaller than the Structuring Element."
},
{
"code": null,
"e": 5496,
"s": 5411,
"text": "Note: The Top Hat and the Black Hat transforms are more suited for grayscale images."
},
{
"code": null,
"e": 5570,
"s": 5496,
"text": "Contrast Enhancement, in simple words, requires the following to be done:"
},
{
"code": null,
"e": 5663,
"s": 5570,
"text": "Making the bright regions in the image brighter.Making the dark regions in the image darker."
},
{
"code": null,
"e": 5712,
"s": 5663,
"text": "Making the bright regions in the image brighter."
},
{
"code": null,
"e": 5757,
"s": 5712,
"text": "Making the dark regions in the image darker."
},
{
"code": null,
"e": 6113,
"s": 5757,
"text": "As we had seen earlier, the result of the Top Hat Transform is an image consisting of all the bright features in the input image and the result of the Black Hat Transform is an image consisting of all the dark features in the input image. Thus, for the purpose of Contrast Enhancement, we will need the Top and the Black Hat Transforms of the input image."
},
{
"code": null,
"e": 6372,
"s": 6113,
"text": "After obtaining the Top and Black Hat Transforms of the input image, we will add the Top Hat Transform to the input image in order to make its bright regions brighter, and subtract the Black Hat Transform from the input image to make its dark regions darker."
},
{
"code": null,
"e": 6444,
"s": 6372,
"text": "The step mentioned above can be represented as an equation shown below:"
},
{
"code": null,
"e": 6562,
"s": 6444,
"text": "where R is the result image, I is the input image, T and B are the Top Hat and the Black Hat transforms respectively."
},
{
"code": null,
"e": 6640,
"s": 6562,
"text": "The flowchart below depicts the steps we will follow to enhance the contrast."
},
{
"code": null,
"e": 6774,
"s": 6640,
"text": "We will implement this Contrast Enhancement technique using Python and OpenCV. We will need to first install opencv-python using pip."
},
{
"code": null,
"e": 6800,
"s": 6774,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 6865,
"s": 6800,
"text": "After installing OpenCV, we will import the library in our code."
},
{
"code": null,
"e": 6882,
"s": 6865,
"text": "import cv2 as cv"
},
{
"code": null,
"e": 6985,
"s": 6882,
"text": "We will use the below image for our code, which is taken from the COVID-19 Image Repository on GitHub."
},
{
"code": null,
"e": 7215,
"s": 6985,
"text": "The image data in this repository has been collected from the Institute for Diagnostic and Interventional Radiology, Hannover Medical School, Hannover, Germany and are licensed under the Creative Commons Attribution 3.0 Unported."
},
{
"code": null,
"e": 7284,
"s": 7215,
"text": "I have scaled down the image by 50% to reduce the size of the image."
},
{
"code": null,
"e": 7347,
"s": 7284,
"text": "To read this image, we will use the imread function by OpenCV."
},
{
"code": null,
"e": 7410,
"s": 7347,
"text": "filename = # path to the image fileimg = cv.imread(filename,0)"
},
{
"code": null,
"e": 7661,
"s": 7410,
"text": "Now that we have our image, we will obtain the Top and the Black Hat Transforms of this image. Before this, we need to construct our Structuring Element or the kernel. We can use the getStructuringElement function provided by OpenCV for this purpose."
},
{
"code": null,
"e": 7719,
"s": 7661,
"text": "kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(5,5))"
},
{
"code": null,
"e": 7896,
"s": 7719,
"text": "In the above snippet, we have constructed an elliptical Structuring Element of size (5,5). You can experiment by changing these parameters and observe the effect on the output."
},
{
"code": null,
"e": 8008,
"s": 7896,
"text": "The next step is to get the transforms of the input image using the kernel we constructed in the previous step."
},
{
"code": null,
"e": 8161,
"s": 8008,
"text": "# Top Hat TransformtopHat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)# Black Hat TransformblackHat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)"
},
{
"code": null,
"e": 8243,
"s": 8161,
"text": "Once we have our transforms, we will apply the equation that we had seen earlier."
},
{
"code": null,
"e": 8273,
"s": 8243,
"text": "res = img + topHat - blackHat"
},
{
"code": null,
"e": 8536,
"s": 8273,
"text": "We can see the contrast of the input image has improved a bit. Some of the minute features, that were not prominent in the input image, are now visible. However, this technique also adds some noise to the image if the Structuring Element is not chosen carefully."
},
{
"code": null,
"e": 8895,
"s": 8536,
"text": "For example, the image below shows the output when an elliptical Structuring Element was chosen of size (15,15). The minute features in the lungs and the edges of the bones are now more prominent and clear than the earlier output, but we can see some noisy areas in the output image, near the boundaries of the body, i.e. the white patches in the background."
},
{
"code": null,
"e": 9164,
"s": 8895,
"text": "As you go on increasing the size of the Structuring Element, the foreground features will become more prominent but the background will start becoming more and more noisy. The output below with Structuring Element of size (35,35) has more noisy area in the background."
},
{
"code": null,
"e": 9407,
"s": 9164,
"text": "Thus, we saw how to enhance the contrast of grayscale images using a combination of Top Hat and Black Hat Morphological Operations. Some of the minute features were greatly enhanced and became more prominent in our output image as seen above."
},
{
"code": null,
"e": 10442,
"s": 9407,
"text": "This method might not work as efficiently as the original Contrast Stretching method due to the noise it introduces in the image, as we go on increasing the size of our Structuring Element.As the Structuring Element is basically the size of the neighborhood to consider while applying the transformations, the output will also depend on the size of the input image. For example, a (35,35) kernel for an image of size 1000 x 1000 will form a smaller region as compared to a (35,35) kernel for a 250 x 250 image. Thus, resizing the image will also affect the output of this method.As Top and Black Hat Transforms give us the brighter and darker features respectively that are smaller than the Structuring Element, this method of Contrast Enhancement will work well if the size of the features to enhance are smaller than the size of our chosen Structuring Element. Thus, it becomes difficult to accurately enhance the contrast of larger features, as greater sizes of our kernel will introduce larger noisy areas in our image background."
},
{
"code": null,
"e": 10632,
"s": 10442,
"text": "This method might not work as efficiently as the original Contrast Stretching method due to the noise it introduces in the image, as we go on increasing the size of our Structuring Element."
},
{
"code": null,
"e": 11023,
"s": 10632,
"text": "As the Structuring Element is basically the size of the neighborhood to consider while applying the transformations, the output will also depend on the size of the input image. For example, a (35,35) kernel for an image of size 1000 x 1000 will form a smaller region as compared to a (35,35) kernel for a 250 x 250 image. Thus, resizing the image will also affect the output of this method."
},
{
"code": null,
"e": 11479,
"s": 11023,
"text": "As Top and Black Hat Transforms give us the brighter and darker features respectively that are smaller than the Structuring Element, this method of Contrast Enhancement will work well if the size of the features to enhance are smaller than the size of our chosen Structuring Element. Thus, it becomes difficult to accurately enhance the contrast of larger features, as greater sizes of our kernel will introduce larger noisy areas in our image background."
},
{
"code": null,
"e": 11568,
"s": 11479,
"text": "Thank you for reading! :) You can connect with me on LinkedIn if you have any questions."
},
{
"code": null,
"e": 12106,
"s": 11568,
"text": "OpenCV: Morphological Transformations https://docs.opencv.org/3.4/d9/d61/tutorial_py_morphological_ops.htmlKushol R., Nishat R. M., Rahman A. B. M. A., Salekin M. M., “Contrast Enhancement of Medical X-Ray Image Using Morphological Operators with Optimal Structuring Element,” arXiv:1905.08545v1 [cs.CV] 27 May 2019Hinrich B. Winther, Hans Laser, Svetlana Gerbel, Sabine K. Maschke, Jan B. Hinrichs, Jens Vogel-Claussen, Frank K. Wacker, Marius M. Höper, Bernhard C. Meyer, “COVID-19 Image Repository,” DOI: 10.6084/m9.figshare.12275009"
},
{
"code": null,
"e": 12214,
"s": 12106,
"text": "OpenCV: Morphological Transformations https://docs.opencv.org/3.4/d9/d61/tutorial_py_morphological_ops.html"
},
{
"code": null,
"e": 12423,
"s": 12214,
"text": "Kushol R., Nishat R. M., Rahman A. B. M. A., Salekin M. M., “Contrast Enhancement of Medical X-Ray Image Using Morphological Operators with Optimal Structuring Element,” arXiv:1905.08545v1 [cs.CV] 27 May 2019"
}
] |
How to add a title to an existing line border in Java?
|
Here, we will see how to add a title to an existing Line border. Let’s say we have a label and the border is to be set −
LineBorder linedBorder = new LineBorder(Color.blue);
TitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, "Demo Title");
JLabel label = new JLabel();
label.setBorder(titledBorder);
The following is an example to add a title to an existing line border −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SwingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LineBorder linedBorder = new LineBorder(Color.blue);
TitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, "Demo Title");
JLabel label = new JLabel();
label.setBorder(titledBorder);
Container contentPane = frame.getContentPane();
contentPane.add(label, BorderLayout.CENTER);
frame.setSize(550, 300);
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Here, we will see how to add a title to an existing Line border. Let’s say we have a label and the border is to be set −"
},
{
"code": null,
"e": 1385,
"s": 1183,
"text": "LineBorder linedBorder = new LineBorder(Color.blue);\nTitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, \"Demo Title\");\nJLabel label = new JLabel();\nlabel.setBorder(titledBorder);"
},
{
"code": null,
"e": 1457,
"s": 1385,
"text": "The following is an example to add a title to an existing line border −"
},
{
"code": null,
"e": 2284,
"s": 1457,
"text": "package my;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Container;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.border.LineBorder;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n LineBorder linedBorder = new LineBorder(Color.blue);\n TitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, \"Demo Title\");\n JLabel label = new JLabel();\n label.setBorder(titledBorder);\n Container contentPane = frame.getContentPane();\n contentPane.add(label, BorderLayout.CENTER);\n frame.setSize(550, 300);\n frame.setVisible(true);\n }\n}"
}
] |
How to standardize matrix elements in R?
|
The standardization is the process of converting a value to another value so that the mean of the set of values from which the original value was taken becomes zero and the standard deviation becomes one. To standardize matrix elements, we can use data.Normalization function of clusterSim package but we need to make sure that we set the type argument to n1 because that corresponds to standardization with mean zero and standard deviation 1.
Loading clusterSim package −
library("clusterSim")
Live Demo
M1<-matrix(rnorm(25,5,1),ncol=5)
M1
[,1] [,2] [,3] [,4] [,5]
[1,] 5.556224 2.934854 6.239076 4.501244 5.697287
[2,] 5.663404 4.404059 4.458465 2.875686 2.939572
[3,] 4.254188 4.168798 5.716965 5.003396 5.501523
[4,] 4.720976 5.032672 5.511445 4.678973 5.289942
[5,] 2.882521 5.694891 4.996887 4.825759 3.951424
data.Normalization(M1,type="n1")
[,1] [,2] [,3] [,4] [,5]
[1,] -0.84326235 -1.4331856 0.03959949 0.006214853 -0.6799208
[2,] 0.93062056 0.5714407 -0.31945831 0.065871281 -0.7808809
[3,] -1.18376086 -0.6408459 0.33301120 -0.026702496 -0.6877277
[4,] 1.00673967 0.5514687 -1.40208868 -1.435823004 1.3452576
[5,] 0.08966297 0.9511221 1.34893630 1.390439366 0.8032717
attr(,"normalized:shift")
1 2 3 4 5
5.473020 4.598571 5.143872 4.673848 4.880121
attr(,"normalized:scale")
1 2 3 4 5
1.0620129 0.9269254 0.9739280 1.2254604 0.9488868
Live Demo
M2<-matrix(rpois(100,10),ncol=10)
M2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 15 10 14 15 5 3 11 11 11 7
[2,] 10 8 6 13 4 15 8 6 13 14
[3,] 2 10 5 15 4 10 9 7 6 13
[4,] 12 5 14 11 7 13 8 12 8 7
[5,] 11 11 12 15 10 9 9 12 19 8
[6,] 10 12 8 9 6 12 10 15 11 10
[7,] 13 12 11 9 7 8 17 17 18 13
[8,] 11 8 8 6 10 6 9 8 13 12
[9,] 9 8 10 13 12 14 8 7 4 13
[10,] 7 10 4 7 14 8 10 13 11 11
data.Normalization(M2,type="n1")
data.Normalization(M2,type="n1")
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] -1.9409899 -0.8923761 1.86543426 -1.67507682 -1.1484061 -1.4356319
[2,] 0.9704950 1.5101749 -0.64037295 -0.09481567 -1.6477131 -0.8114441
[3,] 0.3234983 0.1372886 1.03016519 -0.09481567 1.8474359 -0.4993502
[4,] 0.3234983 0.8237318 -0.64037295 -1.04297236 0.3495149 2.3094948
[5,] 0.9704950 0.1372886 0.75174216 0.53728879 -0.1497921 -0.1872563
[6,] -0.3234983 1.5101749 0.19489612 -0.09481567 0.8488219 0.4369314
[7,] -0.6469966 -0.5491545 -1.47564202 -0.41086790 -0.6490991 -0.4993502
[8,] -0.9704950 -1.2355977 -0.08352691 -0.09481567 -0.1497921 0.4369314
[9,] 0.0000000 -0.8923761 -0.91879598 1.80149771 0.3495149 0.1248376
[10,] 1.2939933 -0.5491545 -0.08352691 1.16939325 0.3495149 0.1248376
[,7] [,8] [,9] [,10]
[1,] -0.9091373 2.07152663 0.76931647 1.4367622
[2,] 0.6060915 0.74362494 -0.62944075 -0.2535463
[3,] 1.2121831 -1.11543742 0.06993786 0.1690309
[4,] -1.5152288 0.21246427 0.06993786 -0.6761234
[5,] -0.6060915 -0.84985708 -0.27975144 -1.5212777
[6,] -0.3030458 0.47804461 -1.67850865 -0.6761234
[7,] -0.9091373 -0.05311607 0.06993786 0.5916080
[8,] 1.5152288 -0.05311607 0.06993786 1.0141851
[9,] 0.3030458 -0.05311607 2.16807368 1.0141851
[10,] 0.6060915 -1.38101775 -0.62944075 -1.0987005
attr(,"normalized:shift")
1 2 3 4 5 6 7 8 9 10 12.0 10.6 10.3 9.3 10.3 10.6 10.0 9.2 8.8 8.6
attr(,"normalized:scale")
1 2 3 4 5 6 7 8
3.091206 2.913570 3.591657 3.164034 2.002776 3.204164 3.299832 3.765339
9 10
2.859681 2.366432
Live Demo
M3<-matrix(round(runif(36,2,10),0),ncol=6)
M3
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 4 9 4 8 7 5
[2,] 8 3 9 7 9 3
[3,] 9 3 8 4 9 4
[4,] 6 10 4 7 3 3
[5,] 7 8 10 9 4 6
[6,] 7 9 6 9 3 7
data.Normalization(M3,type="n1")
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0.8017837 1.4647150 1.5430335 -0.6358384 0.1331559 0.8017837
[2,] -1.3363062 -1.3315591 -0.7715167 -1.1808427 0.9320914 -0.2672612
[3,] -0.8017837 -0.5326236 0.1543033 1.5441789 -0.2663118 -0.8017837
[4,] -0.2672612 -0.5326236 -0.3086067 0.4541703 -1.0652473 -1.3363062
[5,] 0.2672612 0.6657796 -1.2344268 -0.6358384 -1.0652473 0.2672612
[6,] 1.3363062 0.2663118 0.6172134 0.4541703 1.3315591 1.3363062
attr(,"normalized:shift")
1 2 3 4 5 6
5.500000 5.333333 4.666667 5.166667 6.666667 6.500000
attr(,"normalized:scale")
1 2 3 4 5 6
1.870829 2.503331 2.160247 1.834848 2.503331 1.870829
Live Demo
M4<-matrix(rexp(16,0.50),nrow=4)
M4
[,1] [,2] [,3] [,4]
[1,] 1.8392684 0.1260047 1.8536475 0.3727895
[2,] 2.3926115 2.9282159 0.5356917 0.6675259
[3,] 0.6198705 5.3994087 0.7795360 1.6238094
[4,] 3.9293381 0.6119497 0.8212652 0.6498672
data.Normalization(M4,type="n1")
[,1] [,2] [,3] [,4]
[1,] -0.76247841 0.6334982 0.2251928 1.2625561
[2,] -0.08745082 -1.0914747 -0.8013569 -0.6296948
[3,] 1.43733539 -0.5780098 -0.7465997 -0.9525044
[4,] -0.58740616 1.0359864 1.3227638 0.3196432
attr(,"normalized:shift")
1 2 3 4
1.587821 1.762592 2.272075 3.611091
attr(,"normalized:scale")
1 2 3 4
0.4923935 1.5823407 2.2370054 1.3130271
|
[
{
"code": null,
"e": 1506,
"s": 1062,
"text": "The standardization is the process of converting a value to another value so that the mean of the set of values from which the original value was taken becomes zero and the standard deviation becomes one. To standardize matrix elements, we can use data.Normalization function of clusterSim package but we need to make sure that we set the type argument to n1 because that corresponds to standardization with mean zero and standard deviation 1."
},
{
"code": null,
"e": 1535,
"s": 1506,
"text": "Loading clusterSim package −"
},
{
"code": null,
"e": 1557,
"s": 1535,
"text": "library(\"clusterSim\")"
},
{
"code": null,
"e": 1568,
"s": 1557,
"text": " Live Demo"
},
{
"code": null,
"e": 1604,
"s": 1568,
"text": "M1<-matrix(rnorm(25,5,1),ncol=5)\nM1"
},
{
"code": null,
"e": 1879,
"s": 1604,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 5.556224 2.934854 6.239076 4.501244 5.697287\n[2,] 5.663404 4.404059 4.458465 2.875686 2.939572\n[3,] 4.254188 4.168798 5.716965 5.003396 5.501523\n[4,] 4.720976 5.032672 5.511445 4.678973 5.289942\n[5,] 2.882521 5.694891 4.996887 4.825759 3.951424"
},
{
"code": null,
"e": 1912,
"s": 1879,
"text": "data.Normalization(M1,type=\"n1\")"
},
{
"code": null,
"e": 2243,
"s": 1912,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] -0.84326235 -1.4331856 0.03959949 0.006214853 -0.6799208\n[2,] 0.93062056 0.5714407 -0.31945831 0.065871281 -0.7808809\n[3,] -1.18376086 -0.6408459 0.33301120 -0.026702496 -0.6877277\n[4,] 1.00673967 0.5514687 -1.40208868 -1.435823004 1.3452576\n[5,] 0.08966297 0.9511221 1.34893630 1.390439366 0.8032717"
},
{
"code": null,
"e": 2269,
"s": 2243,
"text": "attr(,\"normalized:shift\")"
},
{
"code": null,
"e": 2324,
"s": 2269,
"text": "1 2 3 4 5\n5.473020 4.598571 5.143872 4.673848 4.880121"
},
{
"code": null,
"e": 2350,
"s": 2324,
"text": "attr(,\"normalized:scale\")"
},
{
"code": null,
"e": 2410,
"s": 2350,
"text": "1 2 3 4 5\n1.0620129 0.9269254 0.9739280 1.2254604 0.9488868"
},
{
"code": null,
"e": 2421,
"s": 2410,
"text": " Live Demo"
},
{
"code": null,
"e": 2458,
"s": 2421,
"text": "M2<-matrix(rpois(100,10),ncol=10)\nM2"
},
{
"code": null,
"e": 2817,
"s": 2458,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 15 10 14 15 5 3 11 11 11 7\n[2,] 10 8 6 13 4 15 8 6 13 14\n[3,] 2 10 5 15 4 10 9 7 6 13\n[4,] 12 5 14 11 7 13 8 12 8 7\n[5,] 11 11 12 15 10 9 9 12 19 8\n[6,] 10 12 8 9 6 12 10 15 11 10\n[7,] 13 12 11 9 7 8 17 17 18 13\n[8,] 11 8 8 6 10 6 9 8 13 12\n[9,] 9 8 10 13 12 14 8 7 4 13\n[10,] 7 10 4 7 14 8 10 13 11 11"
},
{
"code": null,
"e": 2850,
"s": 2817,
"text": "data.Normalization(M2,type=\"n1\")"
},
{
"code": null,
"e": 4263,
"s": 2850,
"text": "data.Normalization(M2,type=\"n1\")\n [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] -1.9409899 -0.8923761 1.86543426 -1.67507682 -1.1484061 -1.4356319\n[2,] 0.9704950 1.5101749 -0.64037295 -0.09481567 -1.6477131 -0.8114441\n[3,] 0.3234983 0.1372886 1.03016519 -0.09481567 1.8474359 -0.4993502\n[4,] 0.3234983 0.8237318 -0.64037295 -1.04297236 0.3495149 2.3094948\n[5,] 0.9704950 0.1372886 0.75174216 0.53728879 -0.1497921 -0.1872563\n[6,] -0.3234983 1.5101749 0.19489612 -0.09481567 0.8488219 0.4369314\n[7,] -0.6469966 -0.5491545 -1.47564202 -0.41086790 -0.6490991 -0.4993502\n[8,] -0.9704950 -1.2355977 -0.08352691 -0.09481567 -0.1497921 0.4369314\n[9,] 0.0000000 -0.8923761 -0.91879598 1.80149771 0.3495149 0.1248376\n[10,] 1.2939933 -0.5491545 -0.08352691 1.16939325 0.3495149 0.1248376\n [,7] [,8] [,9] [,10]\n[1,] -0.9091373 2.07152663 0.76931647 1.4367622\n[2,] 0.6060915 0.74362494 -0.62944075 -0.2535463\n[3,] 1.2121831 -1.11543742 0.06993786 0.1690309\n[4,] -1.5152288 0.21246427 0.06993786 -0.6761234\n[5,] -0.6060915 -0.84985708 -0.27975144 -1.5212777\n[6,] -0.3030458 0.47804461 -1.67850865 -0.6761234\n[7,] -0.9091373 -0.05311607 0.06993786 0.5916080\n[8,] 1.5152288 -0.05311607 0.06993786 1.0141851\n[9,] 0.3030458 -0.05311607 2.16807368 1.0141851\n[10,] 0.6060915 -1.38101775 -0.62944075 -1.0987005"
},
{
"code": null,
"e": 4289,
"s": 4263,
"text": "attr(,\"normalized:shift\")"
},
{
"code": null,
"e": 4356,
"s": 4289,
"text": "1 2 3 4 5 6 7 8 9 10 12.0 10.6 10.3 9.3 10.3 10.6 10.0 9.2 8.8 8.6"
},
{
"code": null,
"e": 4382,
"s": 4356,
"text": "attr(,\"normalized:scale\")"
},
{
"code": null,
"e": 4493,
"s": 4382,
"text": "1 2 3 4 5 6 7 8\n3.091206 2.913570 3.591657 3.164034 2.002776 3.204164 3.299832 3.765339\n9 10\n2.859681 2.366432"
},
{
"code": null,
"e": 4504,
"s": 4493,
"text": " Live Demo"
},
{
"code": null,
"e": 4550,
"s": 4504,
"text": "M3<-matrix(round(runif(36,2,10),0),ncol=6)\nM3"
},
{
"code": null,
"e": 4789,
"s": 4550,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 4 9 4 8 7 5\n[2,] 8 3 9 7 9 3\n[3,] 9 3 8 4 9 4\n[4,] 6 10 4 7 3 3\n[5,] 7 8 10 9 4 6\n[6,] 7 9 6 9 3 7"
},
{
"code": null,
"e": 4822,
"s": 4789,
"text": "data.Normalization(M3,type=\"n1\")"
},
{
"code": null,
"e": 5316,
"s": 4822,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 0.8017837 1.4647150 1.5430335 -0.6358384 0.1331559 0.8017837\n[2,] -1.3363062 -1.3315591 -0.7715167 -1.1808427 0.9320914 -0.2672612\n[3,] -0.8017837 -0.5326236 0.1543033 1.5441789 -0.2663118 -0.8017837\n[4,] -0.2672612 -0.5326236 -0.3086067 0.4541703 -1.0652473 -1.3363062\n[5,] 0.2672612 0.6657796 -1.2344268 -0.6358384 -1.0652473 0.2672612\n[6,] 1.3363062 0.2663118 0.6172134 0.4541703 1.3315591 1.3363062"
},
{
"code": null,
"e": 5342,
"s": 5316,
"text": "attr(,\"normalized:shift\")"
},
{
"code": null,
"e": 5408,
"s": 5342,
"text": "1 2 3 4 5 6\n5.500000 5.333333 4.666667 5.166667 6.666667 6.500000"
},
{
"code": null,
"e": 5434,
"s": 5408,
"text": "attr(,\"normalized:scale\")"
},
{
"code": null,
"e": 5500,
"s": 5434,
"text": "1 2 3 4 5 6\n1.870829 2.503331 2.160247 1.834848 2.503331 1.870829"
},
{
"code": null,
"e": 5511,
"s": 5500,
"text": " Live Demo"
},
{
"code": null,
"e": 5547,
"s": 5511,
"text": "M4<-matrix(rexp(16,0.50),nrow=4)\nM4"
},
{
"code": null,
"e": 5769,
"s": 5547,
"text": " [,1] [,2] [,3] [,4]\n[1,] 1.8392684 0.1260047 1.8536475 0.3727895\n[2,] 2.3926115 2.9282159 0.5356917 0.6675259\n[3,] 0.6198705 5.3994087 0.7795360 1.6238094\n[4,] 3.9293381 0.6119497 0.8212652 0.6498672"
},
{
"code": null,
"e": 5802,
"s": 5769,
"text": "data.Normalization(M4,type=\"n1\")"
},
{
"code": null,
"e": 6056,
"s": 5802,
"text": " [,1] [,2] [,3] [,4]\n[1,] -0.76247841 0.6334982 0.2251928 1.2625561\n[2,] -0.08745082 -1.0914747 -0.8013569 -0.6296948\n[3,] 1.43733539 -0.5780098 -0.7465997 -0.9525044\n[4,] -0.58740616 1.0359864 1.3227638 0.3196432"
},
{
"code": null,
"e": 6082,
"s": 6056,
"text": "attr(,\"normalized:shift\")"
},
{
"code": null,
"e": 6126,
"s": 6082,
"text": "1 2 3 4\n1.587821 1.762592 2.272075 3.611091"
},
{
"code": null,
"e": 6152,
"s": 6126,
"text": "attr(,\"normalized:scale\")"
},
{
"code": null,
"e": 6200,
"s": 6152,
"text": "1 2 3 4\n0.4923935 1.5823407 2.2370054 1.3130271"
}
] |
CSS Overflow
|
The CSS overflow property controls what
happens to content that is too big to fit into an area.
The overflow property specifies whether to clip
the content or
to add scrollbars when the content of an element is too big to fit in the specified
area.
The overflow property has the following values:
visible - Default. The overflow is not clipped.
The content renders outside the element's box
hidden - The overflow is clipped, and the rest of the content will be invisible
scroll - The overflow is clipped, and a scrollbar is added to see the rest of the content
auto - Similar to scroll,
but it adds scrollbars only when necessary
Note: The overflow property only works for block elements with a specified height.
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).
By default, the overflow is visible, meaning that it is not clipped and it
renders outside the element's box:
With the hidden value, the overflow is clipped, and the rest of the content is hidden:
Setting the value to scroll, the overflow is clipped and a scrollbar is added to scroll inside the box. Note that this will add a scrollbar both horizontally and vertically (even if you do not need it):
The auto value is similar to scroll,
but it adds scrollbars only when necessary:
The overflow-x and overflow-y properties specifies
whether to change the overflow of content just horizontally or vertically (or
both):
overflow-x specifies what to do with the left/right edges of the
content.
overflow-y specifies what to do with the top/bottom edges of the
content.
Force a scroll bar to the <div> element with class="intro".
<style>
.intro {
width: 200px;
height: 70px;
: ;
}
</style>
<body>
<div class="intro">
Lorem ipsum dolor sit amet,consectetur adipiscing elit.Phasellus imperdiet, nulla et dictum interdum,nisi lorem egestas odio,vitae scelerisque enim ligula venenatis dolor.
</div>
</body>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 97,
"s": 0,
"text": "The CSS overflow property controls what \nhappens to content that is too big to fit into an area."
},
{
"code": null,
"e": 253,
"s": 97,
"text": "The overflow property specifies whether to clip \nthe content or \nto add scrollbars when the content of an element is too big to fit in the specified \narea."
},
{
"code": null,
"e": 301,
"s": 253,
"text": "The overflow property has the following values:"
},
{
"code": null,
"e": 396,
"s": 301,
"text": "visible - Default. The overflow is not clipped. \nThe content renders outside the element's box"
},
{
"code": null,
"e": 476,
"s": 396,
"text": "hidden - The overflow is clipped, and the rest of the content will be invisible"
},
{
"code": null,
"e": 566,
"s": 476,
"text": "scroll - The overflow is clipped, and a scrollbar is added to see the rest of the content"
},
{
"code": null,
"e": 636,
"s": 566,
"text": "auto - Similar to scroll, \nbut it adds scrollbars only when necessary"
},
{
"code": null,
"e": 719,
"s": 636,
"text": "Note: The overflow property only works for block elements with a specified height."
},
{
"code": null,
"e": 852,
"s": 719,
"text": "Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though \"overflow:scroll\" is set)."
},
{
"code": null,
"e": 963,
"s": 852,
"text": "By default, the overflow is visible, meaning that it is not clipped and it \nrenders outside the element's box:"
},
{
"code": null,
"e": 1050,
"s": 963,
"text": "With the hidden value, the overflow is clipped, and the rest of the content is hidden:"
},
{
"code": null,
"e": 1253,
"s": 1050,
"text": "Setting the value to scroll, the overflow is clipped and a scrollbar is added to scroll inside the box. Note that this will add a scrollbar both horizontally and vertically (even if you do not need it):"
},
{
"code": null,
"e": 1335,
"s": 1253,
"text": "The auto value is similar to scroll, \nbut it adds scrollbars only when necessary:"
},
{
"code": null,
"e": 1473,
"s": 1335,
"text": "The overflow-x and overflow-y properties specifies \nwhether to change the overflow of content just horizontally or vertically (or \nboth):"
},
{
"code": null,
"e": 1623,
"s": 1473,
"text": "overflow-x specifies what to do with the left/right edges of the \ncontent.\noverflow-y specifies what to do with the top/bottom edges of the \ncontent."
},
{
"code": null,
"e": 1683,
"s": 1623,
"text": "Force a scroll bar to the <div> element with class=\"intro\"."
},
{
"code": null,
"e": 1967,
"s": 1683,
"text": "<style>\n.intro {\n width: 200px;\n height: 70px;\n : ;\n}\n</style>\n\n<body>\n\n<div class=\"intro\">\nLorem ipsum dolor sit amet,consectetur adipiscing elit.Phasellus imperdiet, nulla et dictum interdum,nisi lorem egestas odio,vitae scelerisque enim ligula venenatis dolor.\n</div>\n\n</body>\n"
},
{
"code": null,
"e": 1986,
"s": 1967,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2019,
"s": 1986,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2061,
"s": 2019,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2168,
"s": 2061,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2187,
"s": 2168,
"text": "[email protected]"
}
] |
How to Solve the Real Big Data Problems - Load Huge Excel Files | by Shravankumar Suvarna | Towards Data Science
|
More and more companies have started to realize the importance of data. Hence, they come with requests to load huge CSV or Excel files from their legacy systems or manual processes to a database for data-driven analytics. I know, we now have a lot of solutions to solve this problem like pandas, dask, vaex python libraries or tools like Informatica etc.
However, it’s always fun to learn different approaches to solve a problem statement. We will be using PDI to solve this problem statement and use PostgreSQL as our database. The idea here will be to optimally utilize our system capabilities. I know not all of us have the perk of memory-optimized servers at our disposal.
If you are new to data pipeline building process, then I will recommend you to go through the below story.
medium.com
PDI: Pentaho Data Integration installed on your system. You can use the link for a step-by-step installation guide.
PostgreSQL: We can use any relational or non-relational database as per our preference. If you want to follow along, then please use the link to install the same.
I like to define the user stories for our problem statement first. This helps me design the high-level architecture for the data pipeline. We need to always break the problem in small easy individual pieces.
I want to read huge a CSV file with economic data containing millions of records.I want to perform a lookup for each content in the data with a dimension/master table.I want to clean the data and remove NULL fields.I want to add a row-level condition. I want to append ‘_R’ if the status column contains the word ‘Revised’.I want to load the same in PostgreSQL database.
I want to read huge a CSV file with economic data containing millions of records.
I want to perform a lookup for each content in the data with a dimension/master table.
I want to clean the data and remove NULL fields.
I want to add a row-level condition. I want to append ‘_R’ if the status column contains the word ‘Revised’.
I want to load the same in PostgreSQL database.
We are trying to replicate the real-world scenario by adding a little complexity of data manipulation as well.
It is a good practice to understand the input data files. Now, in our case, it might be difficult to open huge CSV files and check the columns and rows. However, there are methods by which we can determine or check sample data. PDI provides you to read sample data and check other metadata by creating a small transformation.
Here, I Googled the term ‘huge data file in csv’ and downloaded the file from the first website. Here’s the link.
Now, I wanted to crash the system and create huge file; like we are dealing with Big Data, right? The downloaded file had 66,526 records, so I appended the same records multiple times to create a huge file with around 11,974,697 records; yeah not that big.
Defining test cases are important here since we cannot manually check the entire data. We need to make sure, we check good enough sample data to cross-validate the accuracy.
Check the row count and match with input data. Please note, since we will be removing the NULL data. It is important to store those NULL records as well.Cross-validate the dimensions output results for at least 500 -1000 records.Cross-validate the calculation randomly to check for accuracy; again for at least a thousand records.
Check the row count and match with input data. Please note, since we will be removing the NULL data. It is important to store those NULL records as well.
Cross-validate the dimensions output results for at least 500 -1000 records.
Cross-validate the calculation randomly to check for accuracy; again for at least a thousand records.
We have a pretty simple project set up for this project. Just one directory and one transformation file.
I prefer to create all the work-related projects in one single project directory named ‘Work’; I know, how creative! We need to perform the below; you can skip this step.
Create our project directory - LoadData.Create a directory ‘Input’ within the project directory.Create an empty Transformation named ‘Main.ktr’ within the project directory.
Create our project directory - LoadData.
Create a directory ‘Input’ within the project directory.
Create an empty Transformation named ‘Main.ktr’ within the project directory.
If you are not aware of the words like transformations or job, then I will recommend the below-mentioned story.
medium.com
I am assuming that you have the database already installed here. We are using PostgreSQL.
Now, I prefer to create tables using Django Models. You don’t necessarily have to use this methodology.
Having said so, it makes our life easy by writing Django models instead of manually creating tables and column natively. Django models does that for us using the simple migrations command and also get CRUD (create, read, update and delete) functionality out of the box.
You can choose below mentioned two options to create the database and table. I have create a table medium_db
PostgreSQL create script.
— Table: public.economic_data — DROP TABLE public.economic_data;CREATE TABLE public.economic_data(id integer NOT NULL DEFAULT nextval(‘economic_data_id_seq’::regclass),series_reference character varying(255) COLLATE pg_catalog.”default” NOT NULL,indicator_name character varying(255) COLLATE pg_catalog.”default” NOT NULL,period character varying(45) COLLATE pg_catalog.”default” NOT NULL,indicator_value numeric(30,10) NOT NULL,status character varying(255) COLLATE pg_catalog.”default” NOT NULL,indicator_unit character varying(255) COLLATE pg_catalog.”default” NOT NULL,group_name character varying(255) COLLATE pg_catalog.”default” NOT NULL,series_name character varying(255) COLLATE pg_catalog.”default”, CONSTRAINT economic_data_pkey PRIMARY KEY (id))TABLESPACE pg_default;ALTER TABLE public.economic_dataOWNER to YOURUSER;
Django Model script to run migrations.
from django.db import models# Create your models here.class EconomicData(models.Model):series_reference = models.CharField(db_column="series_reference",max_length=255,help_text="Unique code to identify a particular record",verbose_name="Series Reference",)indicator_name = models.CharField(db_column="indicator_name",max_length=255,verbose_name="Name of the indicators")period = models.CharField(db_column="period",max_length=45,verbose_name="Period")indicator_value = models.DecimalField(db_column="indicator_value",max_digits=30,decimal_places=10,verbose_name="Value of the Field")status = models.CharField(db_column="status",max_length=255,verbose_name="Status of the value For eg, Final or Revised")indicator_unit = models.CharField(db_column="indicator_unit",max_length=255,verbose_name="Unit of the indicators")group_name = models.CharField(db_column="group_name",max_length=255,verbose_name="Group of the indicators")series_name = models.CharField(db_column="series_name",max_length=255,verbose_name="Series of the indicators"null=True)def __str__(self):return f"{self.indicator_name} - {self.value}"class Meta:db_table = "economic_data"verbose_name = "Economic Data"verbose_name_plural = "Economic Data"
If you are interested in understanding how we can benefit from Django in our data pipeline, then please do let me know the same in the response section below.
We have our table ready. Now, let create our transformation.
We need to create a loader transformation which read our input CSV, perform manipulation and load the data onto the database.
We need to open our Main.ktr file and drag some plugin as mentioned below.
Firstly, let’s add a small description about the transformation. Documentation is a key for any data pipeline.Drag ‘CSV file input’, ‘Data grid’, ‘Join rows (cartesian product)’, ‘User defined Java expression’, ‘Filter rows’, ‘Text file output’, ‘Table Output’ plugins from the design tab onto the canvas.Rename the fields as per our naming convention.
Firstly, let’s add a small description about the transformation. Documentation is a key for any data pipeline.
Drag ‘CSV file input’, ‘Data grid’, ‘Join rows (cartesian product)’, ‘User defined Java expression’, ‘Filter rows’, ‘Text file output’, ‘Table Output’ plugins from the design tab onto the canvas.
Rename the fields as per our naming convention.
We need to configure the properties for each of the above-mentioned steps. Let configure for our CSV input step, we need to browse for our input file in the Filename field and click on Get Fields. We can tweak the NIO buffer size as per our memory availability; it will process the files in batches of 50K records each.We need to add data in Data Grid (Replicating a table here). Here, we are using a data grid for example data. In a real-world scenario, you will get this data from some dimension table. We are standardizing the Group Names. You can refer the below screenshot for the data. We need to add column names in the Meta tab and actual data in the Data tab.In the Join rows step, we need to map the fields that we want from the input with our dimension table/grid. Since we are mapping groups here, we need to add the Condition to map the same.In the User defined java expression, we will configure the custom row-level condition. We need to define our New field as ‘series_reference_flag’, here we want to change the ‘Series_reference’ field and append ‘_R’ if the status column is ‘Revised’. In our Java expression, we will add the following condition - ‘status == “Revised”? Series_reference + “_R” : Series_reference’; this is java code. We can perform similar conditions or calculations, Powerful! Lastly, we need to add Value type to ‘String’.In the Filter rows step, we need to define our condition of passing records without null values.In the Text file output (error report), we need to add Filename as ‘${Internal.Entry.Current.Directory}/error_report’ and change the Extension to ‘CSV’.In Table output step, we need to create a new Connection to connect to our database. We can connect to any database as per our requirements. We here will connect to PostgreSQL; refer screenshot for connection details. We need to browse for the Target table to ‘economic_data’. We need to check the Specify database fields field. We then need to map the input/transformation fields to table fields.
We need to configure the properties for each of the above-mentioned steps. Let configure for our CSV input step, we need to browse for our input file in the Filename field and click on Get Fields. We can tweak the NIO buffer size as per our memory availability; it will process the files in batches of 50K records each.
We need to add data in Data Grid (Replicating a table here). Here, we are using a data grid for example data. In a real-world scenario, you will get this data from some dimension table. We are standardizing the Group Names. You can refer the below screenshot for the data. We need to add column names in the Meta tab and actual data in the Data tab.
In the Join rows step, we need to map the fields that we want from the input with our dimension table/grid. Since we are mapping groups here, we need to add the Condition to map the same.
In the User defined java expression, we will configure the custom row-level condition. We need to define our New field as ‘series_reference_flag’, here we want to change the ‘Series_reference’ field and append ‘_R’ if the status column is ‘Revised’. In our Java expression, we will add the following condition - ‘status == “Revised”? Series_reference + “_R” : Series_reference’; this is java code. We can perform similar conditions or calculations, Powerful! Lastly, we need to add Value type to ‘String’.
In the Filter rows step, we need to define our condition of passing records without null values.
In the Text file output (error report), we need to add Filename as ‘${Internal.Entry.Current.Directory}/error_report’ and change the Extension to ‘CSV’.
In Table output step, we need to create a new Connection to connect to our database. We can connect to any database as per our requirements. We here will connect to PostgreSQL; refer screenshot for connection details. We need to browse for the Target table to ‘economic_data’. We need to check the Specify database fields field. We then need to map the input/transformation fields to table fields.
Now that we have configured the properties, we can speed the process by creating multiple threads for inserting data. This will boost the performance. PDI provides us with the facility to configure multi-threading per steps. If we use it in an input step, it will multiply the records. Whereas, if we use it for output steps like database, it will distribute the records.
PDI provides us with many options to optimize the performance. We can perform the below steps to boost the performance.
Change the NIO buffer size in our in input step, define our batch size.Change Max. cache size (in rows) in lookup step, define the number of rows it will store in cache memory instead of querying to the database.Change Commit Size, similar to buffer size change the batch size to insert records.Use multiple threads to perform the activity, we can add a Dummy step and right-click to select Change Number of Copies to Start from 1 to anything above 1 as per our requirements before our output step.Please note, if we want to perform multiple threads on table output step, then we cannot use point number four. We will then have to add a Dummy step before output and distribute the records in multiple output table steps.
Change the NIO buffer size in our in input step, define our batch size.
Change Max. cache size (in rows) in lookup step, define the number of rows it will store in cache memory instead of querying to the database.
Change Commit Size, similar to buffer size change the batch size to insert records.
Use multiple threads to perform the activity, we can add a Dummy step and right-click to select Change Number of Copies to Start from 1 to anything above 1 as per our requirements before our output step.
Please note, if we want to perform multiple threads on table output step, then we cannot use point number four. We will then have to add a Dummy step before output and distribute the records in multiple output table steps.
Wow! we have so many options, should we change all the performance optimizer? Short answer is NO. We need to try with sample data and perform multiple tests on what works best for us.
Let’s run the flow without performance optimizer and then compare it by applying the optimizer.
We reduced the time taken by almost 50% to perform the same activity by adding some simple performance optimizer.
If we want to read multiple files and create a loop to process the same, then I will recommend you to go through the below story.
towardsdatascience.com
We took a problem statement and tried solving it using multiple approaches and tried optimizing it as well. In theory, you can apply this process to fit your requirement and try to optimize it further as well. PDI provides us with PostgreSQL bulk loader step as well; I have tried that step as well. However, there was not any significant performance booster provided by the same.
We cannot optimize the code/pipeline at the beginning and will have to perform multiple tests to get the ideal results. However, to shorten the learning curve you can always read through my experiences and find solutions to the problem statement by subscribing to my email list using the below link.
|
[
{
"code": null,
"e": 526,
"s": 171,
"text": "More and more companies have started to realize the importance of data. Hence, they come with requests to load huge CSV or Excel files from their legacy systems or manual processes to a database for data-driven analytics. I know, we now have a lot of solutions to solve this problem like pandas, dask, vaex python libraries or tools like Informatica etc."
},
{
"code": null,
"e": 848,
"s": 526,
"text": "However, it’s always fun to learn different approaches to solve a problem statement. We will be using PDI to solve this problem statement and use PostgreSQL as our database. The idea here will be to optimally utilize our system capabilities. I know not all of us have the perk of memory-optimized servers at our disposal."
},
{
"code": null,
"e": 955,
"s": 848,
"text": "If you are new to data pipeline building process, then I will recommend you to go through the below story."
},
{
"code": null,
"e": 966,
"s": 955,
"text": "medium.com"
},
{
"code": null,
"e": 1082,
"s": 966,
"text": "PDI: Pentaho Data Integration installed on your system. You can use the link for a step-by-step installation guide."
},
{
"code": null,
"e": 1245,
"s": 1082,
"text": "PostgreSQL: We can use any relational or non-relational database as per our preference. If you want to follow along, then please use the link to install the same."
},
{
"code": null,
"e": 1453,
"s": 1245,
"text": "I like to define the user stories for our problem statement first. This helps me design the high-level architecture for the data pipeline. We need to always break the problem in small easy individual pieces."
},
{
"code": null,
"e": 1824,
"s": 1453,
"text": "I want to read huge a CSV file with economic data containing millions of records.I want to perform a lookup for each content in the data with a dimension/master table.I want to clean the data and remove NULL fields.I want to add a row-level condition. I want to append ‘_R’ if the status column contains the word ‘Revised’.I want to load the same in PostgreSQL database."
},
{
"code": null,
"e": 1906,
"s": 1824,
"text": "I want to read huge a CSV file with economic data containing millions of records."
},
{
"code": null,
"e": 1993,
"s": 1906,
"text": "I want to perform a lookup for each content in the data with a dimension/master table."
},
{
"code": null,
"e": 2042,
"s": 1993,
"text": "I want to clean the data and remove NULL fields."
},
{
"code": null,
"e": 2151,
"s": 2042,
"text": "I want to add a row-level condition. I want to append ‘_R’ if the status column contains the word ‘Revised’."
},
{
"code": null,
"e": 2199,
"s": 2151,
"text": "I want to load the same in PostgreSQL database."
},
{
"code": null,
"e": 2310,
"s": 2199,
"text": "We are trying to replicate the real-world scenario by adding a little complexity of data manipulation as well."
},
{
"code": null,
"e": 2636,
"s": 2310,
"text": "It is a good practice to understand the input data files. Now, in our case, it might be difficult to open huge CSV files and check the columns and rows. However, there are methods by which we can determine or check sample data. PDI provides you to read sample data and check other metadata by creating a small transformation."
},
{
"code": null,
"e": 2750,
"s": 2636,
"text": "Here, I Googled the term ‘huge data file in csv’ and downloaded the file from the first website. Here’s the link."
},
{
"code": null,
"e": 3007,
"s": 2750,
"text": "Now, I wanted to crash the system and create huge file; like we are dealing with Big Data, right? The downloaded file had 66,526 records, so I appended the same records multiple times to create a huge file with around 11,974,697 records; yeah not that big."
},
{
"code": null,
"e": 3181,
"s": 3007,
"text": "Defining test cases are important here since we cannot manually check the entire data. We need to make sure, we check good enough sample data to cross-validate the accuracy."
},
{
"code": null,
"e": 3512,
"s": 3181,
"text": "Check the row count and match with input data. Please note, since we will be removing the NULL data. It is important to store those NULL records as well.Cross-validate the dimensions output results for at least 500 -1000 records.Cross-validate the calculation randomly to check for accuracy; again for at least a thousand records."
},
{
"code": null,
"e": 3666,
"s": 3512,
"text": "Check the row count and match with input data. Please note, since we will be removing the NULL data. It is important to store those NULL records as well."
},
{
"code": null,
"e": 3743,
"s": 3666,
"text": "Cross-validate the dimensions output results for at least 500 -1000 records."
},
{
"code": null,
"e": 3845,
"s": 3743,
"text": "Cross-validate the calculation randomly to check for accuracy; again for at least a thousand records."
},
{
"code": null,
"e": 3950,
"s": 3845,
"text": "We have a pretty simple project set up for this project. Just one directory and one transformation file."
},
{
"code": null,
"e": 4121,
"s": 3950,
"text": "I prefer to create all the work-related projects in one single project directory named ‘Work’; I know, how creative! We need to perform the below; you can skip this step."
},
{
"code": null,
"e": 4295,
"s": 4121,
"text": "Create our project directory - LoadData.Create a directory ‘Input’ within the project directory.Create an empty Transformation named ‘Main.ktr’ within the project directory."
},
{
"code": null,
"e": 4336,
"s": 4295,
"text": "Create our project directory - LoadData."
},
{
"code": null,
"e": 4393,
"s": 4336,
"text": "Create a directory ‘Input’ within the project directory."
},
{
"code": null,
"e": 4471,
"s": 4393,
"text": "Create an empty Transformation named ‘Main.ktr’ within the project directory."
},
{
"code": null,
"e": 4583,
"s": 4471,
"text": "If you are not aware of the words like transformations or job, then I will recommend the below-mentioned story."
},
{
"code": null,
"e": 4594,
"s": 4583,
"text": "medium.com"
},
{
"code": null,
"e": 4684,
"s": 4594,
"text": "I am assuming that you have the database already installed here. We are using PostgreSQL."
},
{
"code": null,
"e": 4788,
"s": 4684,
"text": "Now, I prefer to create tables using Django Models. You don’t necessarily have to use this methodology."
},
{
"code": null,
"e": 5058,
"s": 4788,
"text": "Having said so, it makes our life easy by writing Django models instead of manually creating tables and column natively. Django models does that for us using the simple migrations command and also get CRUD (create, read, update and delete) functionality out of the box."
},
{
"code": null,
"e": 5167,
"s": 5058,
"text": "You can choose below mentioned two options to create the database and table. I have create a table medium_db"
},
{
"code": null,
"e": 5193,
"s": 5167,
"text": "PostgreSQL create script."
},
{
"code": null,
"e": 6024,
"s": 5193,
"text": " — Table: public.economic_data — DROP TABLE public.economic_data;CREATE TABLE public.economic_data(id integer NOT NULL DEFAULT nextval(‘economic_data_id_seq’::regclass),series_reference character varying(255) COLLATE pg_catalog.”default” NOT NULL,indicator_name character varying(255) COLLATE pg_catalog.”default” NOT NULL,period character varying(45) COLLATE pg_catalog.”default” NOT NULL,indicator_value numeric(30,10) NOT NULL,status character varying(255) COLLATE pg_catalog.”default” NOT NULL,indicator_unit character varying(255) COLLATE pg_catalog.”default” NOT NULL,group_name character varying(255) COLLATE pg_catalog.”default” NOT NULL,series_name character varying(255) COLLATE pg_catalog.”default”, CONSTRAINT economic_data_pkey PRIMARY KEY (id))TABLESPACE pg_default;ALTER TABLE public.economic_dataOWNER to YOURUSER;"
},
{
"code": null,
"e": 6063,
"s": 6024,
"text": "Django Model script to run migrations."
},
{
"code": null,
"e": 7275,
"s": 6063,
"text": "from django.db import models# Create your models here.class EconomicData(models.Model):series_reference = models.CharField(db_column=\"series_reference\",max_length=255,help_text=\"Unique code to identify a particular record\",verbose_name=\"Series Reference\",)indicator_name = models.CharField(db_column=\"indicator_name\",max_length=255,verbose_name=\"Name of the indicators\")period = models.CharField(db_column=\"period\",max_length=45,verbose_name=\"Period\")indicator_value = models.DecimalField(db_column=\"indicator_value\",max_digits=30,decimal_places=10,verbose_name=\"Value of the Field\")status = models.CharField(db_column=\"status\",max_length=255,verbose_name=\"Status of the value For eg, Final or Revised\")indicator_unit = models.CharField(db_column=\"indicator_unit\",max_length=255,verbose_name=\"Unit of the indicators\")group_name = models.CharField(db_column=\"group_name\",max_length=255,verbose_name=\"Group of the indicators\")series_name = models.CharField(db_column=\"series_name\",max_length=255,verbose_name=\"Series of the indicators\"null=True)def __str__(self):return f\"{self.indicator_name} - {self.value}\"class Meta:db_table = \"economic_data\"verbose_name = \"Economic Data\"verbose_name_plural = \"Economic Data\""
},
{
"code": null,
"e": 7434,
"s": 7275,
"text": "If you are interested in understanding how we can benefit from Django in our data pipeline, then please do let me know the same in the response section below."
},
{
"code": null,
"e": 7495,
"s": 7434,
"text": "We have our table ready. Now, let create our transformation."
},
{
"code": null,
"e": 7621,
"s": 7495,
"text": "We need to create a loader transformation which read our input CSV, perform manipulation and load the data onto the database."
},
{
"code": null,
"e": 7696,
"s": 7621,
"text": "We need to open our Main.ktr file and drag some plugin as mentioned below."
},
{
"code": null,
"e": 8049,
"s": 7696,
"text": "Firstly, let’s add a small description about the transformation. Documentation is a key for any data pipeline.Drag ‘CSV file input’, ‘Data grid’, ‘Join rows (cartesian product)’, ‘User defined Java expression’, ‘Filter rows’, ‘Text file output’, ‘Table Output’ plugins from the design tab onto the canvas.Rename the fields as per our naming convention."
},
{
"code": null,
"e": 8160,
"s": 8049,
"text": "Firstly, let’s add a small description about the transformation. Documentation is a key for any data pipeline."
},
{
"code": null,
"e": 8356,
"s": 8160,
"text": "Drag ‘CSV file input’, ‘Data grid’, ‘Join rows (cartesian product)’, ‘User defined Java expression’, ‘Filter rows’, ‘Text file output’, ‘Table Output’ plugins from the design tab onto the canvas."
},
{
"code": null,
"e": 8404,
"s": 8356,
"text": "Rename the fields as per our naming convention."
},
{
"code": null,
"e": 10410,
"s": 8404,
"text": "We need to configure the properties for each of the above-mentioned steps. Let configure for our CSV input step, we need to browse for our input file in the Filename field and click on Get Fields. We can tweak the NIO buffer size as per our memory availability; it will process the files in batches of 50K records each.We need to add data in Data Grid (Replicating a table here). Here, we are using a data grid for example data. In a real-world scenario, you will get this data from some dimension table. We are standardizing the Group Names. You can refer the below screenshot for the data. We need to add column names in the Meta tab and actual data in the Data tab.In the Join rows step, we need to map the fields that we want from the input with our dimension table/grid. Since we are mapping groups here, we need to add the Condition to map the same.In the User defined java expression, we will configure the custom row-level condition. We need to define our New field as ‘series_reference_flag’, here we want to change the ‘Series_reference’ field and append ‘_R’ if the status column is ‘Revised’. In our Java expression, we will add the following condition - ‘status == “Revised”? Series_reference + “_R” : Series_reference’; this is java code. We can perform similar conditions or calculations, Powerful! Lastly, we need to add Value type to ‘String’.In the Filter rows step, we need to define our condition of passing records without null values.In the Text file output (error report), we need to add Filename as ‘${Internal.Entry.Current.Directory}/error_report’ and change the Extension to ‘CSV’.In Table output step, we need to create a new Connection to connect to our database. We can connect to any database as per our requirements. We here will connect to PostgreSQL; refer screenshot for connection details. We need to browse for the Target table to ‘economic_data’. We need to check the Specify database fields field. We then need to map the input/transformation fields to table fields."
},
{
"code": null,
"e": 10730,
"s": 10410,
"text": "We need to configure the properties for each of the above-mentioned steps. Let configure for our CSV input step, we need to browse for our input file in the Filename field and click on Get Fields. We can tweak the NIO buffer size as per our memory availability; it will process the files in batches of 50K records each."
},
{
"code": null,
"e": 11080,
"s": 10730,
"text": "We need to add data in Data Grid (Replicating a table here). Here, we are using a data grid for example data. In a real-world scenario, you will get this data from some dimension table. We are standardizing the Group Names. You can refer the below screenshot for the data. We need to add column names in the Meta tab and actual data in the Data tab."
},
{
"code": null,
"e": 11268,
"s": 11080,
"text": "In the Join rows step, we need to map the fields that we want from the input with our dimension table/grid. Since we are mapping groups here, we need to add the Condition to map the same."
},
{
"code": null,
"e": 11774,
"s": 11268,
"text": "In the User defined java expression, we will configure the custom row-level condition. We need to define our New field as ‘series_reference_flag’, here we want to change the ‘Series_reference’ field and append ‘_R’ if the status column is ‘Revised’. In our Java expression, we will add the following condition - ‘status == “Revised”? Series_reference + “_R” : Series_reference’; this is java code. We can perform similar conditions or calculations, Powerful! Lastly, we need to add Value type to ‘String’."
},
{
"code": null,
"e": 11871,
"s": 11774,
"text": "In the Filter rows step, we need to define our condition of passing records without null values."
},
{
"code": null,
"e": 12024,
"s": 11871,
"text": "In the Text file output (error report), we need to add Filename as ‘${Internal.Entry.Current.Directory}/error_report’ and change the Extension to ‘CSV’."
},
{
"code": null,
"e": 12422,
"s": 12024,
"text": "In Table output step, we need to create a new Connection to connect to our database. We can connect to any database as per our requirements. We here will connect to PostgreSQL; refer screenshot for connection details. We need to browse for the Target table to ‘economic_data’. We need to check the Specify database fields field. We then need to map the input/transformation fields to table fields."
},
{
"code": null,
"e": 12794,
"s": 12422,
"text": "Now that we have configured the properties, we can speed the process by creating multiple threads for inserting data. This will boost the performance. PDI provides us with the facility to configure multi-threading per steps. If we use it in an input step, it will multiply the records. Whereas, if we use it for output steps like database, it will distribute the records."
},
{
"code": null,
"e": 12914,
"s": 12794,
"text": "PDI provides us with many options to optimize the performance. We can perform the below steps to boost the performance."
},
{
"code": null,
"e": 13635,
"s": 12914,
"text": "Change the NIO buffer size in our in input step, define our batch size.Change Max. cache size (in rows) in lookup step, define the number of rows it will store in cache memory instead of querying to the database.Change Commit Size, similar to buffer size change the batch size to insert records.Use multiple threads to perform the activity, we can add a Dummy step and right-click to select Change Number of Copies to Start from 1 to anything above 1 as per our requirements before our output step.Please note, if we want to perform multiple threads on table output step, then we cannot use point number four. We will then have to add a Dummy step before output and distribute the records in multiple output table steps."
},
{
"code": null,
"e": 13707,
"s": 13635,
"text": "Change the NIO buffer size in our in input step, define our batch size."
},
{
"code": null,
"e": 13849,
"s": 13707,
"text": "Change Max. cache size (in rows) in lookup step, define the number of rows it will store in cache memory instead of querying to the database."
},
{
"code": null,
"e": 13933,
"s": 13849,
"text": "Change Commit Size, similar to buffer size change the batch size to insert records."
},
{
"code": null,
"e": 14137,
"s": 13933,
"text": "Use multiple threads to perform the activity, we can add a Dummy step and right-click to select Change Number of Copies to Start from 1 to anything above 1 as per our requirements before our output step."
},
{
"code": null,
"e": 14360,
"s": 14137,
"text": "Please note, if we want to perform multiple threads on table output step, then we cannot use point number four. We will then have to add a Dummy step before output and distribute the records in multiple output table steps."
},
{
"code": null,
"e": 14544,
"s": 14360,
"text": "Wow! we have so many options, should we change all the performance optimizer? Short answer is NO. We need to try with sample data and perform multiple tests on what works best for us."
},
{
"code": null,
"e": 14640,
"s": 14544,
"text": "Let’s run the flow without performance optimizer and then compare it by applying the optimizer."
},
{
"code": null,
"e": 14754,
"s": 14640,
"text": "We reduced the time taken by almost 50% to perform the same activity by adding some simple performance optimizer."
},
{
"code": null,
"e": 14884,
"s": 14754,
"text": "If we want to read multiple files and create a loop to process the same, then I will recommend you to go through the below story."
},
{
"code": null,
"e": 14907,
"s": 14884,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15288,
"s": 14907,
"text": "We took a problem statement and tried solving it using multiple approaches and tried optimizing it as well. In theory, you can apply this process to fit your requirement and try to optimize it further as well. PDI provides us with PostgreSQL bulk loader step as well; I have tried that step as well. However, there was not any significant performance booster provided by the same."
}
] |
Java BeanUtils - BeanUtils and ConvertUtils
|
The BeanUtils is defined as a utility method for populating JavaBeans properties and ConvertUtils method converts string scalar values to objects, string arrays to arrays of the specified class.
The BeanUtils accepts string values by using the setter methods and automatically converts them to suitable property types for Java primitives and uses the getter methods for reverse conversion. The populate() method accepts set of property values from java.util.HashMap and uses the suitable setters whenever bean contain the property with the same name.
The below example shows usage of BeanUtils properties:
import java.util.HashMap;
import org.apache.commons.beanutils.BeanUtils;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args){
@SuppressWarnings("rawtypes")
HashMap map = new HashMap();
map.put("username","admin");
map.put("password","secret");
map.put("age","52");
User bean = new User();
try{
BeanUtils.populate(bean,map);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Username: "+bean.getUsername());
System.out.println("Password: "+bean.getPassword());
System.out.println("Age: "+bean.getAge());
}
}
Now we will create another class called User.java as shown below:
public class User {
private String username;
private String password;
private String age;
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password){
this.password = password;
}
public String getAge() {
return age;
}
public void setAge(String age){
this.age = age;
}
}
Let's carry out the following steps to see how above code works:
Save the above first code as Test.java.
Save the above first code as Test.java.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
The Apache Commons BeanUtils is a library that comes with a number of converters to convert to and from different data types and also contain ConvertUtils utility class which makes use of these converters.
The below example shows the conversion of string array to a double array using ConvertUtils utility:
package com.javadb;
import org.apache.commons.beanutils.ConvertUtils;
public class ConvertStringArrayToDoubleArray {
public static void main(String[] args) {
String values[] = { "5", "6", "3" };
double[] doubleValues = (double[])ConvertUtils.convert(values, Double.TYPE);
for (double d : doubleValues) {
System.out.println(d);
}
}
}
Save the above first code as ConvertStringArrayToDoubleArray.java.
Save the above first code as ConvertStringArrayToDoubleArray.java.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2351,
"s": 2156,
"text": "The BeanUtils is defined as a utility method for populating JavaBeans properties and ConvertUtils method converts string scalar values to objects, string arrays to arrays of the specified class."
},
{
"code": null,
"e": 2707,
"s": 2351,
"text": "The BeanUtils accepts string values by using the setter methods and automatically converts them to suitable property types for Java primitives and uses the getter methods for reverse conversion. The populate() method accepts set of property values from java.util.HashMap and uses the suitable setters whenever bean contain the property with the same name."
},
{
"code": null,
"e": 2762,
"s": 2707,
"text": "The below example shows usage of BeanUtils properties:"
},
{
"code": null,
"e": 3476,
"s": 2762,
"text": "import java.util.HashMap;\nimport org.apache.commons.beanutils.BeanUtils;\n\npublic class Test {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args){\n @SuppressWarnings(\"rawtypes\")\n HashMap map = new HashMap();\n map.put(\"username\",\"admin\");\n map.put(\"password\",\"secret\");\n map.put(\"age\",\"52\");\n \n User bean = new User();\n try{\n BeanUtils.populate(bean,map);\n }catch(Exception e){\n e.printStackTrace();\n }\n \n System.out.println(\"Username: \"+bean.getUsername());\n System.out.println(\"Password: \"+bean.getPassword());\n System.out.println(\"Age: \"+bean.getAge());\n }\n}"
},
{
"code": null,
"e": 3542,
"s": 3476,
"text": "Now we will create another class called User.java as shown below:"
},
{
"code": null,
"e": 4084,
"s": 3542,
"text": "public class User {\n private String username;\n private String password;\n private String age;\n \n public String getUsername(){\n return username;\n }\n \n public void setUsername(String username){\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\t\n public void setPassword(String password){\n this.password = password;\n }\n\n public String getAge() {\n return age;\n }\n\t\n public void setAge(String age){\n this.age = age;\n }\n}"
},
{
"code": null,
"e": 4149,
"s": 4084,
"text": "Let's carry out the following steps to see how above code works:"
},
{
"code": null,
"e": 4189,
"s": 4149,
"text": "Save the above first code as Test.java."
},
{
"code": null,
"e": 4229,
"s": 4189,
"text": "Save the above first code as Test.java."
},
{
"code": null,
"e": 4315,
"s": 4229,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 4401,
"s": 4315,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 4607,
"s": 4401,
"text": "The Apache Commons BeanUtils is a library that comes with a number of converters to convert to and from different data types and also contain ConvertUtils utility class which makes use of these converters."
},
{
"code": null,
"e": 4708,
"s": 4607,
"text": "The below example shows the conversion of string array to a double array using ConvertUtils utility:"
},
{
"code": null,
"e": 5097,
"s": 4708,
"text": "package com.javadb;\nimport org.apache.commons.beanutils.ConvertUtils;\n\npublic class ConvertStringArrayToDoubleArray {\n public static void main(String[] args) {\n String values[] = { \"5\", \"6\", \"3\" };\n double[] doubleValues = (double[])ConvertUtils.convert(values, Double.TYPE); \n for (double d : doubleValues) {\n System.out.println(d);\n }\n }\n}"
},
{
"code": null,
"e": 5164,
"s": 5097,
"text": "Save the above first code as ConvertStringArrayToDoubleArray.java."
},
{
"code": null,
"e": 5231,
"s": 5164,
"text": "Save the above first code as ConvertStringArrayToDoubleArray.java."
},
{
"code": null,
"e": 5317,
"s": 5231,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 5403,
"s": 5317,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 5436,
"s": 5403,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5452,
"s": 5436,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5485,
"s": 5452,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5501,
"s": 5485,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5536,
"s": 5501,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5550,
"s": 5536,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5584,
"s": 5550,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5598,
"s": 5584,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5635,
"s": 5598,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5650,
"s": 5635,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5683,
"s": 5650,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5702,
"s": 5683,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5709,
"s": 5702,
"text": " Print"
},
{
"code": null,
"e": 5720,
"s": 5709,
"text": " Add Notes"
}
] |
C | Pointer Basics | Question 6 - GeeksforGeeks
|
04 Feb, 2013
#include<stdio.h>int main(){ int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0;}
Assume that an int variable takes 4 bytes and a char variable takes 1 byte(A) Number of elements between two pointer are: 5.Number of bytes between two pointers are: 20(B) Number of elements between two pointer are: 20.Number of bytes between two pointers are: 20(C) Number of elements between two pointer are: 5.Number of bytes between two pointers are: 5(D) Compiler Error(E) Runtime ErrorAnswer: (A)Explanation: Array name gives the address of first element in array. So when we do ‘*ptr1 = arr;’, ptr1 starts holding the address of element 10. ‘arr + 5’ gives the address of 6th element as arithmetic is done using pointers. So ‘ptr2-ptr1’ gives 5. When we do ‘(char *)ptr2’, ptr2 is type-casted to char pointer and size of character is one byte, pointer arithmetic happens considering character pointers. So we get 5*sizeof(int)/sizeof(char) as a difference of two pointers.
C-Pointers
Pointers
C Language
C Quiz
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Misc | Question 7
Output of C programs | Set 64 (Pointers)
|
[
{
"code": null,
"e": 23979,
"s": 23951,
"text": "\n04 Feb, 2013"
},
{
"code": "#include<stdio.h>int main(){ int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf(\"Number of elements between two pointer are: %d.\", (ptr2 - ptr1)); printf(\"Number of bytes between two pointers are: %d\", (char*)ptr2 - (char*) ptr1); return 0;}",
"e": 24334,
"s": 23979,
"text": null
},
{
"code": null,
"e": 25214,
"s": 24334,
"text": "Assume that an int variable takes 4 bytes and a char variable takes 1 byte(A) Number of elements between two pointer are: 5.Number of bytes between two pointers are: 20(B) Number of elements between two pointer are: 20.Number of bytes between two pointers are: 20(C) Number of elements between two pointer are: 5.Number of bytes between two pointers are: 5(D) Compiler Error(E) Runtime ErrorAnswer: (A)Explanation: Array name gives the address of first element in array. So when we do ‘*ptr1 = arr;’, ptr1 starts holding the address of element 10. ‘arr + 5’ gives the address of 6th element as arithmetic is done using pointers. So ‘ptr2-ptr1’ gives 5. When we do ‘(char *)ptr2’, ptr2 is type-casted to char pointer and size of character is one byte, pointer arithmetic happens considering character pointers. So we get 5*sizeof(int)/sizeof(char) as a difference of two pointers."
},
{
"code": null,
"e": 25225,
"s": 25214,
"text": "C-Pointers"
},
{
"code": null,
"e": 25234,
"s": 25225,
"text": "Pointers"
},
{
"code": null,
"e": 25245,
"s": 25234,
"text": "C Language"
},
{
"code": null,
"e": 25252,
"s": 25245,
"text": "C Quiz"
},
{
"code": null,
"e": 25261,
"s": 25252,
"text": "Pointers"
},
{
"code": null,
"e": 25359,
"s": 25261,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25368,
"s": 25359,
"text": "Comments"
},
{
"code": null,
"e": 25381,
"s": 25368,
"text": "Old Comments"
},
{
"code": null,
"e": 25393,
"s": 25381,
"text": "fork() in C"
},
{
"code": null,
"e": 25425,
"s": 25393,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25442,
"s": 25425,
"text": "Substring in C++"
},
{
"code": null,
"e": 25464,
"s": 25442,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 25511,
"s": 25464,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 25553,
"s": 25511,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 25596,
"s": 25553,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25627,
"s": 25596,
"text": "C | File Handling | Question 1"
},
{
"code": null,
"e": 25649,
"s": 25627,
"text": "C | Misc | Question 7"
}
] |
time.Weekday() Function in Golang With Examples - GeeksforGeeks
|
21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Weekday() function in Go language is used to check the English name of the day. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.
Syntax:
func (d Weekday) String() string
Return value: It returns English name of the day.
Example 1:
// Golang program to illustrate the usage of// Weekday() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Main functionfunc main() { // Calling Weekday method using // Now function weekday := time.Now().Weekday() // Prints the current weekday fmt.Println("Weekday is: ", weekday)}
Output:
Weekday is: Thursday
Example 2:
// Golang program to illustrate the usage of// Weekday() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Main functionfunc main() { // Calling Weekday method using // Now function weekday := time.Now().Weekday() // Prints the current // weekday in int form fmt.Println("Weekday in number is: ", int(weekday))}
Output:
Weekday in number is: 4
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
Time Formatting in Golang
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Slices in Golang
Golang Maps
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to compare times in Golang?
|
[
{
"code": null,
"e": 24063,
"s": 24035,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24373,
"s": 24063,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Weekday() function in Go language is used to check the English name of the day. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions."
},
{
"code": null,
"e": 24381,
"s": 24373,
"text": "Syntax:"
},
{
"code": null,
"e": 24415,
"s": 24381,
"text": "func (d Weekday) String() string\n"
},
{
"code": null,
"e": 24465,
"s": 24415,
"text": "Return value: It returns English name of the day."
},
{
"code": null,
"e": 24476,
"s": 24465,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// Weekday() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Main functionfunc main() { // Calling Weekday method using // Now function weekday := time.Now().Weekday() // Prints the current weekday fmt.Println(\"Weekday is: \", weekday)}",
"e": 24834,
"s": 24476,
"text": null
},
{
"code": null,
"e": 24842,
"s": 24834,
"text": "Output:"
},
{
"code": null,
"e": 24865,
"s": 24842,
"text": "Weekday is: Thursday\n"
},
{
"code": null,
"e": 24876,
"s": 24865,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// Weekday() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Main functionfunc main() { // Calling Weekday method using // Now function weekday := time.Now().Weekday() // Prints the current // weekday in int form fmt.Println(\"Weekday in number is: \", int(weekday))}",
"e": 25268,
"s": 24876,
"text": null
},
{
"code": null,
"e": 25276,
"s": 25268,
"text": "Output:"
},
{
"code": null,
"e": 25302,
"s": 25276,
"text": "Weekday in number is: 4\n"
},
{
"code": null,
"e": 25314,
"s": 25302,
"text": "GoLang-time"
},
{
"code": null,
"e": 25326,
"s": 25314,
"text": "Go Language"
},
{
"code": null,
"e": 25424,
"s": 25326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25433,
"s": 25424,
"text": "Comments"
},
{
"code": null,
"e": 25446,
"s": 25433,
"text": "Old Comments"
},
{
"code": null,
"e": 25497,
"s": 25446,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 25523,
"s": 25497,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 25536,
"s": 25523,
"text": "Arrays in Go"
},
{
"code": null,
"e": 25583,
"s": 25536,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 25616,
"s": 25583,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 25633,
"s": 25616,
"text": "Slices in Golang"
},
{
"code": null,
"e": 25645,
"s": 25633,
"text": "Golang Maps"
},
{
"code": null,
"e": 25699,
"s": 25645,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 25721,
"s": 25699,
"text": "Inheritance in GoLang"
}
] |
Comparing dates in Python
|
Comparing dates and times is a very crucial requirement in any programming language. Python has a datetime library which has many inbuilt functions to use date and time. Interestingly date and time can also be compared like mathematical comparison between various numbers.
In the below example we have chosen to dates by passing the value of year, month and date to the date function. Then we compare the dates using a if condition and we get the appropriate result.
import datetime
# Get default date format
print("Today is: ",datetime.date.today())
date1 = datetime.date(2019, 7, 2)
date2 = datetime.date(2019, 6, 5)
# Compare dates
if (date1 > date2):
print("Date1 > Date2")
elif (date1 < date2):
print("Date1 < Date2")
else:
print("Dates are equal")
# Get Default date time format
print(datetime.datetime.now())
date_time1 = datetime.datetime(2019, 7, 2,23,15,9)
date_time2 = datetime.datetime(2019, 7, 2,23,15,9)
# Compare date time
print(date_time2)
if (date_time1 == date_time2):
print("Date Time 1 is equal to Date Time 2")
else:
print("Date times are unequal")
Running the above code gives us the following result −
Today is: 2019-08-01
Date1 > Date2
2019-08-01 16:34:01.061242
2019-07-02 23:15:09
Date Time 1 is equal to Date Time 2
|
[
{
"code": null,
"e": 1335,
"s": 1062,
"text": "Comparing dates and times is a very crucial requirement in any programming language. Python has a datetime library which has many inbuilt functions to use date and time. Interestingly date and time can also be compared like mathematical comparison between various numbers."
},
{
"code": null,
"e": 1529,
"s": 1335,
"text": "In the below example we have chosen to dates by passing the value of year, month and date to the date function. Then we compare the dates using a if condition and we get the appropriate result."
},
{
"code": null,
"e": 2150,
"s": 1529,
"text": "import datetime\n# Get default date format\nprint(\"Today is: \",datetime.date.today())\ndate1 = datetime.date(2019, 7, 2)\ndate2 = datetime.date(2019, 6, 5)\n\n# Compare dates\nif (date1 > date2):\n print(\"Date1 > Date2\")\nelif (date1 < date2):\n print(\"Date1 < Date2\")\nelse:\n print(\"Dates are equal\")\n\n# Get Default date time format\nprint(datetime.datetime.now())\ndate_time1 = datetime.datetime(2019, 7, 2,23,15,9)\ndate_time2 = datetime.datetime(2019, 7, 2,23,15,9)\n\n# Compare date time\nprint(date_time2)\nif (date_time1 == date_time2):\n print(\"Date Time 1 is equal to Date Time 2\")\nelse:\n print(\"Date times are unequal\")"
},
{
"code": null,
"e": 2205,
"s": 2150,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2323,
"s": 2205,
"text": "Today is: 2019-08-01\nDate1 > Date2\n2019-08-01 16:34:01.061242\n2019-07-02 23:15:09\nDate Time 1 is equal to Date Time 2"
}
] |
jQuery Traversing Siblings
|
With jQuery you can traverse sideways in the DOM
tree to find siblings of an element.
Siblings share the same parent.
There are many useful jQuery methods for traversing sideways in the DOM tree:
siblings()
next()
nextAll()
nextUntil()
prev()
prevAll()
prevUntil()
The siblings() method returns all sibling elements of the selected element.
The following example returns all sibling elements of <h2>:
You can also use an optional parameter to filter the search for siblings.
The following example returns all sibling elements of <h2> that are <p>
elements:
The next() method returns the next sibling element of the selected element.
The following example returns the next sibling of <h2>:
The nextAll() method returns all next sibling elements of the selected element.
The following example returns all next sibling elements of
<h2>:
The nextUntil() method returns all next sibling elements between two given
arguments.
The following example returns all sibling elements
between a <h2> and a <h6> element:
The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they
return previous sibling elements (traverse backwards along sibling
elements in the DOM tree, instead of forward).
Use a jQuery method to get all siblings elements of an <h2> element.
$("h2").();
Start the Exercise
For a complete overview of all jQuery Traversing methods, please go to our
jQuery Traversing Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 87,
"s": 0,
"text": "With jQuery you can traverse sideways in the DOM \ntree to find siblings of an element."
},
{
"code": null,
"e": 120,
"s": 87,
"text": "Siblings share the same parent. "
},
{
"code": null,
"e": 198,
"s": 120,
"text": "There are many useful jQuery methods for traversing sideways in the DOM tree:"
},
{
"code": null,
"e": 209,
"s": 198,
"text": "siblings()"
},
{
"code": null,
"e": 216,
"s": 209,
"text": "next()"
},
{
"code": null,
"e": 226,
"s": 216,
"text": "nextAll()"
},
{
"code": null,
"e": 238,
"s": 226,
"text": "nextUntil()"
},
{
"code": null,
"e": 245,
"s": 238,
"text": "prev()"
},
{
"code": null,
"e": 255,
"s": 245,
"text": "prevAll()"
},
{
"code": null,
"e": 267,
"s": 255,
"text": "prevUntil()"
},
{
"code": null,
"e": 343,
"s": 267,
"text": "The siblings() method returns all sibling elements of the selected element."
},
{
"code": null,
"e": 403,
"s": 343,
"text": "The following example returns all sibling elements of <h2>:"
},
{
"code": null,
"e": 477,
"s": 403,
"text": "You can also use an optional parameter to filter the search for siblings."
},
{
"code": null,
"e": 560,
"s": 477,
"text": "The following example returns all sibling elements of <h2> that are <p> \nelements:"
},
{
"code": null,
"e": 636,
"s": 560,
"text": "The next() method returns the next sibling element of the selected element."
},
{
"code": null,
"e": 692,
"s": 636,
"text": "The following example returns the next sibling of <h2>:"
},
{
"code": null,
"e": 772,
"s": 692,
"text": "The nextAll() method returns all next sibling elements of the selected element."
},
{
"code": null,
"e": 838,
"s": 772,
"text": "The following example returns all next sibling elements of \n<h2>:"
},
{
"code": null,
"e": 925,
"s": 838,
"text": "The nextUntil() method returns all next sibling elements between two given \narguments."
},
{
"code": null,
"e": 1012,
"s": 925,
"text": "The following example returns all sibling elements \nbetween a <h2> and a <h6> element:"
},
{
"code": null,
"e": 1244,
"s": 1012,
"text": "The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they \nreturn previous sibling elements (traverse backwards along sibling \nelements in the DOM tree, instead of forward)."
},
{
"code": null,
"e": 1313,
"s": 1244,
"text": "Use a jQuery method to get all siblings elements of an <h2> element."
},
{
"code": null,
"e": 1326,
"s": 1313,
"text": "$(\"h2\").();\n"
},
{
"code": null,
"e": 1345,
"s": 1326,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1449,
"s": 1345,
"text": "For a complete overview of all jQuery Traversing methods, please go to our\njQuery Traversing Reference."
},
{
"code": null,
"e": 1482,
"s": 1449,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1524,
"s": 1482,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1631,
"s": 1524,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1650,
"s": 1631,
"text": "[email protected]"
}
] |
Phone Number Verification using Firebase in Android
|
19 Sep, 2021
Phone number Firebase Authentication is used to sign in a user by sending an SMS message to the user’s phone. The user signs in using a one-time code contained in the SMS message. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Note: To implement this in Java language refer to this article Firebase Authentication with Phone Number OTP in Android
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 Kotlin as the programming language.
Step 2: Connect Project to Firebase.
Step 3: Add dependency to the build.gradle file and click “sync now”
implementation platform(‘com.google.firebase:firebase-bom:26.5.0’)
implementation ‘com.google.firebase:firebase-auth-ktx’
Step 4: Create two new activities.
Create two new activities. One PhoneNumberActivity.kt with the layout file activity_phone_number.xml for entering the phone number and starting the authentication process. Second OtpActivity.kt with the layout file activity_otp.xml for entering OTP received from firebase.
Step 5: Working with layout
Working with activity_phone_number.xml. Go to the activity_phone_number.xml file and write the following code.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".PhoneNumberActivity"> <!--This will be used to enter the phone number--> <EditText android:id="@+id/et_phone_number" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="200dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:ems="10" android:hint="Enter Phone Number" android:inputType="phone" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:layout_editor_absoluteY="85dp" /> <!--On click of this button OTP will be send to phone--> <Button android:id="@+id/button_otp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Send OTP" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_phone_number" /> </androidx.constraintlayout.widget.ConstraintLayout>
Working with activity_otp.xml. Go to the activity_otp.xml file and write the following code.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".OtpActivity"> <TextView android:id="@+id/tv_otp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="200dp" android:text="Enter OTP" android:textSize="20sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--We will use it to enter OTP after we receive OTP--> <EditText android:id="@+id/et_otp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:hint="Enter OTP" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/tv_otp" /> <!--On click of this button final authentication will start--> <Button android:id="@+id/login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Login" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/et_otp" /> </androidx.constraintlayout.widget.ConstraintLayout>
Working with activity_main.xml. Go to the activity_main.xml file and write the following code. This is the final activity where we reach after verification is completed.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome To GFG!!" android:textSize="22sp" android:textColor="@color/black" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 6: Working with the PhoneNumberActivity.kt file
Go to the PhoneNumberActivity.kt file and refer to the following code. Below is the code for the PhoneNumberActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport com.google.firebase.FirebaseExceptionimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.PhoneAuthCredentialimport com.google.firebase.auth.PhoneAuthOptionsimport com.google.firebase.auth.PhoneAuthProviderimport java.util.concurrent.TimeUnit class PhoneNumberActivity : AppCompatActivity() { // this stores the phone number of the user var number : String ="" // create instance of firebase auth lateinit var auth: FirebaseAuth // we will use this to match the sent otp from firebase lateinit var storedVerificationId:String lateinit var resendToken: PhoneAuthProvider.ForceResendingToken private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_phone_number) auth=FirebaseAuth.getInstance() // start verification on click of the button findViewById<Button>(R.id.button_otp).setOnClickListener { login() } // Callback function for Phone Auth callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { // This method is called when the verification is completed override fun onVerificationCompleted(credential: PhoneAuthCredential) { startActivity(Intent(applicationContext, MainActivity::class.java)) finish() Log.d("GFG" , "onVerificationCompleted Success") } // Called when verification is failed add log statement to see the exception override fun onVerificationFailed(e: FirebaseException) { Log.d("GFG" , "onVerificationFailed $e") } // On code is sent by the firebase this method is called // in here we start a new activity where user can enter the OTP override fun onCodeSent( verificationId: String, token: PhoneAuthProvider.ForceResendingToken ) { Log.d("GFG","onCodeSent: $verificationId") storedVerificationId = verificationId resendToken = token // Start a new activity using intent // also send the storedVerificationId using intent // we will use this id to send the otp back to firebase val intent = Intent(applicationContext,OtpActivity::class.java) intent.putExtra("storedVerificationId",storedVerificationId) startActivity(intent) finish() } } } private fun login() { number = findViewById<EditText>(R.id.et_phone_number).text.trim().toString() // get the phone number from edit text and append the country cde with it if (number.isNotEmpty()){ number = "+91$number" sendVerificationCode(number) }else{ Toast.makeText(this,"Enter mobile number", Toast.LENGTH_SHORT).show() } } // this method sends the verification code // and starts the callback of verification // which is implemented above in onCreate private fun sendVerificationCode(number: String) { val options = PhoneAuthOptions.newBuilder(auth) .setPhoneNumber(number) // Phone number to verify .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit .setActivity(this) // Activity (for callback binding) .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks .build() PhoneAuthProvider.verifyPhoneNumber(options) Log.d("GFG" , "Auth started") }}
Step 7: Working with the OtpActivity.kt file
Go to the OtpActivity.kt file and refer to the following code. Below is the code for the OtpActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.FirebaseAuthInvalidCredentialsExceptionimport com.google.firebase.auth.PhoneAuthCredentialimport com.google.firebase.auth.PhoneAuthProvider class OtpActivity : AppCompatActivity() { // get reference of the firebase auth lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_otp) auth=FirebaseAuth.getInstance() // get storedVerificationId from the intent val storedVerificationId= intent.getStringExtra("storedVerificationId") // fill otp and call the on click on button findViewById<Button>(R.id.login).setOnClickListener { val otp = findViewById<EditText>(R.id.et_otp).text.trim().toString() if(otp.isNotEmpty()){ val credential : PhoneAuthCredential = PhoneAuthProvider.getCredential( storedVerificationId.toString(), otp) signInWithPhoneAuthCredential(credential) }else{ Toast.makeText(this,"Enter OTP", Toast.LENGTH_SHORT).show() } } } // verifies if the code matches sent by firebase // if success start the new activity in our case it is main Activity private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) { auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { val intent = Intent(this , MainActivity::class.java) startActivity(intent) finish() } else { // Sign in failed, display a message and update the UI if (task.exception is FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid Toast.makeText(this,"Invalid OTP", Toast.LENGTH_SHORT).show() } } } }}
Step 8: Go to AndroidManifest.xml and add the following code
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.phoneauth"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.PhoneAuth"> <activity android:name=".OtpActivity"></activity> <activity android:name=".PhoneNumberActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity"> </activity> </application> </manifest>
Step 9: Enable the Android DeviceCheck API for your project
In the Google Cloud Console, enable the Android DeviceCheck API for your project. The default Firebase API Key will be used and needs to be allowed to access the DeviceCheck API.
Step 10: Add SHA keys from Android Studio to Firebase
Copy SHA1 and SHA-256 keys from your project and paste them to the firebase console. Below is the screenshot to guide you.
Note: Please refer to this article How to Generate SHA1, MD5, and SHA-256 Keys in Android Studio?
On the Firebase console go to Project Overview -> Project Setting, and click add fingerprint button, and add your SHA keys copied from firebase
Step 11: Enable Phone Number sign-in for your Firebase project
In the Firebase console choose your project, open the Authentication section. On the Sign-in Method page, enable the Phone Number sign-in method.
Github repo here.
sweetyty
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 400,
"s": 52,
"text": "Phone number Firebase Authentication is used to sign in a user by sending an SMS message to the user’s phone. The user signs in using a one-time code contained in the SMS message. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language."
},
{
"code": null,
"e": 520,
"s": 400,
"text": "Note: To implement this in Java language refer to this article Firebase Authentication with Phone Number OTP in Android"
},
{
"code": null,
"e": 549,
"s": 520,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 713,
"s": 549,
"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 Kotlin as the programming language."
},
{
"code": null,
"e": 750,
"s": 713,
"text": "Step 2: Connect Project to Firebase."
},
{
"code": null,
"e": 819,
"s": 750,
"text": "Step 3: Add dependency to the build.gradle file and click “sync now”"
},
{
"code": null,
"e": 890,
"s": 819,
"text": " implementation platform(‘com.google.firebase:firebase-bom:26.5.0’)"
},
{
"code": null,
"e": 948,
"s": 890,
"text": " implementation ‘com.google.firebase:firebase-auth-ktx’"
},
{
"code": null,
"e": 983,
"s": 948,
"text": "Step 4: Create two new activities."
},
{
"code": null,
"e": 1256,
"s": 983,
"text": "Create two new activities. One PhoneNumberActivity.kt with the layout file activity_phone_number.xml for entering the phone number and starting the authentication process. Second OtpActivity.kt with the layout file activity_otp.xml for entering OTP received from firebase."
},
{
"code": null,
"e": 1284,
"s": 1256,
"text": "Step 5: Working with layout"
},
{
"code": null,
"e": 1395,
"s": 1284,
"text": "Working with activity_phone_number.xml. Go to the activity_phone_number.xml file and write the following code."
},
{
"code": null,
"e": 1399,
"s": 1395,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".PhoneNumberActivity\"> <!--This will be used to enter the phone number--> <EditText android:id=\"@+id/et_phone_number\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"200dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:ems=\"10\" android:hint=\"Enter Phone Number\" android:inputType=\"phone\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" tools:layout_editor_absoluteY=\"85dp\" /> <!--On click of this button OTP will be send to phone--> <Button android:id=\"@+id/button_otp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"Send OTP\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/et_phone_number\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2926,
"s": 1399,
"text": null
},
{
"code": null,
"e": 3023,
"s": 2930,
"text": "Working with activity_otp.xml. Go to the activity_otp.xml file and write the following code."
},
{
"code": null,
"e": 3029,
"s": 3025,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".OtpActivity\"> <TextView android:id=\"@+id/tv_otp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"200dp\" android:text=\"Enter OTP\" android:textSize=\"20sp\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--We will use it to enter OTP after we receive OTP--> <EditText android:id=\"@+id/et_otp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:hint=\"Enter OTP\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@id/tv_otp\" /> <!--On click of this button final authentication will start--> <Button android:id=\"@+id/login\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Login\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@id/et_otp\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 4665,
"s": 3029,
"text": null
},
{
"code": null,
"e": 4839,
"s": 4669,
"text": "Working with activity_main.xml. Go to the activity_main.xml file and write the following code. This is the final activity where we reach after verification is completed."
},
{
"code": null,
"e": 4845,
"s": 4841,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Welcome To GFG!!\" android:textSize=\"22sp\" android:textColor=\"@color/black\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 5689,
"s": 4845,
"text": null
},
{
"code": null,
"e": 5746,
"s": 5693,
"text": "Step 6: Working with the PhoneNumberActivity.kt file"
},
{
"code": null,
"e": 5948,
"s": 5748,
"text": "Go to the PhoneNumberActivity.kt file and refer to the following code. Below is the code for the PhoneNumberActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 5957,
"s": 5950,
"text": "Kotlin"
},
{
"code": "import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport com.google.firebase.FirebaseExceptionimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.PhoneAuthCredentialimport com.google.firebase.auth.PhoneAuthOptionsimport com.google.firebase.auth.PhoneAuthProviderimport java.util.concurrent.TimeUnit class PhoneNumberActivity : AppCompatActivity() { // this stores the phone number of the user var number : String =\"\" // create instance of firebase auth lateinit var auth: FirebaseAuth // we will use this to match the sent otp from firebase lateinit var storedVerificationId:String lateinit var resendToken: PhoneAuthProvider.ForceResendingToken private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_phone_number) auth=FirebaseAuth.getInstance() // start verification on click of the button findViewById<Button>(R.id.button_otp).setOnClickListener { login() } // Callback function for Phone Auth callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { // This method is called when the verification is completed override fun onVerificationCompleted(credential: PhoneAuthCredential) { startActivity(Intent(applicationContext, MainActivity::class.java)) finish() Log.d(\"GFG\" , \"onVerificationCompleted Success\") } // Called when verification is failed add log statement to see the exception override fun onVerificationFailed(e: FirebaseException) { Log.d(\"GFG\" , \"onVerificationFailed $e\") } // On code is sent by the firebase this method is called // in here we start a new activity where user can enter the OTP override fun onCodeSent( verificationId: String, token: PhoneAuthProvider.ForceResendingToken ) { Log.d(\"GFG\",\"onCodeSent: $verificationId\") storedVerificationId = verificationId resendToken = token // Start a new activity using intent // also send the storedVerificationId using intent // we will use this id to send the otp back to firebase val intent = Intent(applicationContext,OtpActivity::class.java) intent.putExtra(\"storedVerificationId\",storedVerificationId) startActivity(intent) finish() } } } private fun login() { number = findViewById<EditText>(R.id.et_phone_number).text.trim().toString() // get the phone number from edit text and append the country cde with it if (number.isNotEmpty()){ number = \"+91$number\" sendVerificationCode(number) }else{ Toast.makeText(this,\"Enter mobile number\", Toast.LENGTH_SHORT).show() } } // this method sends the verification code // and starts the callback of verification // which is implemented above in onCreate private fun sendVerificationCode(number: String) { val options = PhoneAuthOptions.newBuilder(auth) .setPhoneNumber(number) // Phone number to verify .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit .setActivity(this) // Activity (for callback binding) .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks .build() PhoneAuthProvider.verifyPhoneNumber(options) Log.d(\"GFG\" , \"Auth started\") }}",
"e": 9876,
"s": 5957,
"text": null
},
{
"code": null,
"e": 9925,
"s": 9880,
"text": "Step 7: Working with the OtpActivity.kt file"
},
{
"code": null,
"e": 10111,
"s": 9927,
"text": "Go to the OtpActivity.kt file and refer to the following code. Below is the code for the OtpActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 10120,
"s": 10113,
"text": "Kotlin"
},
{
"code": "import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.FirebaseAuthInvalidCredentialsExceptionimport com.google.firebase.auth.PhoneAuthCredentialimport com.google.firebase.auth.PhoneAuthProvider class OtpActivity : AppCompatActivity() { // get reference of the firebase auth lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_otp) auth=FirebaseAuth.getInstance() // get storedVerificationId from the intent val storedVerificationId= intent.getStringExtra(\"storedVerificationId\") // fill otp and call the on click on button findViewById<Button>(R.id.login).setOnClickListener { val otp = findViewById<EditText>(R.id.et_otp).text.trim().toString() if(otp.isNotEmpty()){ val credential : PhoneAuthCredential = PhoneAuthProvider.getCredential( storedVerificationId.toString(), otp) signInWithPhoneAuthCredential(credential) }else{ Toast.makeText(this,\"Enter OTP\", Toast.LENGTH_SHORT).show() } } } // verifies if the code matches sent by firebase // if success start the new activity in our case it is main Activity private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) { auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { val intent = Intent(this , MainActivity::class.java) startActivity(intent) finish() } else { // Sign in failed, display a message and update the UI if (task.exception is FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid Toast.makeText(this,\"Invalid OTP\", Toast.LENGTH_SHORT).show() } } } }}",
"e": 12376,
"s": 10120,
"text": null
},
{
"code": null,
"e": 12441,
"s": 12380,
"text": "Step 8: Go to AndroidManifest.xml and add the following code"
},
{
"code": null,
"e": 12447,
"s": 12443,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.phoneauth\"> <uses-permission android:name=\"android.permission.INTERNET\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.PhoneAuth\"> <activity android:name=\".OtpActivity\"></activity> <activity android:name=\".PhoneNumberActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <activity android:name=\".MainActivity\"> </activity> </application> </manifest>",
"e": 13357,
"s": 12447,
"text": null
},
{
"code": null,
"e": 13421,
"s": 13361,
"text": "Step 9: Enable the Android DeviceCheck API for your project"
},
{
"code": null,
"e": 13602,
"s": 13423,
"text": "In the Google Cloud Console, enable the Android DeviceCheck API for your project. The default Firebase API Key will be used and needs to be allowed to access the DeviceCheck API."
},
{
"code": null,
"e": 13660,
"s": 13606,
"text": "Step 10: Add SHA keys from Android Studio to Firebase"
},
{
"code": null,
"e": 13785,
"s": 13662,
"text": "Copy SHA1 and SHA-256 keys from your project and paste them to the firebase console. Below is the screenshot to guide you."
},
{
"code": null,
"e": 13885,
"s": 13787,
"text": "Note: Please refer to this article How to Generate SHA1, MD5, and SHA-256 Keys in Android Studio?"
},
{
"code": null,
"e": 14032,
"s": 13887,
"text": "On the Firebase console go to Project Overview -> Project Setting, and click add fingerprint button, and add your SHA keys copied from firebase"
},
{
"code": null,
"e": 14099,
"s": 14036,
"text": "Step 11: Enable Phone Number sign-in for your Firebase project"
},
{
"code": null,
"e": 14247,
"s": 14101,
"text": "In the Firebase console choose your project, open the Authentication section. On the Sign-in Method page, enable the Phone Number sign-in method."
},
{
"code": null,
"e": 14269,
"s": 14251,
"text": "Github repo here."
},
{
"code": null,
"e": 14280,
"s": 14271,
"text": "sweetyty"
},
{
"code": null,
"e": 14304,
"s": 14280,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 14312,
"s": 14304,
"text": "Android"
},
{
"code": null,
"e": 14319,
"s": 14312,
"text": "Kotlin"
},
{
"code": null,
"e": 14338,
"s": 14319,
"text": "Technical Scripter"
},
{
"code": null,
"e": 14346,
"s": 14338,
"text": "Android"
}
] |
How to Display Random ASCII Art on Linux Terminal?
|
09 Apr, 2021
Here we are going to see how to print the drawing on the terminal in the form of ASCII characters.ASCII-Art-Splash-Screen is a tool written in python that pulls a random drawing from a repository and shows it every time you open the terminal. This work on UNIX-based systems like Linux and macOS.
Now let’s see how to install the ASCII-Art-Splash-Screen tool on our Linux system.
The followings are the two requirements to install the ASCII-Art-Splash-Screen tool:
Python3 (Installation of python on Linux)
curl (CLI tool to download files)
Let’s see how to install curl:
To install curl on the Debian based system like Ubuntu and Kali Linux use the following command:
sudo apt install curl
For systems like RHEL/CentOS:
yum install curl
For the Fedora 22+:
dnf install curl
Before moving further make sure that you have installed these dependencies on the system.
Now let’s see how to install ASCII-Art-Splash-Screen tool. First clone the GitHub repository on the system using the following command:
git clone https://github.com/DanCRichards/ASCII-Art-Splash-Screen.git
After this move into the local repository and then copy the ascii.py file into the home directory. Use the following commands to do this:
cd ASCII-Art-Splash-Screen/
cp ascii.py ~/
Now to get the ASCII art on the terminal when we open the terminal we need to put python3 ascii.py command into the .bashrc file. Use the following command to put this command into .bashrc file
echo "python3 ascii.py" >> ~/.bashrc
We have successfully installed the ASCII-Art-Splash-Screen tool on our Linux system.
Now when you open a new terminal you will see the new ASCII art on the terminal every time. Here are some of them.
ASCII art1
ASCII art2
ASCII art3
This is how we can print the ASCII art on an open new terminal.
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 326,
"s": 28,
"text": "Here we are going to see how to print the drawing on the terminal in the form of ASCII characters.ASCII-Art-Splash-Screen is a tool written in python that pulls a random drawing from a repository and shows it every time you open the terminal. This work on UNIX-based systems like Linux and macOS. "
},
{
"code": null,
"e": 409,
"s": 326,
"text": "Now let’s see how to install the ASCII-Art-Splash-Screen tool on our Linux system."
},
{
"code": null,
"e": 494,
"s": 409,
"text": "The followings are the two requirements to install the ASCII-Art-Splash-Screen tool:"
},
{
"code": null,
"e": 536,
"s": 494,
"text": "Python3 (Installation of python on Linux)"
},
{
"code": null,
"e": 570,
"s": 536,
"text": "curl (CLI tool to download files)"
},
{
"code": null,
"e": 601,
"s": 570,
"text": "Let’s see how to install curl:"
},
{
"code": null,
"e": 698,
"s": 601,
"text": "To install curl on the Debian based system like Ubuntu and Kali Linux use the following command:"
},
{
"code": null,
"e": 720,
"s": 698,
"text": "sudo apt install curl"
},
{
"code": null,
"e": 750,
"s": 720,
"text": "For systems like RHEL/CentOS:"
},
{
"code": null,
"e": 768,
"s": 750,
"text": " yum install curl"
},
{
"code": null,
"e": 788,
"s": 768,
"text": "For the Fedora 22+:"
},
{
"code": null,
"e": 805,
"s": 788,
"text": "dnf install curl"
},
{
"code": null,
"e": 895,
"s": 805,
"text": "Before moving further make sure that you have installed these dependencies on the system."
},
{
"code": null,
"e": 1031,
"s": 895,
"text": "Now let’s see how to install ASCII-Art-Splash-Screen tool. First clone the GitHub repository on the system using the following command:"
},
{
"code": null,
"e": 1102,
"s": 1031,
"text": "git clone https://github.com/DanCRichards/ASCII-Art-Splash-Screen.git "
},
{
"code": null,
"e": 1240,
"s": 1102,
"text": "After this move into the local repository and then copy the ascii.py file into the home directory. Use the following commands to do this:"
},
{
"code": null,
"e": 1283,
"s": 1240,
"text": "cd ASCII-Art-Splash-Screen/\ncp ascii.py ~/"
},
{
"code": null,
"e": 1477,
"s": 1283,
"text": "Now to get the ASCII art on the terminal when we open the terminal we need to put python3 ascii.py command into the .bashrc file. Use the following command to put this command into .bashrc file"
},
{
"code": null,
"e": 1514,
"s": 1477,
"text": "echo \"python3 ascii.py\" >> ~/.bashrc"
},
{
"code": null,
"e": 1601,
"s": 1514,
"text": "We have successfully installed the ASCII-Art-Splash-Screen tool on our Linux system. "
},
{
"code": null,
"e": 1716,
"s": 1601,
"text": "Now when you open a new terminal you will see the new ASCII art on the terminal every time. Here are some of them."
},
{
"code": null,
"e": 1727,
"s": 1716,
"text": "ASCII art1"
},
{
"code": null,
"e": 1738,
"s": 1727,
"text": "ASCII art2"
},
{
"code": null,
"e": 1749,
"s": 1738,
"text": "ASCII art3"
},
{
"code": null,
"e": 1813,
"s": 1749,
"text": "This is how we can print the ASCII art on an open new terminal."
},
{
"code": null,
"e": 1820,
"s": 1813,
"text": "How To"
},
{
"code": null,
"e": 1831,
"s": 1820,
"text": "Linux-Unix"
}
] |
PostgreSQL – Create Database
|
28 Aug, 2020
PostgreSQL has multiple ways to create a database. In this article we will discuss multiple ways to do so.
1. Using psql Shell:
To create a database through the psql shell we make the use of the CREATE DATABASE statement as below:
CREATE DATABASE db_name
OWNER = role_name
TEMPLATE = template
ENCODING = encoding
LC_COLLATE = collate
LC_CTYPE = ctype
TABLESPACE = tablespace_name
CONNECTION LIMIT = max_concurrent_connection
The various options provided by the CREATE DATABASE statement are explained below:
db_name: It is the name of the new database that you want to create.It must always be a unique name.
role_name: It is the role name of the user who will own the new database.
template: It is the name of the database template from which the new database gets created.
encoding: It specifies the character set encoding for the new database. By default, it is the encoding of the template database.
collate: It specifies a collation for the new database.
ctype: It specifies the character classification for the new database like digit, lower and upper.
tablespace_name: It specifies the tablespace name for the new database.
max_concurrent_connection: It specifies the maximum concurrent connections to the new database.
Example 1:Here we will create a test database with all default settings.
CREATE DATABASE my_test_db1;
Output:
Example 2:Here we will create a test database with the following parameters:
Encoding: utf-8.
Owner: GeeksForGeeks with postgres as the user.
Maximum concurrent connections: 30.
CREATE DATABASE my_test_db2
WITH ENCODING='UTF8'
OWNER=GeeksForGeeks
CONNECTION LIMIT=30;
Output:
2. Using pgAdmin:
Follow the below steps to create a new database using pgAdmin.
Step 1: Log in to PostgreSQL via pgAdmin.
Step 2: Right click on the Databases menu and then click on New Database... sub-menu item as depicted below:
Step 3: Now enter the new database name, owner, and configure parameters and click the OK button as depicted below:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 135,
"s": 28,
"text": "PostgreSQL has multiple ways to create a database. In this article we will discuss multiple ways to do so."
},
{
"code": null,
"e": 156,
"s": 135,
"text": "1. Using psql Shell:"
},
{
"code": null,
"e": 259,
"s": 156,
"text": "To create a database through the psql shell we make the use of the CREATE DATABASE statement as below:"
},
{
"code": null,
"e": 462,
"s": 259,
"text": "CREATE DATABASE db_name\n OWNER = role_name\n TEMPLATE = template\n ENCODING = encoding\n LC_COLLATE = collate\n LC_CTYPE = ctype\n TABLESPACE = tablespace_name\n CONNECTION LIMIT = max_concurrent_connection\n"
},
{
"code": null,
"e": 545,
"s": 462,
"text": "The various options provided by the CREATE DATABASE statement are explained below:"
},
{
"code": null,
"e": 646,
"s": 545,
"text": "db_name: It is the name of the new database that you want to create.It must always be a unique name."
},
{
"code": null,
"e": 720,
"s": 646,
"text": "role_name: It is the role name of the user who will own the new database."
},
{
"code": null,
"e": 812,
"s": 720,
"text": "template: It is the name of the database template from which the new database gets created."
},
{
"code": null,
"e": 941,
"s": 812,
"text": "encoding: It specifies the character set encoding for the new database. By default, it is the encoding of the template database."
},
{
"code": null,
"e": 997,
"s": 941,
"text": "collate: It specifies a collation for the new database."
},
{
"code": null,
"e": 1096,
"s": 997,
"text": "ctype: It specifies the character classification for the new database like digit, lower and upper."
},
{
"code": null,
"e": 1168,
"s": 1096,
"text": "tablespace_name: It specifies the tablespace name for the new database."
},
{
"code": null,
"e": 1264,
"s": 1168,
"text": "max_concurrent_connection: It specifies the maximum concurrent connections to the new database."
},
{
"code": null,
"e": 1337,
"s": 1264,
"text": "Example 1:Here we will create a test database with all default settings."
},
{
"code": null,
"e": 1366,
"s": 1337,
"text": "CREATE DATABASE my_test_db1;"
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Output:"
},
{
"code": null,
"e": 1451,
"s": 1374,
"text": "Example 2:Here we will create a test database with the following parameters:"
},
{
"code": null,
"e": 1468,
"s": 1451,
"text": "Encoding: utf-8."
},
{
"code": null,
"e": 1516,
"s": 1468,
"text": "Owner: GeeksForGeeks with postgres as the user."
},
{
"code": null,
"e": 1552,
"s": 1516,
"text": "Maximum concurrent connections: 30."
},
{
"code": null,
"e": 1645,
"s": 1552,
"text": "CREATE DATABASE my_test_db2\n WITH ENCODING='UTF8'\n OWNER=GeeksForGeeks\n CONNECTION LIMIT=30;"
},
{
"code": null,
"e": 1653,
"s": 1645,
"text": "Output:"
},
{
"code": null,
"e": 1671,
"s": 1653,
"text": "2. Using pgAdmin:"
},
{
"code": null,
"e": 1734,
"s": 1671,
"text": "Follow the below steps to create a new database using pgAdmin."
},
{
"code": null,
"e": 1776,
"s": 1734,
"text": "Step 1: Log in to PostgreSQL via pgAdmin."
},
{
"code": null,
"e": 1885,
"s": 1776,
"text": "Step 2: Right click on the Databases menu and then click on New Database... sub-menu item as depicted below:"
},
{
"code": null,
"e": 2001,
"s": 1885,
"text": "Step 3: Now enter the new database name, owner, and configure parameters and click the OK button as depicted below:"
},
{
"code": null,
"e": 2022,
"s": 2001,
"text": "postgreSQL-operators"
},
{
"code": null,
"e": 2033,
"s": 2022,
"text": "PostgreSQL"
}
] |
Sort a stack using a temporary stack
|
13 Jul, 2022
Given a stack of integers, sort it in ascending order using another temporary stack.
Examples:
Input : [34, 3, 31, 98, 92, 23]
Output : [3, 23, 31, 34, 92, 98]
Input : [3, 5, 1, 4, 2, 8]
Output : [1, 2, 3, 4, 5, 8]
Algorithm:
Create a temporary stack say tmpStack.While input stack is NOT empty do this: Pop an element from input stack call it tempwhile temporary stack is NOT empty and top of temporary stack is greater than temp, pop from temporary stack and push it to the input stackpush temp in temporary stackThe sorted numbers are in tmpStack
Create a temporary stack say tmpStack.
While input stack is NOT empty do this: Pop an element from input stack call it tempwhile temporary stack is NOT empty and top of temporary stack is greater than temp, pop from temporary stack and push it to the input stackpush temp in temporary stack
Pop an element from input stack call it temp
while temporary stack is NOT empty and top of temporary stack is greater than temp, pop from temporary stack and push it to the input stack
push temp in temporary stack
The sorted numbers are in tmpStack
Here is a dry run of the above pseudo code.
input: [34, 3, 31, 98, 92, 23]
Element taken out: 23
input: [34, 3, 31, 98, 92]
tmpStack: [23]
Element taken out: 92
input: [34, 3, 31, 98]
tmpStack: [23, 92]
Element taken out: 98
input: [34, 3, 31]
tmpStack: [23, 92, 98]
Element taken out: 31
input: [34, 3, 98, 92]
tmpStack: [23, 31]
Element taken out: 92
input: [34, 3, 98]
tmpStack: [23, 31, 92]
Element taken out: 98
input: [34, 3]
tmpStack: [23, 31, 92, 98]
Element taken out: 3
input: [34, 98, 92, 31, 23]
tmpStack: [3]
Element taken out: 23
input: [34, 98, 92, 31]
tmpStack: [3, 23]
Element taken out: 31
input: [34, 98, 92]
tmpStack: [3, 23, 31]
Element taken out: 92
input: [34, 98]
tmpStack: [3, 23, 31, 92]
Element taken out: 98
input: [34]
tmpStack: [3, 23, 31, 92, 98]
Element taken out: 34
input: [98, 92]
tmpStack: [3, 23, 31, 34]
Element taken out: 92
input: [98]
tmpStack: [3, 23, 31, 34, 92]
Element taken out: 98
input: []
tmpStack: [3, 23, 31, 34, 92, 98]
final sorted list: [3, 23, 31, 34, 92, 98]
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to sort a stack using an// auxiliary stack.#include <bits/stdc++.h>using namespace std; // This function return the sorted stackstack<int> sortStack(stack<int> &input){ stack<int> tmpStack; while (!input.empty()) { // pop out the first element int tmp = input.top(); input.pop(); // while temporary stack is not empty and top // of stack is greater than temp while (!tmpStack.empty() && tmpStack.top() > tmp) { // pop from temporary stack and push // it to the input stack input.push(tmpStack.top()); tmpStack.pop(); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack;} // main functionint main(){ stack<int> input; input.push(34); input.push(3); input.push(31); input.push(98); input.push(92); input.push(23); // This is the temporary stack stack<int> tmpStack = sortStack(input); cout << "Sorted numbers are:\n"; while (!tmpStack.empty()) { cout << tmpStack.top()<< " "; tmpStack.pop(); }}
// Java program to sort a stack using// a auxiliary stack.import java.util.*; class SortStack{ // This function return the sorted stack public static Stack<Integer> sortstack(Stack<Integer> input) { Stack<Integer> tmpStack = new Stack<Integer>(); while(!input.isEmpty()) { // pop out the first element int tmp = input.pop(); // while temporary stack is not empty and // top of stack is greater than temp while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) { // pop from temporary stack and // push it to the input stack input.push(tmpStack.pop()); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } // Driver Code public static void main(String args[]) { Stack<Integer> input = new Stack<Integer>(); input.add(34); input.add(3); input.add(31); input.add(98); input.add(92); input.add(23); // This is the temporary stack Stack<Integer> tmpStack=sortstack(input); System.out.println("Sorted numbers are:"); while (!tmpStack.empty()) { System.out.print(tmpStack.pop()+" "); } }}// This code is contributed by Danish Kaleem
# Python program to sort a# stack using auxiliary stack. # This function return the sorted stackdef sortStack ( stack ): tmpStack = createStack() while(isEmpty(stack) == False): # pop out the first element tmp = top(stack) pop(stack) # while temporary stack is not # empty and top of stack is # greater than temp while(isEmpty(tmpStack) == False and int(top(tmpStack)) > int(tmp)): # pop from temporary stack and # push it to the input stack push(stack,top(tmpStack)) pop(tmpStack) # push temp in temporary of stack push(tmpStack,tmp) return tmpStack # Below is a complete running# program for testing above# function. # Function to create a stack.# It initializes size of stack# as 0def createStack(): stack = [] return stack # Function to check if# the stack is emptydef isEmpty( stack ): return len(stack) == 0 # Function to push an# item to stackdef push( stack, item ): stack.append( item ) # Function to get top# item of stackdef top( stack ): p = len(stack) return stack[p-1] # Function to pop an# item from stackdef pop( stack ): # If stack is empty # then error if(isEmpty( stack )): print("Stack Underflow ") exit(1) return stack.pop() # Function to print the stackdef prints(stack): for i in range(len(stack)-1, -1, -1): print(stack[i], end = ' ') print() # Driver Codestack = createStack()push( stack, str(34) )push( stack, str(3) )push( stack, str(31) )push( stack, str(98) )push( stack, str(92) )push( stack, str(23) ) print("Sorted numbers are: ")sortedst = sortStack ( stack )prints(sortedst) # This code is contributed by# Prasad Kshirsagar
// C# program to sort a stack using// a auxiliary stack.using System;using System.Collections.Generic; class GFG{// This function return the sorted stackpublic static Stack<int> sortstack(Stack<int> input){ Stack<int> tmpStack = new Stack<int>(); while (input.Count > 0) { // pop out the first element int tmp = input.Pop(); // while temporary stack is not empty and // top of stack is greater than temp while (tmpStack.Count > 0 && tmpStack.Peek() > tmp) { // pop from temporary stack and // push it to the input stack input.Push(tmpStack.Pop()); } // push temp in temporary of stack tmpStack.Push(tmp); } return tmpStack;} // Driver Codepublic static void Main(string[] args){ Stack<int> input = new Stack<int>(); input.Push(34); input.Push(3); input.Push(31); input.Push(98); input.Push(92); input.Push(23); // This is the temporary stack Stack<int> tmpStack = sortstack(input); Console.WriteLine("Sorted numbers are:"); while (tmpStack.Count > 0) { Console.Write(tmpStack.Pop() + " "); }}} // This code is contributed by Shrikant13
<script> // Javascript program to sort a stack using // a auxiliary stack. // This function return the sorted stack function sortstack(input) { let tmpStack = []; while (input.length > 0) { // pop out the first element let tmp = input.pop(); // while temporary stack is not empty and // top of stack is greater than temp while (tmpStack.length > 0 && tmpStack[tmpStack.length - 1] > tmp) { // pop from temporary stack and // push it to the input stack input.push(tmpStack[tmpStack.length - 1]); tmpStack.pop() } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } let input = []; input.push(34); input.push(3); input.push(31); input.push(98); input.push(92); input.push(23); // This is the temporary stack let tmpStack = sortstack(input); document.write("Sorted numbers are:" + "</br>"); while (tmpStack.length > 0) { document.write(tmpStack[tmpStack.length - 1] + " "); tmpStack.pop(); } // This code is contributed by rameshtravel07.</script>
Sorted numbers are:
98 92 34 31 23 3
Time Complexity: O(n2) where n is the total number of integers in the given stack.Auxiliary Space: O(n)
This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Prasad_Kshirsagar
shrikanth13
anujdada532
chinmayrdhakemet17
abhishekkumarsingh2101
rameshtravel07
whorahulnayak
pushpeshrajdx01
hardikkoriintern
Amazon
Goldman Sachs
IBM
Kuliza
STL
Yahoo
Recursion
Sorting
Stack
Amazon
Goldman Sachs
Yahoo
IBM
Kuliza
Recursion
Stack
Sorting
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jul, 2022"
},
{
"code": null,
"e": 139,
"s": 54,
"text": "Given a stack of integers, sort it in ascending order using another temporary stack."
},
{
"code": null,
"e": 150,
"s": 139,
"text": "Examples: "
},
{
"code": null,
"e": 272,
"s": 150,
"text": "Input : [34, 3, 31, 98, 92, 23]\nOutput : [3, 23, 31, 34, 92, 98]\n\nInput : [3, 5, 1, 4, 2, 8]\nOutput : [1, 2, 3, 4, 5, 8] "
},
{
"code": null,
"e": 283,
"s": 272,
"text": "Algorithm:"
},
{
"code": null,
"e": 607,
"s": 283,
"text": "Create a temporary stack say tmpStack.While input stack is NOT empty do this: Pop an element from input stack call it tempwhile temporary stack is NOT empty and top of temporary stack is greater than temp, pop from temporary stack and push it to the input stackpush temp in temporary stackThe sorted numbers are in tmpStack"
},
{
"code": null,
"e": 646,
"s": 607,
"text": "Create a temporary stack say tmpStack."
},
{
"code": null,
"e": 898,
"s": 646,
"text": "While input stack is NOT empty do this: Pop an element from input stack call it tempwhile temporary stack is NOT empty and top of temporary stack is greater than temp, pop from temporary stack and push it to the input stackpush temp in temporary stack"
},
{
"code": null,
"e": 943,
"s": 898,
"text": "Pop an element from input stack call it temp"
},
{
"code": null,
"e": 1083,
"s": 943,
"text": "while temporary stack is NOT empty and top of temporary stack is greater than temp, pop from temporary stack and push it to the input stack"
},
{
"code": null,
"e": 1112,
"s": 1083,
"text": "push temp in temporary stack"
},
{
"code": null,
"e": 1147,
"s": 1112,
"text": "The sorted numbers are in tmpStack"
},
{
"code": null,
"e": 1193,
"s": 1147,
"text": "Here is a dry run of the above pseudo code. "
},
{
"code": null,
"e": 2179,
"s": 1193,
"text": "input: [34, 3, 31, 98, 92, 23]\n\nElement taken out: 23\ninput: [34, 3, 31, 98, 92]\ntmpStack: [23]\n\nElement taken out: 92\ninput: [34, 3, 31, 98]\ntmpStack: [23, 92]\n\nElement taken out: 98\ninput: [34, 3, 31]\ntmpStack: [23, 92, 98]\n\nElement taken out: 31\ninput: [34, 3, 98, 92]\ntmpStack: [23, 31]\n\nElement taken out: 92\ninput: [34, 3, 98]\ntmpStack: [23, 31, 92]\n\nElement taken out: 98\ninput: [34, 3]\ntmpStack: [23, 31, 92, 98]\n\nElement taken out: 3\ninput: [34, 98, 92, 31, 23]\ntmpStack: [3]\n\nElement taken out: 23\ninput: [34, 98, 92, 31]\ntmpStack: [3, 23]\n\nElement taken out: 31\ninput: [34, 98, 92]\ntmpStack: [3, 23, 31]\n\nElement taken out: 92\ninput: [34, 98]\ntmpStack: [3, 23, 31, 92]\n\nElement taken out: 98\ninput: [34]\ntmpStack: [3, 23, 31, 92, 98]\n\nElement taken out: 34\ninput: [98, 92]\ntmpStack: [3, 23, 31, 34]\n\nElement taken out: 92\ninput: [98]\ntmpStack: [3, 23, 31, 34, 92]\n\nElement taken out: 98\ninput: []\ntmpStack: [3, 23, 31, 34, 92, 98]\n\nfinal sorted list: [3, 23, 31, 34, 92, 98]"
},
{
"code": null,
"e": 2195,
"s": 2179,
"text": "Implementation:"
},
{
"code": null,
"e": 2199,
"s": 2195,
"text": "C++"
},
{
"code": null,
"e": 2204,
"s": 2199,
"text": "Java"
},
{
"code": null,
"e": 2212,
"s": 2204,
"text": "Python3"
},
{
"code": null,
"e": 2215,
"s": 2212,
"text": "C#"
},
{
"code": null,
"e": 2226,
"s": 2215,
"text": "Javascript"
},
{
"code": "// C++ program to sort a stack using an// auxiliary stack.#include <bits/stdc++.h>using namespace std; // This function return the sorted stackstack<int> sortStack(stack<int> &input){ stack<int> tmpStack; while (!input.empty()) { // pop out the first element int tmp = input.top(); input.pop(); // while temporary stack is not empty and top // of stack is greater than temp while (!tmpStack.empty() && tmpStack.top() > tmp) { // pop from temporary stack and push // it to the input stack input.push(tmpStack.top()); tmpStack.pop(); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack;} // main functionint main(){ stack<int> input; input.push(34); input.push(3); input.push(31); input.push(98); input.push(92); input.push(23); // This is the temporary stack stack<int> tmpStack = sortStack(input); cout << \"Sorted numbers are:\\n\"; while (!tmpStack.empty()) { cout << tmpStack.top()<< \" \"; tmpStack.pop(); }}",
"e": 3345,
"s": 2226,
"text": null
},
{
"code": "// Java program to sort a stack using// a auxiliary stack.import java.util.*; class SortStack{ // This function return the sorted stack public static Stack<Integer> sortstack(Stack<Integer> input) { Stack<Integer> tmpStack = new Stack<Integer>(); while(!input.isEmpty()) { // pop out the first element int tmp = input.pop(); // while temporary stack is not empty and // top of stack is greater than temp while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) { // pop from temporary stack and // push it to the input stack input.push(tmpStack.pop()); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } // Driver Code public static void main(String args[]) { Stack<Integer> input = new Stack<Integer>(); input.add(34); input.add(3); input.add(31); input.add(98); input.add(92); input.add(23); // This is the temporary stack Stack<Integer> tmpStack=sortstack(input); System.out.println(\"Sorted numbers are:\"); while (!tmpStack.empty()) { System.out.print(tmpStack.pop()+\" \"); } }}// This code is contributed by Danish Kaleem",
"e": 4822,
"s": 3345,
"text": null
},
{
"code": "# Python program to sort a# stack using auxiliary stack. # This function return the sorted stackdef sortStack ( stack ): tmpStack = createStack() while(isEmpty(stack) == False): # pop out the first element tmp = top(stack) pop(stack) # while temporary stack is not # empty and top of stack is # greater than temp while(isEmpty(tmpStack) == False and int(top(tmpStack)) > int(tmp)): # pop from temporary stack and # push it to the input stack push(stack,top(tmpStack)) pop(tmpStack) # push temp in temporary of stack push(tmpStack,tmp) return tmpStack # Below is a complete running# program for testing above# function. # Function to create a stack.# It initializes size of stack# as 0def createStack(): stack = [] return stack # Function to check if# the stack is emptydef isEmpty( stack ): return len(stack) == 0 # Function to push an# item to stackdef push( stack, item ): stack.append( item ) # Function to get top# item of stackdef top( stack ): p = len(stack) return stack[p-1] # Function to pop an# item from stackdef pop( stack ): # If stack is empty # then error if(isEmpty( stack )): print(\"Stack Underflow \") exit(1) return stack.pop() # Function to print the stackdef prints(stack): for i in range(len(stack)-1, -1, -1): print(stack[i], end = ' ') print() # Driver Codestack = createStack()push( stack, str(34) )push( stack, str(3) )push( stack, str(31) )push( stack, str(98) )push( stack, str(92) )push( stack, str(23) ) print(\"Sorted numbers are: \")sortedst = sortStack ( stack )prints(sortedst) # This code is contributed by# Prasad Kshirsagar",
"e": 6596,
"s": 4822,
"text": null
},
{
"code": "// C# program to sort a stack using// a auxiliary stack.using System;using System.Collections.Generic; class GFG{// This function return the sorted stackpublic static Stack<int> sortstack(Stack<int> input){ Stack<int> tmpStack = new Stack<int>(); while (input.Count > 0) { // pop out the first element int tmp = input.Pop(); // while temporary stack is not empty and // top of stack is greater than temp while (tmpStack.Count > 0 && tmpStack.Peek() > tmp) { // pop from temporary stack and // push it to the input stack input.Push(tmpStack.Pop()); } // push temp in temporary of stack tmpStack.Push(tmp); } return tmpStack;} // Driver Codepublic static void Main(string[] args){ Stack<int> input = new Stack<int>(); input.Push(34); input.Push(3); input.Push(31); input.Push(98); input.Push(92); input.Push(23); // This is the temporary stack Stack<int> tmpStack = sortstack(input); Console.WriteLine(\"Sorted numbers are:\"); while (tmpStack.Count > 0) { Console.Write(tmpStack.Pop() + \" \"); }}} // This code is contributed by Shrikant13",
"e": 7793,
"s": 6596,
"text": null
},
{
"code": "<script> // Javascript program to sort a stack using // a auxiliary stack. // This function return the sorted stack function sortstack(input) { let tmpStack = []; while (input.length > 0) { // pop out the first element let tmp = input.pop(); // while temporary stack is not empty and // top of stack is greater than temp while (tmpStack.length > 0 && tmpStack[tmpStack.length - 1] > tmp) { // pop from temporary stack and // push it to the input stack input.push(tmpStack[tmpStack.length - 1]); tmpStack.pop() } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } let input = []; input.push(34); input.push(3); input.push(31); input.push(98); input.push(92); input.push(23); // This is the temporary stack let tmpStack = sortstack(input); document.write(\"Sorted numbers are:\" + \"</br>\"); while (tmpStack.length > 0) { document.write(tmpStack[tmpStack.length - 1] + \" \"); tmpStack.pop(); } // This code is contributed by rameshtravel07.</script>",
"e": 9053,
"s": 7793,
"text": null
},
{
"code": null,
"e": 9091,
"s": 9053,
"text": "Sorted numbers are:\n98 92 34 31 23 3 "
},
{
"code": null,
"e": 9195,
"s": 9091,
"text": "Time Complexity: O(n2) where n is the total number of integers in the given stack.Auxiliary Space: O(n)"
},
{
"code": null,
"e": 9504,
"s": 9195,
"text": "This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 9522,
"s": 9504,
"text": "Prasad_Kshirsagar"
},
{
"code": null,
"e": 9534,
"s": 9522,
"text": "shrikanth13"
},
{
"code": null,
"e": 9546,
"s": 9534,
"text": "anujdada532"
},
{
"code": null,
"e": 9565,
"s": 9546,
"text": "chinmayrdhakemet17"
},
{
"code": null,
"e": 9588,
"s": 9565,
"text": "abhishekkumarsingh2101"
},
{
"code": null,
"e": 9603,
"s": 9588,
"text": "rameshtravel07"
},
{
"code": null,
"e": 9617,
"s": 9603,
"text": "whorahulnayak"
},
{
"code": null,
"e": 9633,
"s": 9617,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 9650,
"s": 9633,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 9657,
"s": 9650,
"text": "Amazon"
},
{
"code": null,
"e": 9671,
"s": 9657,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 9675,
"s": 9671,
"text": "IBM"
},
{
"code": null,
"e": 9682,
"s": 9675,
"text": "Kuliza"
},
{
"code": null,
"e": 9686,
"s": 9682,
"text": "STL"
},
{
"code": null,
"e": 9692,
"s": 9686,
"text": "Yahoo"
},
{
"code": null,
"e": 9702,
"s": 9692,
"text": "Recursion"
},
{
"code": null,
"e": 9710,
"s": 9702,
"text": "Sorting"
},
{
"code": null,
"e": 9716,
"s": 9710,
"text": "Stack"
},
{
"code": null,
"e": 9723,
"s": 9716,
"text": "Amazon"
},
{
"code": null,
"e": 9737,
"s": 9723,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 9743,
"s": 9737,
"text": "Yahoo"
},
{
"code": null,
"e": 9747,
"s": 9743,
"text": "IBM"
},
{
"code": null,
"e": 9754,
"s": 9747,
"text": "Kuliza"
},
{
"code": null,
"e": 9764,
"s": 9754,
"text": "Recursion"
},
{
"code": null,
"e": 9770,
"s": 9764,
"text": "Stack"
},
{
"code": null,
"e": 9778,
"s": 9770,
"text": "Sorting"
},
{
"code": null,
"e": 9782,
"s": 9778,
"text": "STL"
}
] |
Program to find the count of coins of each type from the given ratio
|
14 Apr, 2021
Given the total number of Rupees in a bag and the ratio of coins. The bag contains only 1 Rs, 50 paise, 25 paise coins in X, Y, Z, ratio. The task is to determine the number of 1 Rs coins, 50 Paise coins, and 25 paise coins So that after summation of all these we again get the total rupees given.Examples:
Input: totalRupees = 1800, X = 1, Y = 2, Z = 4
Output: 1 rupees coins = 600
50 paisa coins = 1200
25 paisa coins = 2400
Input: totalRupees = 2500, X = 2, Y = 4, Z = 2
Output: 1 rupees coins = 555
50 paisa coins = 1110
25 paisa coins = 2220
Approach:
Let the ratio in which 1 Rs, 50 paise and 25 paise coin is divided is 1:2:4 Now, 1 Rs coins in a bag is 1x. 50 paise coins in a bag is 2x. 25 paise coins in a bag is 4x.Now convert these paise into Rupees. So, x coins of 1 Rs each, the total value is x rupees. 2x coins of 50 paise i.e (1 / 2) rupees each, the total value is x rupees. 4x coins of 25 paise i.e (1 / 4) rupees each, the total is x rupees.Therefore,3x = 1800 x = 6001 rupess coins = 600 * 1 = 600 50 paisa coins = 600 * 2 = 1200 25 paisa coins = 600 * 4 = 2400
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // function to calculate coin.int coin(int totalRupees, int X, int Y, int Z){ float one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2.0); twentyfive = ((Z * 1) / 4.0); total = one + fifty + twentyfive; result = ((totalRupees) / total); return result;} // Driver codeint main(){ int totalRupees = 1800; int X = 1, Y = 2, Z = 4; int Rupees = coin(totalRupees, X, Y, Z); cout << "1 rupess coins = " << Rupees * 1 << endl; cout << "50 paisa coins = " << Rupees * 2 << endl; cout << "25 paisa coins = " << Rupees * 4 << endl; return 0;}
// Java implementation of above approach import java.io.*; class GFG { // function to calculate coin. static int coin(int totalRupees, int X, int Y, int Z){ float one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2); twentyfive = ((Z * 1) / 4); total = one + fifty + twentyfive; result = ((totalRupees) / total); return (int)result;} // Driver code public static void main (String[] args) { int totalRupees = 1800; int X = 1, Y = 2, Z = 4; int Rupees = coin(totalRupees, X, Y, Z); System.out.println( "1 rupess coins = " + Rupees * 1); System.out.println( "50 paisa coins = " + Rupees * 2); System.out.println( "25 paisa coins = " + Rupees * 4); }}//This code is contributed by inder_verma.
# Python3 implementation of above approach # function to calculate coin.def coin(totalRupees, X, Y, Z): # Converting each of them in rupees. # As we are given totalRupees = 1800 one = X * 1 fifty = ((Y * 1) / 2.0) twentyfive = ((Z * 1) / 4.0) total = one + fifty + twentyfive result = ((totalRupees) / total) return int(result) # Driver codeif __name__=='__main__': totalRupees = 1800 X, Y, Z = 1, 2, 4 Rupees = coin(totalRupees, X, Y, Z) print("1 rupess coins = ", Rupees * 1) print("50 paisa coins = ", Rupees * 2) print("25 paisa coins = ", Rupees * 4) # This code is contributed by# Sanjit_Prasad
// C# implementation of above approachusing System; class GFG{ // function to calculate coin.static int coin(int totalRupees, int X, int Y, int Z){ float one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2); twentyfive = ((Z * 1) / 4); total = one + fifty + twentyfive; result = ((totalRupees) / total); return (int)result;} // Driver codepublic static void Main (){ int totalRupees = 1800; int X = 1, Y = 2, Z = 4; int Rupees = coin(totalRupees, X, Y, Z); Console.WriteLine( "1 rupess coins = " + Rupees * 1); Console.WriteLine( "50 paisa coins = " + Rupees * 2); Console.WriteLine( "25 paisa coins = " + Rupees * 4);}} // This code is contributed by inder_verma
<?php// PHP implementation of above approach //function to calculate coinfunction coin($totalRupees, $X, $Y, $Z){ $one = 0; $fifty = 0; $twentyfive = 0; $result = 0; $total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 $one = $X * 1; $fifty = (($Y * 1) / 2.0); $twentyfive = (($Z * 1) / 4.0); $total = $one + $fifty + $twentyfive; $result = (($totalRupees) / $total); return $result; } // Driver Code$totalRupees = 1800;$X = 1;$Y = 2;$Z = 4;$Rupees = coin($totalRupees, $X, $Y, $Z);echo "1 rupess coins = ", $Rupees * 1, "\n";echo "50 paisa coins = ", $Rupees * 2, "\n";echo "25 paisa coins = ", $Rupees * 4, "\n"; // This code is contributed// by Shashank_Sharma.?>
<script> // Javascript implementation of above approach // function to calculate coin.function coin(totalRupees, X, Y, Z){ var one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2.0); twentyfive = ((Z * 1) / 4.0); total = one + fifty + twentyfive; result = ((totalRupees) / total); return result;} // Driver codevar totalRupees = 1800;var X = 1, Y = 2, Z = 4;var Rupees = coin(totalRupees, X, Y, Z);document.write( "1 rupess coins = " + Rupees * 1 + "<br>");document.write( "50 paisa coins = " + Rupees * 2 + "<br>");document.write( "25 paisa coins = " + Rupees * 4 + "<br>"); </script>
1 rupess coins = 600
50 paisa coins = 1200
25 paisa coins = 2400
Sanjit_Prasad
Shashank_Sharma
inderDuMCA
rutvik_56
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Apr, 2021"
},
{
"code": null,
"e": 337,
"s": 28,
"text": "Given the total number of Rupees in a bag and the ratio of coins. The bag contains only 1 Rs, 50 paise, 25 paise coins in X, Y, Z, ratio. The task is to determine the number of 1 Rs coins, 50 Paise coins, and 25 paise coins So that after summation of all these we again get the total rupees given.Examples: "
},
{
"code": null,
"e": 616,
"s": 337,
"text": "Input: totalRupees = 1800, X = 1, Y = 2, Z = 4\nOutput: 1 rupees coins = 600\n 50 paisa coins = 1200\n 25 paisa coins = 2400\n\nInput: totalRupees = 2500, X = 2, Y = 4, Z = 2\nOutput: 1 rupees coins = 555\n 50 paisa coins = 1110\n 25 paisa coins = 2220"
},
{
"code": null,
"e": 630,
"s": 618,
"text": "Approach: "
},
{
"code": null,
"e": 1157,
"s": 630,
"text": "Let the ratio in which 1 Rs, 50 paise and 25 paise coin is divided is 1:2:4 Now, 1 Rs coins in a bag is 1x. 50 paise coins in a bag is 2x. 25 paise coins in a bag is 4x.Now convert these paise into Rupees. So, x coins of 1 Rs each, the total value is x rupees. 2x coins of 50 paise i.e (1 / 2) rupees each, the total value is x rupees. 4x coins of 25 paise i.e (1 / 4) rupees each, the total is x rupees.Therefore,3x = 1800 x = 6001 rupess coins = 600 * 1 = 600 50 paisa coins = 600 * 2 = 1200 25 paisa coins = 600 * 4 = 2400 "
},
{
"code": null,
"e": 1210,
"s": 1157,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1214,
"s": 1210,
"text": "C++"
},
{
"code": null,
"e": 1219,
"s": 1214,
"text": "Java"
},
{
"code": null,
"e": 1227,
"s": 1219,
"text": "Python3"
},
{
"code": null,
"e": 1230,
"s": 1227,
"text": "C#"
},
{
"code": null,
"e": 1234,
"s": 1230,
"text": "PHP"
},
{
"code": null,
"e": 1245,
"s": 1234,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // function to calculate coin.int coin(int totalRupees, int X, int Y, int Z){ float one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2.0); twentyfive = ((Z * 1) / 4.0); total = one + fifty + twentyfive; result = ((totalRupees) / total); return result;} // Driver codeint main(){ int totalRupees = 1800; int X = 1, Y = 2, Z = 4; int Rupees = coin(totalRupees, X, Y, Z); cout << \"1 rupess coins = \" << Rupees * 1 << endl; cout << \"50 paisa coins = \" << Rupees * 2 << endl; cout << \"25 paisa coins = \" << Rupees * 4 << endl; return 0;}",
"e": 2045,
"s": 1245,
"text": null
},
{
"code": "// Java implementation of above approach import java.io.*; class GFG { // function to calculate coin. static int coin(int totalRupees, int X, int Y, int Z){ float one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2); twentyfive = ((Z * 1) / 4); total = one + fifty + twentyfive; result = ((totalRupees) / total); return (int)result;} // Driver code public static void main (String[] args) { int totalRupees = 1800; int X = 1, Y = 2, Z = 4; int Rupees = coin(totalRupees, X, Y, Z); System.out.println( \"1 rupess coins = \" + Rupees * 1); System.out.println( \"50 paisa coins = \" + Rupees * 2); System.out.println( \"25 paisa coins = \" + Rupees * 4); }}//This code is contributed by inder_verma.",
"e": 2930,
"s": 2045,
"text": null
},
{
"code": "# Python3 implementation of above approach # function to calculate coin.def coin(totalRupees, X, Y, Z): # Converting each of them in rupees. # As we are given totalRupees = 1800 one = X * 1 fifty = ((Y * 1) / 2.0) twentyfive = ((Z * 1) / 4.0) total = one + fifty + twentyfive result = ((totalRupees) / total) return int(result) # Driver codeif __name__=='__main__': totalRupees = 1800 X, Y, Z = 1, 2, 4 Rupees = coin(totalRupees, X, Y, Z) print(\"1 rupess coins = \", Rupees * 1) print(\"50 paisa coins = \", Rupees * 2) print(\"25 paisa coins = \", Rupees * 4) # This code is contributed by# Sanjit_Prasad",
"e": 3577,
"s": 2930,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // function to calculate coin.static int coin(int totalRupees, int X, int Y, int Z){ float one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2); twentyfive = ((Z * 1) / 4); total = one + fifty + twentyfive; result = ((totalRupees) / total); return (int)result;} // Driver codepublic static void Main (){ int totalRupees = 1800; int X = 1, Y = 2, Z = 4; int Rupees = coin(totalRupees, X, Y, Z); Console.WriteLine( \"1 rupess coins = \" + Rupees * 1); Console.WriteLine( \"50 paisa coins = \" + Rupees * 2); Console.WriteLine( \"25 paisa coins = \" + Rupees * 4);}} // This code is contributed by inder_verma",
"e": 4442,
"s": 3577,
"text": null
},
{
"code": "<?php// PHP implementation of above approach //function to calculate coinfunction coin($totalRupees, $X, $Y, $Z){ $one = 0; $fifty = 0; $twentyfive = 0; $result = 0; $total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 $one = $X * 1; $fifty = (($Y * 1) / 2.0); $twentyfive = (($Z * 1) / 4.0); $total = $one + $fifty + $twentyfive; $result = (($totalRupees) / $total); return $result; } // Driver Code$totalRupees = 1800;$X = 1;$Y = 2;$Z = 4;$Rupees = coin($totalRupees, $X, $Y, $Z);echo \"1 rupess coins = \", $Rupees * 1, \"\\n\";echo \"50 paisa coins = \", $Rupees * 2, \"\\n\";echo \"25 paisa coins = \", $Rupees * 4, \"\\n\"; // This code is contributed// by Shashank_Sharma.?>",
"e": 5203,
"s": 4442,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // function to calculate coin.function coin(totalRupees, X, Y, Z){ var one = 0, fifty = 0, twentyfive = 0, result = 0, total = 0; // Converting each of them in rupees. // As we are given totalRupees = 1800 one = X * 1; fifty = ((Y * 1) / 2.0); twentyfive = ((Z * 1) / 4.0); total = one + fifty + twentyfive; result = ((totalRupees) / total); return result;} // Driver codevar totalRupees = 1800;var X = 1, Y = 2, Z = 4;var Rupees = coin(totalRupees, X, Y, Z);document.write( \"1 rupess coins = \" + Rupees * 1 + \"<br>\");document.write( \"50 paisa coins = \" + Rupees * 2 + \"<br>\");document.write( \"25 paisa coins = \" + Rupees * 4 + \"<br>\"); </script>",
"e": 5945,
"s": 5203,
"text": null
},
{
"code": null,
"e": 6010,
"s": 5945,
"text": "1 rupess coins = 600\n50 paisa coins = 1200\n25 paisa coins = 2400"
},
{
"code": null,
"e": 6026,
"s": 6012,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 6042,
"s": 6026,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 6053,
"s": 6042,
"text": "inderDuMCA"
},
{
"code": null,
"e": 6063,
"s": 6053,
"text": "rutvik_56"
},
{
"code": null,
"e": 6076,
"s": 6063,
"text": "Mathematical"
},
{
"code": null,
"e": 6095,
"s": 6076,
"text": "School Programming"
},
{
"code": null,
"e": 6108,
"s": 6095,
"text": "Mathematical"
}
] |
Vector elements() Method in Java
|
17 Aug, 2018
The java.util.vector.elements() method of Vector class in Java is used to get the enumeration of the values present in the Vector.
Syntax:
Enumeration enu = Vector.elements()
Parameters: The method does not take any parameters.
Return value: The method returns an enumeration of the values of the Vector.
Below programs are used to illustrate the working of the java.util.Vector.elements() method:
Program 1:
// Java code to illustrate the elements() methodimport java.util.*; public class Vector_Demo { public static void main(String[] args) { // Creating an empty Vector Vector<String> vec_tor = new Vector<String>(5); // Inserting elements into the table vec_tor.add("Geeks"); vec_tor.add("4"); vec_tor.add("Geeks"); vec_tor.add("Welcomes"); vec_tor.add("You"); // Displaying the Vector System.out.println("The Vector is: " + vec_tor); // Creating an empty enumeration to store Enumeration enu = vec_tor.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}
The Vector is: [Geeks, 4, Geeks, Welcomes, You]
The enumeration of values are:
Geeks
4
Geeks
Welcomes
You
Program 2 :
import java.util.*; public class Vector_Demo { public static void main(String[] args) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(5); // Inserting elements into the table vec_tor.add(10); vec_tor.add(15); vec_tor.add(20); vec_tor.add(25); vec_tor.add(30); // Displaying the Vector System.out.println("The Vector is: " + vec_tor); // Creating an empty enumeration to store Enumeration enu = vec_tor.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}
The Vector is: [10, 15, 20, 25, 30]
The enumeration of values are:
10
15
20
25
30
Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Aug, 2018"
},
{
"code": null,
"e": 184,
"s": 53,
"text": "The java.util.vector.elements() method of Vector class in Java is used to get the enumeration of the values present in the Vector."
},
{
"code": null,
"e": 192,
"s": 184,
"text": "Syntax:"
},
{
"code": null,
"e": 228,
"s": 192,
"text": "Enumeration enu = Vector.elements()"
},
{
"code": null,
"e": 281,
"s": 228,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 358,
"s": 281,
"text": "Return value: The method returns an enumeration of the values of the Vector."
},
{
"code": null,
"e": 451,
"s": 358,
"text": "Below programs are used to illustrate the working of the java.util.Vector.elements() method:"
},
{
"code": null,
"e": 462,
"s": 451,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate the elements() methodimport java.util.*; public class Vector_Demo { public static void main(String[] args) { // Creating an empty Vector Vector<String> vec_tor = new Vector<String>(5); // Inserting elements into the table vec_tor.add(\"Geeks\"); vec_tor.add(\"4\"); vec_tor.add(\"Geeks\"); vec_tor.add(\"Welcomes\"); vec_tor.add(\"You\"); // Displaying the Vector System.out.println(\"The Vector is: \" + vec_tor); // Creating an empty enumeration to store Enumeration enu = vec_tor.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}",
"e": 1277,
"s": 462,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1277,
"text": "The Vector is: [Geeks, 4, Geeks, Welcomes, You]\nThe enumeration of values are:\nGeeks\n4\nGeeks\nWelcomes\nYou\n"
},
{
"code": null,
"e": 1396,
"s": 1384,
"text": "Program 2 :"
},
{
"code": "import java.util.*; public class Vector_Demo { public static void main(String[] args) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(5); // Inserting elements into the table vec_tor.add(10); vec_tor.add(15); vec_tor.add(20); vec_tor.add(25); vec_tor.add(30); // Displaying the Vector System.out.println(\"The Vector is: \" + vec_tor); // Creating an empty enumeration to store Enumeration enu = vec_tor.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}",
"e": 2143,
"s": 1396,
"text": null
},
{
"code": null,
"e": 2226,
"s": 2143,
"text": "The Vector is: [10, 15, 20, 25, 30]\nThe enumeration of values are:\n10\n15\n20\n25\n30\n"
},
{
"code": null,
"e": 2246,
"s": 2226,
"text": "Java - util package"
},
{
"code": null,
"e": 2263,
"s": 2246,
"text": "Java-Collections"
},
{
"code": null,
"e": 2278,
"s": 2263,
"text": "Java-Functions"
},
{
"code": null,
"e": 2290,
"s": 2278,
"text": "Java-Vector"
},
{
"code": null,
"e": 2295,
"s": 2290,
"text": "Java"
},
{
"code": null,
"e": 2300,
"s": 2295,
"text": "Java"
},
{
"code": null,
"e": 2317,
"s": 2300,
"text": "Java-Collections"
}
] |
Maximum sum of hour glass in matrix
|
13 Jun, 2022
Given a 2D matrix, the task is to find the maximum sum of an hourglass.
An hour glass is made of 7 cells
in following form.
A B C
D
E F G
Examples:
Input : 1 1 1 0 0
0 1 0 0 0
1 1 1 0 0
0 0 0 0 0
0 0 0 0 0
Output : 7
Below is the hour glass with
maximum sum:
1 1 1
1
1 1 1
Input : 0 3 0 0 0
0 1 0 0 0
1 1 1 0 0
0 0 2 4 4
0 0 0 2 4
Output : 11
Below is the hour glass with
maximum sum
1 0 0
4
0 2 4
Approach:It is evident from the definition of the hourglass that the number of rows and number of columns must be equal to 3. If we count the total number of hourglasses in a matrix, we can say that the count is equal to the count of possible top left cells in an hourglass. The number of top-left cells in an hourglass is equal to (R-2)*(C-2). Therefore, in a matrix total number of an hourglass is (R-2)*(C-2).
mat[][] = 2 3 0 0 0
0 1 0 0 0
1 1 1 0 0
0 0 2 4 4
0 0 0 2 0
Possible hour glass are :
2 3 0 3 0 0 0 0 0
1 0 0
1 1 1 1 1 0 1 0 0
0 1 0 1 0 0 0 0 0
1 1 0
0 0 2 0 2 4 2 4 4
1 1 1 1 1 0 1 0 0
0 2 4
0 0 0 0 0 2 0 2 0
Consider all top left cells of hourglasses one by one. For every cell, we compute the sum of the hourglass formed by it. Finally, return the maximum sum.Below is the implementation of the above idea:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum sum of hour// glass in matrix#include<bits/stdc++.h>using namespace std;const int R = 5;const int C = 5; // Returns maximum sum of hour glass in ar[][]int findMaxSum(int mat[R][C]){ if (R<3 || C<3){ cout << "Not possible" << endl; exit(0); } // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. int max_sum = INT_MIN; for (int i=0; i<R-2; i++) { for (int j=0; j<C-2; j++) { // Considering mat[i][j] as top left cell of // hour glass. int sum = (mat[i][j]+mat[i][j+1]+mat[i][j+2])+ (mat[i+1][j+1])+ (mat[i+2][j]+mat[i+2][j+1]+mat[i+2][j+2]); // If previous sum is less then current sum then // update new sum in max_sum max_sum = max(max_sum, sum); } } return max_sum;} // Driver codeint main(){ int mat[][C] = {{1, 2, 3, 0, 0}, {0, 0, 0, 0, 0}, {2, 1, 4, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 1, 0}}; int res = findMaxSum(mat); cout << "Maximum sum of hour glass = "<< res << endl; return 0;} //Code is modified by Susobhan Akhuli
/* C program to find the maximum sum of hour glass in a Matrix */#include <stdio.h>#include <stdlib.h>// Fixing the size of the matrix// ( Here it is of the order 6// x 6 )#define R 5#define C 5 // Function to find the maximum// sum of the hour glassint MaxSum(int arr[R][C]){ int i, j, sum; if (R<3 || C<3){ printf("Not Possible"); exit(0); } int max_sum = -500000; /* Considering the matrix also contains negative values , so initialized with -50000. It can be any value but very smaller.*/ // int max_sum=0 -> Initialize with 0 only if your // matrix elements are positive // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. for (i = 0; i < R - 2; i++) { for (j = 0; j < C - 2; j++) { // Considering arr[i][j] as top left cell of // hour glass. sum = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2]) + (arr[i + 1][j + 1]) + (arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]); // If previous sum is less then current sum then // update new sum in max_sum if (sum > max_sum) max_sum = sum; else continue; } } return max_sum;} // Driver Codeint main(){ int arr[][C] = { { 1, 2, 3, 0, 0 }, { 0, 0, 0, 0, 0 }, { 2, 1, 4, 0, 0 }, { 0, 0, 0, 0, 0 }, { 1, 1, 0, 1, 0 } }; int res = MaxSum(arr); printf("Maximum sum of hour glass = %d", res); return 0;} // This code is written by Akshay Prakash// Code is modified by Susobhan Akhuli
// Java program to find maximum// sum of hour glass in matriximport java.io.*; class GFG { static int R = 5;static int C = 5; // Returns maximum sum of// hour glass in ar[][]static int findMaxSum(int [][]mat){ if (R < 3 || C < 3){ System.out.println("Not possible"); System.exit(0); } // Here loop runs (R-2)*(C-2) // times considering different // top left cells of hour glasses. int max_sum = Integer.MIN_VALUE; for (int i = 0; i < R - 2; i++) { for (int j = 0; j < C - 2; j++) { // Considering mat[i][j] as top // left cell of hour glass. int sum = (mat[i][j] + mat[i][j + 1] + mat[i][j + 2]) + (mat[i + 1][j + 1]) + (mat[i + 2][j] + mat[i + 2][j + 1] + mat[i + 2][j + 2]); // If previous sum is less then // current sum then update // new sum in max_sum max_sum = Math.max(max_sum, sum); } } return max_sum;} // Driver code static public void main (String[] args) { int [][]mat = {{1, 2, 3, 0, 0}, {0, 0, 0, 0, 0}, {2, 1, 4, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 1, 0}}; int res = findMaxSum(mat); System.out.println("Maximum sum of hour glass = "+ res); } } // This code is contributed by vt_m .// Code is modified by Susobhan Akhuli
# Python 3 program to find the maximum# sum of hour glass in a Matrix # Fixing the size of the Matrix.# Here it is of order 6 x 6R = 5C = 5 # Function to find the maximum sum of hour glassdef MaxSum(arr): # Considering the matrix also contains max_sum = -50000 # Negative values , so initialized with # -50000. It can be any value but very # smaller. # max_sum=0 -> Initialize with 0 only if your # matrix elements are positive if(R < 3 or C < 3): print("Not possible") exit() # Here loop runs (R-2)*(C-2) times considering # different top left cells of hour glasses. for i in range(0, R-2): for j in range(0, C-2): # Considering arr[i][j] as top # left cell of hour glass. SUM = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2]) + (arr[i + 1][j + 1]) + (arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]) # If previous sum is less # then current sum then # update new sum in max_sum if(SUM > max_sum): max_sum = SUM else: continue return max_sum # Driver Codearr = [[1, 2, 3, 0, 0], [0, 0, 0, 0, 0], [2, 1, 4, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 0]]res = MaxSum(arr) print(f"Maximum sum of hour glass = {res}") # This code is written by Akshay Prakash# Code is modified by Susobhan Akhuli
// C# program to find maximum// sum of hour glass in matrixusing System; class GFG { static int R = 5;static int C = 5; // Returns maximum sum of// hour glass in ar[][]static int findMaxSum(int [,]mat){ if (R < 3 || C < 3){ Console.WriteLine("Not possible"); Environment.Exit(0); } // Here loop runs (R-2)*(C-2) // times considering different // top left cells of hour glasses. int max_sum = int.MinValue; for (int i = 0; i < R - 2; i++) { for (int j = 0; j < C - 2; j++) { // Considering mat[i][j] as top // left cell of hour glass. int sum = (mat[i, j] + mat[i, j + 1] + mat[i, j + 2]) + (mat[i + 1, j + 1]) + (mat[i + 2, j] + mat[i + 2, j + 1] + mat[i + 2, j + 2]); // If previous sum is less then // current sum then update // new sum in max_sum max_sum = Math.Max(max_sum, sum); } } return max_sum;} // Driver code static public void Main(String[] args) { int [,]mat = {{1, 2, 3, 0, 0}, {0, 0, 0, 0, 0}, {2, 1, 4, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 1, 0}}; int res = findMaxSum(mat); Console.WriteLine("Maximum sum of hour glass = "+ res); } } // This code is contributed by vt_m .// Code is modified by Susobhan Akhuli
<?php// PHP program to find maximum sum// of hour glass in matrix$R = 5;$C = 5; // Returns maximum sum// of hour glass in ar[][]function findMaxSum($mat){ global $R; global $C; if ($R < 3 || $C < 3){ exit("Not possible"); } // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. $max_sum = PHP_INT_MIN; for ($i = 0; $i < ($R - 2); $i++) { for ($j = 0; $j < ($C - 2); $j++) { // Considering mat[i][j] as // top left cell of hour glass. $sum = ($mat[$i][$j] + $mat[$i][$j + 1] + $mat[$i][$j + 2]) + ($mat[$i + 1][$j + 1]) + ($mat[$i + 2][$j] + $mat[$i + 2][$j + 1] + $mat[$i + 2][$j + 2]); // If previous sum is less than current sum // then update new sum in max_sum $max_sum = max($max_sum, $sum); } } return $max_sum;} // Driver code$mat = array(array(1, 2, 3, 0, 0), array(0, 0, 0, 0, 0), array(2, 1, 4, 0, 0), array(0, 0, 0, 0, 0), array(1, 1, 0, 1, 0));$res = findMaxSum($mat);echo "Maximum sum of hour glass = ",$res, "\n"; // This code is contributed by ajit.// Code is modified by Susobhan Akhuli?>
<script> // Javascript program to find maximum // sum of hour glass in matrix let R = 5; let C = 5; // Returns maximum sum of // hour glass in ar[][] function findMaxSum(mat) { if (R < 3 || C < 3){ document.write("Not possible"); process.exit(0); } // Here loop runs (R-2)*(C-2) // times considering different // top left cells of hour glasses. let max_sum = Number.MIN_VALUE; for (let i = 0; i < R - 2; i++) { for (let j = 0; j < C - 2; j++) { // Considering mat[i][j] as top // left cell of hour glass. let sum = (mat[i][j] + mat[i][j + 1] + mat[i][j + 2]) + (mat[i + 1][j + 1]) + (mat[i + 2][j] + mat[i + 2][j + 1] + mat[i + 2][j + 2]); // If previous sum is less then // current sum then update // new sum in max_sum max_sum = Math.max(max_sum, sum); } } return max_sum; } let mat = [[1, 2, 3, 0, 0], [0, 0, 0, 0, 0], [2, 1, 4, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 0]]; let res = findMaxSum(mat); document.write("Maximum sum of hour glass = " + res); </script>
Maximum sum of hour glass = 13
Time complexity: O(R x C).Auxiliary Space: O(1)
Reference : http://stackoverflow.com/questions/38019861/hourglass-sum-in-2d-arrayThis article is contributed by AKSHAY PRAKASH. 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.
vt_m
jit_t
SrinivasaLakkaraju
prakashakshay122
divyeshrabadiya07
akshays0nawan3
amartyaghoshgfg
susobhanakhuli
codewithmini
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 124,
"s": 52,
"text": "Given a 2D matrix, the task is to find the maximum sum of an hourglass."
},
{
"code": null,
"e": 204,
"s": 124,
"text": "An hour glass is made of 7 cells\nin following form.\n A B C\n D\n E F G"
},
{
"code": null,
"e": 215,
"s": 204,
"text": "Examples: "
},
{
"code": null,
"e": 594,
"s": 215,
"text": "Input : 1 1 1 0 0 \n 0 1 0 0 0 \n 1 1 1 0 0 \n 0 0 0 0 0 \n 0 0 0 0 0 \nOutput : 7\nBelow is the hour glass with\nmaximum sum:\n1 1 1 \n 1\n1 1 1\n \nInput : 0 3 0 0 0\n 0 1 0 0 0\n 1 1 1 0 0\n 0 0 2 4 4\n 0 0 0 2 4\nOutput : 11\nBelow is the hour glass with\nmaximum sum\n1 0 0\n 4\n0 2 4"
},
{
"code": null,
"e": 1007,
"s": 594,
"text": "Approach:It is evident from the definition of the hourglass that the number of rows and number of columns must be equal to 3. If we count the total number of hourglasses in a matrix, we can say that the count is equal to the count of possible top left cells in an hourglass. The number of top-left cells in an hourglass is equal to (R-2)*(C-2). Therefore, in a matrix total number of an hourglass is (R-2)*(C-2)."
},
{
"code": null,
"e": 1322,
"s": 1007,
"text": "mat[][] = 2 3 0 0 0 \n 0 1 0 0 0\n 1 1 1 0 0 \n 0 0 2 4 4\n 0 0 0 2 0\nPossible hour glass are :\n2 3 0 3 0 0 0 0 0 \n 1 0 0 \n1 1 1 1 1 0 1 0 0 \n\n0 1 0 1 0 0 0 0 0 \n 1 1 0 \n0 0 2 0 2 4 2 4 4 \n\n1 1 1 1 1 0 1 0 0\n 0 2 4\n0 0 0 0 0 2 0 2 0"
},
{
"code": null,
"e": 1522,
"s": 1322,
"text": "Consider all top left cells of hourglasses one by one. For every cell, we compute the sum of the hourglass formed by it. Finally, return the maximum sum.Below is the implementation of the above idea:"
},
{
"code": null,
"e": 1526,
"s": 1522,
"text": "C++"
},
{
"code": null,
"e": 1528,
"s": 1526,
"text": "C"
},
{
"code": null,
"e": 1533,
"s": 1528,
"text": "Java"
},
{
"code": null,
"e": 1541,
"s": 1533,
"text": "Python3"
},
{
"code": null,
"e": 1544,
"s": 1541,
"text": "C#"
},
{
"code": null,
"e": 1548,
"s": 1544,
"text": "PHP"
},
{
"code": null,
"e": 1559,
"s": 1548,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum sum of hour// glass in matrix#include<bits/stdc++.h>using namespace std;const int R = 5;const int C = 5; // Returns maximum sum of hour glass in ar[][]int findMaxSum(int mat[R][C]){ if (R<3 || C<3){ cout << \"Not possible\" << endl; exit(0); } // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. int max_sum = INT_MIN; for (int i=0; i<R-2; i++) { for (int j=0; j<C-2; j++) { // Considering mat[i][j] as top left cell of // hour glass. int sum = (mat[i][j]+mat[i][j+1]+mat[i][j+2])+ (mat[i+1][j+1])+ (mat[i+2][j]+mat[i+2][j+1]+mat[i+2][j+2]); // If previous sum is less then current sum then // update new sum in max_sum max_sum = max(max_sum, sum); } } return max_sum;} // Driver codeint main(){ int mat[][C] = {{1, 2, 3, 0, 0}, {0, 0, 0, 0, 0}, {2, 1, 4, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 1, 0}}; int res = findMaxSum(mat); cout << \"Maximum sum of hour glass = \"<< res << endl; return 0;} //Code is modified by Susobhan Akhuli",
"e": 2816,
"s": 1559,
"text": null
},
{
"code": "/* C program to find the maximum sum of hour glass in a Matrix */#include <stdio.h>#include <stdlib.h>// Fixing the size of the matrix// ( Here it is of the order 6// x 6 )#define R 5#define C 5 // Function to find the maximum// sum of the hour glassint MaxSum(int arr[R][C]){ int i, j, sum; if (R<3 || C<3){ printf(\"Not Possible\"); exit(0); } int max_sum = -500000; /* Considering the matrix also contains negative values , so initialized with -50000. It can be any value but very smaller.*/ // int max_sum=0 -> Initialize with 0 only if your // matrix elements are positive // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. for (i = 0; i < R - 2; i++) { for (j = 0; j < C - 2; j++) { // Considering arr[i][j] as top left cell of // hour glass. sum = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2]) + (arr[i + 1][j + 1]) + (arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]); // If previous sum is less then current sum then // update new sum in max_sum if (sum > max_sum) max_sum = sum; else continue; } } return max_sum;} // Driver Codeint main(){ int arr[][C] = { { 1, 2, 3, 0, 0 }, { 0, 0, 0, 0, 0 }, { 2, 1, 4, 0, 0 }, { 0, 0, 0, 0, 0 }, { 1, 1, 0, 1, 0 } }; int res = MaxSum(arr); printf(\"Maximum sum of hour glass = %d\", res); return 0;} // This code is written by Akshay Prakash// Code is modified by Susobhan Akhuli",
"e": 4598,
"s": 2816,
"text": null
},
{
"code": "// Java program to find maximum// sum of hour glass in matriximport java.io.*; class GFG { static int R = 5;static int C = 5; // Returns maximum sum of// hour glass in ar[][]static int findMaxSum(int [][]mat){ if (R < 3 || C < 3){ System.out.println(\"Not possible\"); System.exit(0); } // Here loop runs (R-2)*(C-2) // times considering different // top left cells of hour glasses. int max_sum = Integer.MIN_VALUE; for (int i = 0; i < R - 2; i++) { for (int j = 0; j < C - 2; j++) { // Considering mat[i][j] as top // left cell of hour glass. int sum = (mat[i][j] + mat[i][j + 1] + mat[i][j + 2]) + (mat[i + 1][j + 1]) + (mat[i + 2][j] + mat[i + 2][j + 1] + mat[i + 2][j + 2]); // If previous sum is less then // current sum then update // new sum in max_sum max_sum = Math.max(max_sum, sum); } } return max_sum;} // Driver code static public void main (String[] args) { int [][]mat = {{1, 2, 3, 0, 0}, {0, 0, 0, 0, 0}, {2, 1, 4, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 1, 0}}; int res = findMaxSum(mat); System.out.println(\"Maximum sum of hour glass = \"+ res); } } // This code is contributed by vt_m .// Code is modified by Susobhan Akhuli",
"e": 6073,
"s": 4598,
"text": null
},
{
"code": "# Python 3 program to find the maximum# sum of hour glass in a Matrix # Fixing the size of the Matrix.# Here it is of order 6 x 6R = 5C = 5 # Function to find the maximum sum of hour glassdef MaxSum(arr): # Considering the matrix also contains max_sum = -50000 # Negative values , so initialized with # -50000. It can be any value but very # smaller. # max_sum=0 -> Initialize with 0 only if your # matrix elements are positive if(R < 3 or C < 3): print(\"Not possible\") exit() # Here loop runs (R-2)*(C-2) times considering # different top left cells of hour glasses. for i in range(0, R-2): for j in range(0, C-2): # Considering arr[i][j] as top # left cell of hour glass. SUM = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2]) + (arr[i + 1][j + 1]) + (arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]) # If previous sum is less # then current sum then # update new sum in max_sum if(SUM > max_sum): max_sum = SUM else: continue return max_sum # Driver Codearr = [[1, 2, 3, 0, 0], [0, 0, 0, 0, 0], [2, 1, 4, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 0]]res = MaxSum(arr) print(f\"Maximum sum of hour glass = {res}\") # This code is written by Akshay Prakash# Code is modified by Susobhan Akhuli",
"e": 7519,
"s": 6073,
"text": null
},
{
"code": "// C# program to find maximum// sum of hour glass in matrixusing System; class GFG { static int R = 5;static int C = 5; // Returns maximum sum of// hour glass in ar[][]static int findMaxSum(int [,]mat){ if (R < 3 || C < 3){ Console.WriteLine(\"Not possible\"); Environment.Exit(0); } // Here loop runs (R-2)*(C-2) // times considering different // top left cells of hour glasses. int max_sum = int.MinValue; for (int i = 0; i < R - 2; i++) { for (int j = 0; j < C - 2; j++) { // Considering mat[i][j] as top // left cell of hour glass. int sum = (mat[i, j] + mat[i, j + 1] + mat[i, j + 2]) + (mat[i + 1, j + 1]) + (mat[i + 2, j] + mat[i + 2, j + 1] + mat[i + 2, j + 2]); // If previous sum is less then // current sum then update // new sum in max_sum max_sum = Math.Max(max_sum, sum); } } return max_sum;} // Driver code static public void Main(String[] args) { int [,]mat = {{1, 2, 3, 0, 0}, {0, 0, 0, 0, 0}, {2, 1, 4, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 1, 0}}; int res = findMaxSum(mat); Console.WriteLine(\"Maximum sum of hour glass = \"+ res); } } // This code is contributed by vt_m .// Code is modified by Susobhan Akhuli",
"e": 8978,
"s": 7519,
"text": null
},
{
"code": "<?php// PHP program to find maximum sum// of hour glass in matrix$R = 5;$C = 5; // Returns maximum sum// of hour glass in ar[][]function findMaxSum($mat){ global $R; global $C; if ($R < 3 || $C < 3){ exit(\"Not possible\"); } // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. $max_sum = PHP_INT_MIN; for ($i = 0; $i < ($R - 2); $i++) { for ($j = 0; $j < ($C - 2); $j++) { // Considering mat[i][j] as // top left cell of hour glass. $sum = ($mat[$i][$j] + $mat[$i][$j + 1] + $mat[$i][$j + 2]) + ($mat[$i + 1][$j + 1]) + ($mat[$i + 2][$j] + $mat[$i + 2][$j + 1] + $mat[$i + 2][$j + 2]); // If previous sum is less than current sum // then update new sum in max_sum $max_sum = max($max_sum, $sum); } } return $max_sum;} // Driver code$mat = array(array(1, 2, 3, 0, 0), array(0, 0, 0, 0, 0), array(2, 1, 4, 0, 0), array(0, 0, 0, 0, 0), array(1, 1, 0, 1, 0));$res = findMaxSum($mat);echo \"Maximum sum of hour glass = \",$res, \"\\n\"; // This code is contributed by ajit.// Code is modified by Susobhan Akhuli?>",
"e": 10287,
"s": 8978,
"text": null
},
{
"code": "<script> // Javascript program to find maximum // sum of hour glass in matrix let R = 5; let C = 5; // Returns maximum sum of // hour glass in ar[][] function findMaxSum(mat) { if (R < 3 || C < 3){ document.write(\"Not possible\"); process.exit(0); } // Here loop runs (R-2)*(C-2) // times considering different // top left cells of hour glasses. let max_sum = Number.MIN_VALUE; for (let i = 0; i < R - 2; i++) { for (let j = 0; j < C - 2; j++) { // Considering mat[i][j] as top // left cell of hour glass. let sum = (mat[i][j] + mat[i][j + 1] + mat[i][j + 2]) + (mat[i + 1][j + 1]) + (mat[i + 2][j] + mat[i + 2][j + 1] + mat[i + 2][j + 2]); // If previous sum is less then // current sum then update // new sum in max_sum max_sum = Math.max(max_sum, sum); } } return max_sum; } let mat = [[1, 2, 3, 0, 0], [0, 0, 0, 0, 0], [2, 1, 4, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 0]]; let res = findMaxSum(mat); document.write(\"Maximum sum of hour glass = \" + res); </script>",
"e": 11668,
"s": 10287,
"text": null
},
{
"code": null,
"e": 11699,
"s": 11668,
"text": "Maximum sum of hour glass = 13"
},
{
"code": null,
"e": 11747,
"s": 11699,
"text": "Time complexity: O(R x C).Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12250,
"s": 11747,
"text": "Reference : http://stackoverflow.com/questions/38019861/hourglass-sum-in-2d-arrayThis article is contributed by AKSHAY PRAKASH. 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": 12255,
"s": 12250,
"text": "vt_m"
},
{
"code": null,
"e": 12261,
"s": 12255,
"text": "jit_t"
},
{
"code": null,
"e": 12280,
"s": 12261,
"text": "SrinivasaLakkaraju"
},
{
"code": null,
"e": 12297,
"s": 12280,
"text": "prakashakshay122"
},
{
"code": null,
"e": 12315,
"s": 12297,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 12330,
"s": 12315,
"text": "akshays0nawan3"
},
{
"code": null,
"e": 12346,
"s": 12330,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 12361,
"s": 12346,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 12374,
"s": 12361,
"text": "codewithmini"
},
{
"code": null,
"e": 12381,
"s": 12374,
"text": "Matrix"
},
{
"code": null,
"e": 12388,
"s": 12381,
"text": "Matrix"
}
] |
What are the types of Popup box available in JavaScript ?
|
13 Jun, 2022
In Javascript, popup boxes are used to display the message or notification to the user. There are three types of pop-up boxes in JavaScript namely Alert Box, Confirm Box and Prompt Box.
Alert Box: It is used when a warning message is needed to be produced. When the alert box is displayed to the user, the user needs to press ok and proceed.
Syntax:
alert("your Alert here")
Example:
HTML
<!DOCTYPE html><html> <head> <title>Pop-up Box type | Alert Box</title> <style> h1{ color:green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Alert Box</h3> <button onclick="geekAlert()"> Click here for alert box </button> <!-- Alert box function --> <script> function geekAlert() { alert("An Online Computer Science" + "Portal for Geeks"); } </script> </center> </body> </html>
Output: Before pressing the button:
After pressing the button:
Prompt Box: It is a type of pop up box which is used to get the user input for further use. After entering the required details user have to click ok to proceed next stage else by pressing the cancel button user returns the null value.
Syntax:
prompt("your Prompt here")
Example:
HTML
<!DOCTYPE html><html> <head> <title> Pop-up Box type | Prompt Box </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Prompt Box</h3> <input type="button" onclick="geekPrompt();" value="Click here for Prompt box"/> <!-- Prompt box function --> <script> function geekPrompt() { var x = prompt("Enter your mail here : "); document.write("Your ID : " + x); } </script> </center> </body> </html>
Output: Before pressing the button:
After pressing the button:
Confirm Box: It is a type of pop-up box that is used to get authorization or permission from the user. The user has to press the ok or cancel button to proceed.
Syntax:
confirm("your query here")
Example:
HTML
<!DOCTYPE html><html> <head> <title> Pop-up Box type | Confirm Box </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Confirm Box</h3> <button onclick="geekConfirm()"> Click here for Confirm box </button> <p id="geek"></p> <!-- Confirm box function --> <script> function geekConfirm() { var x; if (confirm("Press a button!") == true) { x = "OK pressed!"; } else { x = "Cancel!"; } document.getElementById("geek").innerHTML = x; } </script> </center></body> </html>
Output: Before pressing the button:
After pressing the button:
HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Akanksha_Rai
anikakapoor
sanjyotpanure
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 238,
"s": 52,
"text": "In Javascript, popup boxes are used to display the message or notification to the user. There are three types of pop-up boxes in JavaScript namely Alert Box, Confirm Box and Prompt Box."
},
{
"code": null,
"e": 394,
"s": 238,
"text": "Alert Box: It is used when a warning message is needed to be produced. When the alert box is displayed to the user, the user needs to press ok and proceed."
},
{
"code": null,
"e": 403,
"s": 394,
"text": "Syntax: "
},
{
"code": null,
"e": 428,
"s": 403,
"text": "alert(\"your Alert here\")"
},
{
"code": null,
"e": 439,
"s": 428,
"text": "Example: "
},
{
"code": null,
"e": 444,
"s": 439,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Pop-up Box type | Alert Box</title> <style> h1{ color:green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Alert Box</h3> <button onclick=\"geekAlert()\"> Click here for alert box </button> <!-- Alert box function --> <script> function geekAlert() { alert(\"An Online Computer Science\" + \"Portal for Geeks\"); } </script> </center> </body> </html>",
"e": 1016,
"s": 444,
"text": null
},
{
"code": null,
"e": 1053,
"s": 1016,
"text": "Output: Before pressing the button: "
},
{
"code": null,
"e": 1084,
"s": 1055,
"text": "After pressing the button: "
},
{
"code": null,
"e": 1322,
"s": 1086,
"text": "Prompt Box: It is a type of pop up box which is used to get the user input for further use. After entering the required details user have to click ok to proceed next stage else by pressing the cancel button user returns the null value."
},
{
"code": null,
"e": 1332,
"s": 1322,
"text": "Syntax: "
},
{
"code": null,
"e": 1359,
"s": 1332,
"text": "prompt(\"your Prompt here\")"
},
{
"code": null,
"e": 1370,
"s": 1359,
"text": "Example: "
},
{
"code": null,
"e": 1375,
"s": 1370,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Pop-up Box type | Prompt Box </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Prompt Box</h3> <input type=\"button\" onclick=\"geekPrompt();\" value=\"Click here for Prompt box\"/> <!-- Prompt box function --> <script> function geekPrompt() { var x = prompt(\"Enter your mail here : \"); document.write(\"Your ID : \" + x); } </script> </center> </body> </html>",
"e": 1972,
"s": 1375,
"text": null
},
{
"code": null,
"e": 2009,
"s": 1972,
"text": "Output: Before pressing the button: "
},
{
"code": null,
"e": 2039,
"s": 2011,
"text": "After pressing the button: "
},
{
"code": null,
"e": 2202,
"s": 2041,
"text": "Confirm Box: It is a type of pop-up box that is used to get authorization or permission from the user. The user has to press the ok or cancel button to proceed."
},
{
"code": null,
"e": 2210,
"s": 2202,
"text": "Syntax:"
},
{
"code": null,
"e": 2237,
"s": 2210,
"text": "confirm(\"your query here\")"
},
{
"code": null,
"e": 2248,
"s": 2237,
"text": "Example: "
},
{
"code": null,
"e": 2253,
"s": 2248,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Pop-up Box type | Confirm Box </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Confirm Box</h3> <button onclick=\"geekConfirm()\"> Click here for Confirm box </button> <p id=\"geek\"></p> <!-- Confirm box function --> <script> function geekConfirm() { var x; if (confirm(\"Press a button!\") == true) { x = \"OK pressed!\"; } else { x = \"Cancel!\"; } document.getElementById(\"geek\").innerHTML = x; } </script> </center></body> </html>",
"e": 3022,
"s": 2253,
"text": null
},
{
"code": null,
"e": 3059,
"s": 3022,
"text": "Output: Before pressing the button: "
},
{
"code": null,
"e": 3089,
"s": 3061,
"text": "After pressing the button: "
},
{
"code": null,
"e": 3290,
"s": 3091,
"text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 3509,
"s": 3290,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3522,
"s": 3509,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3534,
"s": 3522,
"text": "anikakapoor"
},
{
"code": null,
"e": 3548,
"s": 3534,
"text": "sanjyotpanure"
},
{
"code": null,
"e": 3564,
"s": 3548,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3571,
"s": 3564,
"text": "Picked"
},
{
"code": null,
"e": 3582,
"s": 3571,
"text": "JavaScript"
},
{
"code": null,
"e": 3599,
"s": 3582,
"text": "Web Technologies"
},
{
"code": null,
"e": 3626,
"s": 3599,
"text": "Web technologies Questions"
}
] |
Cross Origin Resource Sharing (CORS)
|
07 Nov, 2018
CORS (Cross-Origin Resource Sharing) is a mechanism by which data or any other resource of a site could be shared intentionally to a third party website when there is a need. Generally, access to resources that are residing in a third party site is restricted by the browser clients for security purposes.
Client side code to make an HTTP Call would look like below,
function httpGetAction(urlLink)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", urlLink, false );
xmlHttp.send();
return xmlHttp.responseText;
}
This native JavaScript method is intended to make an HTTP call to the given link urlLink via the GET method and return the response text from the third party resource.
By default, a request to non-parent domains (domains other than the domain from which you are making the call) is blocked by the browser. If you try to do so, the console would throw the following error.,
Failed to load https://contribute.geeksforgeeks.org/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.google.com' is therefore not allowed access.
Of course, there are some cases where you need to access a third party website like getting a public image, making a non-state changing API Call or accessing other domain which you own yourself. There are some ways to achieve this, as and when necessary.
One could get an idea from the error message that the Access-Control-Allow-Origin Header is not present on the requested resource. It simply means that the target website whose resource you are trying to access haven’t specifically allowed you to get the resource from their site.
This could be done with an additional HTTP Header, Access-Control-Allow-Origin. This header could take the following values.,
Access-Control-Allow-Origin : [origin]Example : Access-Control-Allow-Origin: https://contribute.geeksforgeeks.orgThis allows you to specifically allow one website to access your resource. In this case, https://contribute.geeksforgeeks.org can access your web resource, since it is explicitly allowed.This require an additional header called ORIGIN sent from the requesting client containing its hostname. This origin header is matched against the allowed origin and the access to the resource is decided.
Access-Control-Allow-Origin : *Example : Access-Control-Allow-Origin: *Wildcard character (*) means that any site can access the resource you have it in your site and obviously its unsafe.
Based on the request methods (GET/PUT/POST/DELETE) and the request headers, the requests are classified into two categories.
Simple RequestsNon Simple/Complex RequestsSimple RequestsFor Simple Requests, the CORS Works on the following way,Request is made to a third party site with ORIGIN Header.On the target site, the ORIGIN value is compared with the allowed origins.If the source is an allowed one, then the resource is granted access, else denied.Complex RequestsFor Complex Requests, the CORS Works on the following way,Before the actual request is sent, a pre-flight request is sent to the target site.This pre-flight request is sent via the OPTIONS HTTP Request method.Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site.After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser.Whenever there is a need to share the resources to a third party site, the site should be specifically whitelisted with Access-Control-Allow-Origin : https://sitename.com instead of wildcards as a security best practice.References : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORSMy Personal Notes
arrow_drop_upSave
Simple Requests
Non Simple/Complex Requests
Simple RequestsFor Simple Requests, the CORS Works on the following way,Request is made to a third party site with ORIGIN Header.On the target site, the ORIGIN value is compared with the allowed origins.If the source is an allowed one, then the resource is granted access, else denied.Complex RequestsFor Complex Requests, the CORS Works on the following way,Before the actual request is sent, a pre-flight request is sent to the target site.This pre-flight request is sent via the OPTIONS HTTP Request method.Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site.After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser.Whenever there is a need to share the resources to a third party site, the site should be specifically whitelisted with Access-Control-Allow-Origin : https://sitename.com instead of wildcards as a security best practice.References : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORSMy Personal Notes
arrow_drop_upSave
Simple RequestsFor Simple Requests, the CORS Works on the following way,
Request is made to a third party site with ORIGIN Header.On the target site, the ORIGIN value is compared with the allowed origins.If the source is an allowed one, then the resource is granted access, else denied.
Request is made to a third party site with ORIGIN Header.
On the target site, the ORIGIN value is compared with the allowed origins.
If the source is an allowed one, then the resource is granted access, else denied.
Complex RequestsFor Complex Requests, the CORS Works on the following way,
Before the actual request is sent, a pre-flight request is sent to the target site.This pre-flight request is sent via the OPTIONS HTTP Request method.Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site.After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser.
Before the actual request is sent, a pre-flight request is sent to the target site.
This pre-flight request is sent via the OPTIONS HTTP Request method.
Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site.
After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser.
Whenever there is a need to share the resources to a third party site, the site should be specifically whitelisted with Access-Control-Allow-Origin : https://sitename.com instead of wildcards as a security best practice.
References : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Information-Security
Technical Scripter 2018
vulnerability
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Nov, 2018"
},
{
"code": null,
"e": 360,
"s": 54,
"text": "CORS (Cross-Origin Resource Sharing) is a mechanism by which data or any other resource of a site could be shared intentionally to a third party website when there is a need. Generally, access to resources that are residing in a third party site is restricted by the browser clients for security purposes."
},
{
"code": null,
"e": 421,
"s": 360,
"text": "Client side code to make an HTTP Call would look like below,"
},
{
"code": null,
"e": 595,
"s": 421,
"text": "function httpGetAction(urlLink)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.open( \"GET\", urlLink, false ); \n xmlHttp.send();\n return xmlHttp.responseText;\n}\n"
},
{
"code": null,
"e": 763,
"s": 595,
"text": "This native JavaScript method is intended to make an HTTP call to the given link urlLink via the GET method and return the response text from the third party resource."
},
{
"code": null,
"e": 968,
"s": 763,
"text": "By default, a request to non-parent domains (domains other than the domain from which you are making the call) is blocked by the browser. If you try to do so, the console would throw the following error.,"
},
{
"code": null,
"e": 1166,
"s": 968,
"text": "Failed to load https://contribute.geeksforgeeks.org/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.google.com' is therefore not allowed access.\n"
},
{
"code": null,
"e": 1421,
"s": 1166,
"text": "Of course, there are some cases where you need to access a third party website like getting a public image, making a non-state changing API Call or accessing other domain which you own yourself. There are some ways to achieve this, as and when necessary."
},
{
"code": null,
"e": 1702,
"s": 1421,
"text": "One could get an idea from the error message that the Access-Control-Allow-Origin Header is not present on the requested resource. It simply means that the target website whose resource you are trying to access haven’t specifically allowed you to get the resource from their site."
},
{
"code": null,
"e": 1828,
"s": 1702,
"text": "This could be done with an additional HTTP Header, Access-Control-Allow-Origin. This header could take the following values.,"
},
{
"code": null,
"e": 2333,
"s": 1828,
"text": "Access-Control-Allow-Origin : [origin]Example : Access-Control-Allow-Origin: https://contribute.geeksforgeeks.orgThis allows you to specifically allow one website to access your resource. In this case, https://contribute.geeksforgeeks.org can access your web resource, since it is explicitly allowed.This require an additional header called ORIGIN sent from the requesting client containing its hostname. This origin header is matched against the allowed origin and the access to the resource is decided."
},
{
"code": null,
"e": 2522,
"s": 2333,
"text": "Access-Control-Allow-Origin : *Example : Access-Control-Allow-Origin: *Wildcard character (*) means that any site can access the resource you have it in your site and obviously its unsafe."
},
{
"code": null,
"e": 2647,
"s": 2522,
"text": "Based on the request methods (GET/PUT/POST/DELETE) and the request headers, the requests are classified into two categories."
},
{
"code": null,
"e": 3790,
"s": 2647,
"text": "Simple RequestsNon Simple/Complex RequestsSimple RequestsFor Simple Requests, the CORS Works on the following way,Request is made to a third party site with ORIGIN Header.On the target site, the ORIGIN value is compared with the allowed origins.If the source is an allowed one, then the resource is granted access, else denied.Complex RequestsFor Complex Requests, the CORS Works on the following way,Before the actual request is sent, a pre-flight request is sent to the target site.This pre-flight request is sent via the OPTIONS HTTP Request method.Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site.After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser.Whenever there is a need to share the resources to a third party site, the site should be specifically whitelisted with Access-Control-Allow-Origin : https://sitename.com instead of wildcards as a security best practice.References : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORSMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 3806,
"s": 3790,
"text": "Simple Requests"
},
{
"code": null,
"e": 3834,
"s": 3806,
"text": "Non Simple/Complex Requests"
},
{
"code": null,
"e": 4935,
"s": 3834,
"text": "Simple RequestsFor Simple Requests, the CORS Works on the following way,Request is made to a third party site with ORIGIN Header.On the target site, the ORIGIN value is compared with the allowed origins.If the source is an allowed one, then the resource is granted access, else denied.Complex RequestsFor Complex Requests, the CORS Works on the following way,Before the actual request is sent, a pre-flight request is sent to the target site.This pre-flight request is sent via the OPTIONS HTTP Request method.Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site.After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser.Whenever there is a need to share the resources to a third party site, the site should be specifically whitelisted with Access-Control-Allow-Origin : https://sitename.com instead of wildcards as a security best practice.References : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORSMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5008,
"s": 4935,
"text": "Simple RequestsFor Simple Requests, the CORS Works on the following way,"
},
{
"code": null,
"e": 5222,
"s": 5008,
"text": "Request is made to a third party site with ORIGIN Header.On the target site, the ORIGIN value is compared with the allowed origins.If the source is an allowed one, then the resource is granted access, else denied."
},
{
"code": null,
"e": 5280,
"s": 5222,
"text": "Request is made to a third party site with ORIGIN Header."
},
{
"code": null,
"e": 5355,
"s": 5280,
"text": "On the target site, the ORIGIN value is compared with the allowed origins."
},
{
"code": null,
"e": 5438,
"s": 5355,
"text": "If the source is an allowed one, then the resource is granted access, else denied."
},
{
"code": null,
"e": 5513,
"s": 5438,
"text": "Complex RequestsFor Complex Requests, the CORS Works on the following way,"
},
{
"code": null,
"e": 5933,
"s": 5513,
"text": "Before the actual request is sent, a pre-flight request is sent to the target site.This pre-flight request is sent via the OPTIONS HTTP Request method.Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site.After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser."
},
{
"code": null,
"e": 6017,
"s": 5933,
"text": "Before the actual request is sent, a pre-flight request is sent to the target site."
},
{
"code": null,
"e": 6086,
"s": 6017,
"text": "This pre-flight request is sent via the OPTIONS HTTP Request method."
},
{
"code": null,
"e": 6202,
"s": 6086,
"text": "Response to the pre-flight request would contain the Allowed methods, Allowed origin details about the target site."
},
{
"code": null,
"e": 6356,
"s": 6202,
"text": "After deciding whether the target site could return the requested information based on this response, the actual GET/POST request is sent by the browser."
},
{
"code": null,
"e": 6577,
"s": 6356,
"text": "Whenever there is a need to share the resources to a third party site, the site should be specifically whitelisted with Access-Control-Allow-Origin : https://sitename.com instead of wildcards as a security best practice."
},
{
"code": null,
"e": 6645,
"s": 6577,
"text": "References : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"
},
{
"code": null,
"e": 6666,
"s": 6645,
"text": "Information-Security"
},
{
"code": null,
"e": 6690,
"s": 6666,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 6704,
"s": 6690,
"text": "vulnerability"
},
{
"code": null,
"e": 6723,
"s": 6704,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6740,
"s": 6723,
"text": "Web Technologies"
}
] |
How to allow access outside localhost in AngularJS ?
|
05 Jun, 2020
Firstly, let us discuss how we can build an Angular application, run it, and preview it in the browser. We can easily do using the CLI, provided by Angular. The CLI is a Command-line interface tool by using which, the developers face fewer challenges to initialize an application, develop it, scaffold, and maintain it efficiently. CLI is not always required to develop an application in Angular but definitely it gives the developer a high-quality toolset to make the code more impressive and saves time.
Highlights on CLI:
Creating a new Angular application.
Running a development server with LiveReload support to preview your application during development.
Adding different features to the existing Angular application.
Running application’s unit tests.
Running application’s end-to-end (E2E) tests.
Building application for deployment to production.
Let us build our first Angular application. Some prerequisites are as follows:
Node.js 6.9.0npm 3.0.0 or higher versions
Node.js 6.9.0
npm 3.0.0 or higher versions
Installation: To install Angular CLI, run the following in the command prompt, this will install ng in your system.
$ npm install -g @angular/cli
To check the version we will write the following command-
$ ng version
This will give the version you have installed.
@angular/cli: 1.0.0
node: 6.10.0
os: darwin x64
Creation of a new application: To build, and serve a new Angular project on a development server, go to the parent directory of your new workspace and use the following commands:
$ ng new my-first-Angular-application
This ng new command will create a new folder under the current working directory, all the source files and the directories for your new Angular application are created based on the name you specified “my-first-Angular-application”. The npm dependencies are installed. Note that all the files that you want to create, you will be able to create them inside the folder. If the current working directory is not the right place for your project, you can change it to another directory by running cd.
To preview your new application in your browser, navigate to its directory:
$ cd my-first-Angular-application
and run:
$ ng serve
In your browser, open http://localhost:4200/ to see the result of my-first-Angular-application. When you use the ng serve command to build an app and serve it locally, the server automatically rebuilds the app and it reloads the page when you change any of the source files. Creating, building, and running your Angular application is as simple as that.
Now the main question arises, why we need to allow access the localhost from outside?The answer is Often we as developers use more than one device or computer to run our application with respect to our needs. It will make our work efficient and also we can save a lot of time. To allow the access of localhost from outside there is a simple modification to the ng serve comment which we have seen earlier.
$ ng serve --host 0.0.0.0
Then type 192.168.x.x:4200 to get access from another machine. x.x stands for the last two dotted decimal digits from your IP address. Else you can simply type-
$ ng serve --host 192.168.X.X
If you are still not able to access 192.168.X.X:4200, you may be in a network where firewall protection is ON. Disable the protection and check again.
Angular CLI | Angular Project Setup
AngularJS-Misc
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 560,
"s": 54,
"text": "Firstly, let us discuss how we can build an Angular application, run it, and preview it in the browser. We can easily do using the CLI, provided by Angular. The CLI is a Command-line interface tool by using which, the developers face fewer challenges to initialize an application, develop it, scaffold, and maintain it efficiently. CLI is not always required to develop an application in Angular but definitely it gives the developer a high-quality toolset to make the code more impressive and saves time."
},
{
"code": null,
"e": 579,
"s": 560,
"text": "Highlights on CLI:"
},
{
"code": null,
"e": 615,
"s": 579,
"text": "Creating a new Angular application."
},
{
"code": null,
"e": 716,
"s": 615,
"text": "Running a development server with LiveReload support to preview your application during development."
},
{
"code": null,
"e": 779,
"s": 716,
"text": "Adding different features to the existing Angular application."
},
{
"code": null,
"e": 813,
"s": 779,
"text": "Running application’s unit tests."
},
{
"code": null,
"e": 859,
"s": 813,
"text": "Running application’s end-to-end (E2E) tests."
},
{
"code": null,
"e": 910,
"s": 859,
"text": "Building application for deployment to production."
},
{
"code": null,
"e": 989,
"s": 910,
"text": "Let us build our first Angular application. Some prerequisites are as follows:"
},
{
"code": null,
"e": 1031,
"s": 989,
"text": "Node.js 6.9.0npm 3.0.0 or higher versions"
},
{
"code": null,
"e": 1045,
"s": 1031,
"text": "Node.js 6.9.0"
},
{
"code": null,
"e": 1074,
"s": 1045,
"text": "npm 3.0.0 or higher versions"
},
{
"code": null,
"e": 1190,
"s": 1074,
"text": "Installation: To install Angular CLI, run the following in the command prompt, this will install ng in your system."
},
{
"code": null,
"e": 1221,
"s": 1190,
"text": "$ npm install -g @angular/cli "
},
{
"code": null,
"e": 1279,
"s": 1221,
"text": "To check the version we will write the following command-"
},
{
"code": null,
"e": 1293,
"s": 1279,
"text": "$ ng version "
},
{
"code": null,
"e": 1340,
"s": 1293,
"text": "This will give the version you have installed."
},
{
"code": null,
"e": 1388,
"s": 1340,
"text": "@angular/cli: 1.0.0\nnode: 6.10.0\nos: darwin x64"
},
{
"code": null,
"e": 1567,
"s": 1388,
"text": "Creation of a new application: To build, and serve a new Angular project on a development server, go to the parent directory of your new workspace and use the following commands:"
},
{
"code": null,
"e": 1606,
"s": 1567,
"text": "$ ng new my-first-Angular-application "
},
{
"code": null,
"e": 2102,
"s": 1606,
"text": "This ng new command will create a new folder under the current working directory, all the source files and the directories for your new Angular application are created based on the name you specified “my-first-Angular-application”. The npm dependencies are installed. Note that all the files that you want to create, you will be able to create them inside the folder. If the current working directory is not the right place for your project, you can change it to another directory by running cd."
},
{
"code": null,
"e": 2178,
"s": 2102,
"text": "To preview your new application in your browser, navigate to its directory:"
},
{
"code": null,
"e": 2212,
"s": 2178,
"text": "$ cd my-first-Angular-application"
},
{
"code": null,
"e": 2221,
"s": 2212,
"text": "and run:"
},
{
"code": null,
"e": 2232,
"s": 2221,
"text": "$ ng serve"
},
{
"code": null,
"e": 2586,
"s": 2232,
"text": "In your browser, open http://localhost:4200/ to see the result of my-first-Angular-application. When you use the ng serve command to build an app and serve it locally, the server automatically rebuilds the app and it reloads the page when you change any of the source files. Creating, building, and running your Angular application is as simple as that."
},
{
"code": null,
"e": 2992,
"s": 2586,
"text": "Now the main question arises, why we need to allow access the localhost from outside?The answer is Often we as developers use more than one device or computer to run our application with respect to our needs. It will make our work efficient and also we can save a lot of time. To allow the access of localhost from outside there is a simple modification to the ng serve comment which we have seen earlier."
},
{
"code": null,
"e": 3018,
"s": 2992,
"text": "$ ng serve --host 0.0.0.0"
},
{
"code": null,
"e": 3179,
"s": 3018,
"text": "Then type 192.168.x.x:4200 to get access from another machine. x.x stands for the last two dotted decimal digits from your IP address. Else you can simply type-"
},
{
"code": null,
"e": 3209,
"s": 3179,
"text": "$ ng serve --host 192.168.X.X"
},
{
"code": null,
"e": 3360,
"s": 3209,
"text": "If you are still not able to access 192.168.X.X:4200, you may be in a network where firewall protection is ON. Disable the protection and check again."
},
{
"code": null,
"e": 3396,
"s": 3360,
"text": "Angular CLI | Angular Project Setup"
},
{
"code": null,
"e": 3411,
"s": 3396,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3421,
"s": 3411,
"text": "AngularJS"
},
{
"code": null,
"e": 3438,
"s": 3421,
"text": "Web Technologies"
},
{
"code": null,
"e": 3465,
"s": 3438,
"text": "Web technologies Questions"
}
] |
Self Referential Structures
|
03 Nov, 2021
Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in nature.Example:
CPP
Python3
struct node { int data1; char data2; struct node* link;}; int main(){ struct node ob; return 0;}
class node: def __init__(self): self.data1=0 self.data2='' self.link=None if __name__ == '__main__': ob=node()
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer. An important point to consider is that the pointer should be initialized properly before accessing, as by default it contains garbage value.Types of Self Referential Structures
Self Referential Structure with Single LinkSelf Referential Structure with Multiple Links
Self Referential Structure with Single Link
Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one self-pointer as their member. The following example will show us how to connect the objects of a self-referential structure with the single link and access the corresponding data members. The connection formed is shown in the following figure.
CPP
Python3
#include <stdio.h> struct node { int data1; char data2; struct node* link;}; int main(){ struct node ob1; // Node1 // Initialization ob1.link = NULL; ob1.data1 = 10; ob1.data2 = 20; struct node ob2; // Node2 // Initialization ob2.link = NULL; ob2.data1 = 30; ob2.data2 = 40; // Linking ob1 and ob2 ob1.link = &ob2; // Accessing data members of ob2 using ob1 printf("%d", ob1.link->data1); printf("\n%d", ob1.link->data2); return 0;}
class node: def __init__(self): self.data1=0 self.data2=0 self.link=None if __name__ == '__main__': ob1=node() # Node1 # Initialization ob1.link = None ob1.data1 = 10 ob1.data2 = 20 ob2=node() # Node2 # Initialization ob2.link = None ob2.data1 = 30 ob2.data2 = 40 # Linking ob1 and ob2 ob1.link = ob2 # Accessing data members of ob2 using ob1 print(ob1.link.data1) print(ob1.link.data2)
30
40
Self Referential Structure with Multiple Links: Self referential structures with multiple links can have more than one self-pointers. Many complicated data structures can be easily constructed using these structures. Such structures can easily connect to more than one nodes at a time. The following example shows one such structure with more than one links.The connections made in the above example can be understood using the following figure.
CPP
Python3
#include <stdio.h> struct node { int data; struct node* prev_link; struct node* next_link;}; int main(){ struct node ob1; // Node1 // Initialization ob1.prev_link = NULL; ob1.next_link = NULL; ob1.data = 10; struct node ob2; // Node2 // Initialization ob2.prev_link = NULL; ob2.next_link = NULL; ob2.data = 20; struct node ob3; // Node3 // Initialization ob3.prev_link = NULL; ob3.next_link = NULL; ob3.data = 30; // Forward links ob1.next_link = &ob2; ob2.next_link = &ob3; // Backward links ob2.prev_link = &ob1; ob3.prev_link = &ob2; // Accessing data of ob1, ob2 and ob3 by ob1 printf("%d\t", ob1.data); printf("%d\t", ob1.next_link->data); printf("%d\n", ob1.next_link->next_link->data); // Accessing data of ob1, ob2 and ob3 by ob2 printf("%d\t", ob2.prev_link->data); printf("%d\t", ob2.data); printf("%d\n", ob2.next_link->data); // Accessing data of ob1, ob2 and ob3 by ob3 printf("%d\t", ob3.prev_link->prev_link->data); printf("%d\t", ob3.prev_link->data); printf("%d", ob3.data); return 0;}
class node: def __init__(self): self.data=0 self.prev_link=None self.next_link=None if __name__ == '__main__': ob1=node() #Node1 # Initialization ob1.prev_link = None ob1.next_link = None ob1.data = 10 ob2=node() #Node2 # Initialization ob2.prev_link = None ob2.next_link = None ob2.data = 20 ob3=node() # Node3 # Initialization ob3.prev_link = None ob3.next_link = None ob3.data = 30 # Forward links ob1.next_link = ob2 ob2.next_link = ob3 # Backward links ob2.prev_link = ob1 ob3.prev_link = ob2 # Accessing data of ob1, ob2 and ob3 by ob1 print(ob1.data,end='\t') print(ob1.next_link.data,end='\t') print(ob1.next_link.next_link.data) # Accessing data of ob1, ob2 and ob3 by ob2 print(ob2.prev_link.data,end='\t') print(ob2.data,end='\t') print(ob2.next_link.data) # Accessing data of ob1, ob2 and ob3 by ob3 print(ob3.prev_link.prev_link.data,end='\t') print(ob3.prev_link.data,end='\t') print(ob3.data)
10 20 30
10 20 30
10 20 30
In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self referential structure ‘node’. And they are connected using their links in such a way that any of them can easily access each other’s data. This is the beauty of the self referential structures. The connections can be manipulated according to the requirements of the programmer.Applications: Self referential structures are very useful in creation of other complex data structures like:
Linked Lists
Stacks
Queues
Trees
Graphs etc
shubham_singh
amartyaghoshgfg
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
TCS NQT Coding Sheet
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
What Should I Learn First: Data Structures or Algorithms?
Program to implement Singly Linked List in C++ using class
Hash Functions and list/types of Hash functions
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 195,
"s": 54,
"text": "Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member. "
},
{
"code": null,
"e": 304,
"s": 195,
"text": "In other words, structures pointing to the same type of structures are self-referential in nature.Example: "
},
{
"code": null,
"e": 308,
"s": 304,
"text": "CPP"
},
{
"code": null,
"e": 316,
"s": 308,
"text": "Python3"
},
{
"code": "struct node { int data1; char data2; struct node* link;}; int main(){ struct node ob; return 0;}",
"e": 428,
"s": 316,
"text": null
},
{
"code": "class node: def __init__(self): self.data1=0 self.data2='' self.link=None if __name__ == '__main__': ob=node()",
"e": 566,
"s": 428,
"text": null
},
{
"code": null,
"e": 917,
"s": 566,
"text": "In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer. An important point to consider is that the pointer should be initialized properly before accessing, as by default it contains garbage value.Types of Self Referential Structures "
},
{
"code": null,
"e": 1007,
"s": 917,
"text": "Self Referential Structure with Single LinkSelf Referential Structure with Multiple Links"
},
{
"code": null,
"e": 1051,
"s": 1007,
"text": "Self Referential Structure with Single Link"
},
{
"code": null,
"e": 1098,
"s": 1051,
"text": "Self Referential Structure with Multiple Links"
},
{
"code": null,
"e": 1424,
"s": 1098,
"text": "Self Referential Structure with Single Link: These structures can have only one self-pointer as their member. The following example will show us how to connect the objects of a self-referential structure with the single link and access the corresponding data members. The connection formed is shown in the following figure. "
},
{
"code": null,
"e": 1430,
"s": 1426,
"text": "CPP"
},
{
"code": null,
"e": 1438,
"s": 1430,
"text": "Python3"
},
{
"code": "#include <stdio.h> struct node { int data1; char data2; struct node* link;}; int main(){ struct node ob1; // Node1 // Initialization ob1.link = NULL; ob1.data1 = 10; ob1.data2 = 20; struct node ob2; // Node2 // Initialization ob2.link = NULL; ob2.data1 = 30; ob2.data2 = 40; // Linking ob1 and ob2 ob1.link = &ob2; // Accessing data members of ob2 using ob1 printf(\"%d\", ob1.link->data1); printf(\"\\n%d\", ob1.link->data2); return 0;}",
"e": 1934,
"s": 1438,
"text": null
},
{
"code": "class node: def __init__(self): self.data1=0 self.data2=0 self.link=None if __name__ == '__main__': ob1=node() # Node1 # Initialization ob1.link = None ob1.data1 = 10 ob1.data2 = 20 ob2=node() # Node2 # Initialization ob2.link = None ob2.data1 = 30 ob2.data2 = 40 # Linking ob1 and ob2 ob1.link = ob2 # Accessing data members of ob2 using ob1 print(ob1.link.data1) print(ob1.link.data2)",
"e": 2396,
"s": 1934,
"text": null
},
{
"code": null,
"e": 2402,
"s": 2396,
"text": "30\n40"
},
{
"code": null,
"e": 2852,
"s": 2404,
"text": "Self Referential Structure with Multiple Links: Self referential structures with multiple links can have more than one self-pointers. Many complicated data structures can be easily constructed using these structures. Such structures can easily connect to more than one nodes at a time. The following example shows one such structure with more than one links.The connections made in the above example can be understood using the following figure. "
},
{
"code": null,
"e": 2858,
"s": 2854,
"text": "CPP"
},
{
"code": null,
"e": 2866,
"s": 2858,
"text": "Python3"
},
{
"code": "#include <stdio.h> struct node { int data; struct node* prev_link; struct node* next_link;}; int main(){ struct node ob1; // Node1 // Initialization ob1.prev_link = NULL; ob1.next_link = NULL; ob1.data = 10; struct node ob2; // Node2 // Initialization ob2.prev_link = NULL; ob2.next_link = NULL; ob2.data = 20; struct node ob3; // Node3 // Initialization ob3.prev_link = NULL; ob3.next_link = NULL; ob3.data = 30; // Forward links ob1.next_link = &ob2; ob2.next_link = &ob3; // Backward links ob2.prev_link = &ob1; ob3.prev_link = &ob2; // Accessing data of ob1, ob2 and ob3 by ob1 printf(\"%d\\t\", ob1.data); printf(\"%d\\t\", ob1.next_link->data); printf(\"%d\\n\", ob1.next_link->next_link->data); // Accessing data of ob1, ob2 and ob3 by ob2 printf(\"%d\\t\", ob2.prev_link->data); printf(\"%d\\t\", ob2.data); printf(\"%d\\n\", ob2.next_link->data); // Accessing data of ob1, ob2 and ob3 by ob3 printf(\"%d\\t\", ob3.prev_link->prev_link->data); printf(\"%d\\t\", ob3.prev_link->data); printf(\"%d\", ob3.data); return 0;}",
"e": 3991,
"s": 2866,
"text": null
},
{
"code": "class node: def __init__(self): self.data=0 self.prev_link=None self.next_link=None if __name__ == '__main__': ob1=node() #Node1 # Initialization ob1.prev_link = None ob1.next_link = None ob1.data = 10 ob2=node() #Node2 # Initialization ob2.prev_link = None ob2.next_link = None ob2.data = 20 ob3=node() # Node3 # Initialization ob3.prev_link = None ob3.next_link = None ob3.data = 30 # Forward links ob1.next_link = ob2 ob2.next_link = ob3 # Backward links ob2.prev_link = ob1 ob3.prev_link = ob2 # Accessing data of ob1, ob2 and ob3 by ob1 print(ob1.data,end='\\t') print(ob1.next_link.data,end='\\t') print(ob1.next_link.next_link.data) # Accessing data of ob1, ob2 and ob3 by ob2 print(ob2.prev_link.data,end='\\t') print(ob2.data,end='\\t') print(ob2.next_link.data) # Accessing data of ob1, ob2 and ob3 by ob3 print(ob3.prev_link.prev_link.data,end='\\t') print(ob3.prev_link.data,end='\\t') print(ob3.data)",
"e": 5033,
"s": 3991,
"text": null
},
{
"code": null,
"e": 5078,
"s": 5033,
"text": "10 20 30\n10 20 30\n10 20 30"
},
{
"code": null,
"e": 5558,
"s": 5080,
"text": "In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self referential structure ‘node’. And they are connected using their links in such a way that any of them can easily access each other’s data. This is the beauty of the self referential structures. The connections can be manipulated according to the requirements of the programmer.Applications: Self referential structures are very useful in creation of other complex data structures like: "
},
{
"code": null,
"e": 5571,
"s": 5558,
"text": "Linked Lists"
},
{
"code": null,
"e": 5578,
"s": 5571,
"text": "Stacks"
},
{
"code": null,
"e": 5585,
"s": 5578,
"text": "Queues"
},
{
"code": null,
"e": 5591,
"s": 5585,
"text": "Trees"
},
{
"code": null,
"e": 5602,
"s": 5591,
"text": "Graphs etc"
},
{
"code": null,
"e": 5618,
"s": 5604,
"text": "shubham_singh"
},
{
"code": null,
"e": 5634,
"s": 5618,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 5650,
"s": 5634,
"text": "Data Structures"
},
{
"code": null,
"e": 5666,
"s": 5650,
"text": "Data Structures"
},
{
"code": null,
"e": 5764,
"s": 5666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5802,
"s": 5764,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 5870,
"s": 5802,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 5902,
"s": 5870,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5966,
"s": 5902,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 5987,
"s": 5966,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 6014,
"s": 5987,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 6057,
"s": 6014,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 6115,
"s": 6057,
"text": "What Should I Learn First: Data Structures or Algorithms?"
},
{
"code": null,
"e": 6174,
"s": 6115,
"text": "Program to implement Singly Linked List in C++ using class"
}
] |
Create a Donut Chart using Recharts in ReactJS
|
27 Jul, 2021
Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).
To create Donut Chart using Recharts, we create a dataset that contains actual data. Then we define the slices using donaut element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import { PieChart, Pie} from 'recharts'; const App = () => { // Sample dataconst data = [ {name: 'Geeksforgeeks', students: 400}, {name: 'Technical scripter', students: 700}, {name: 'Geek-i-knack', students: 200}, {name: 'Geek-o-mania', students: 1000}]; return ( <PieChart width={700} height={700}> <Pie data={data} dataKey="students" outerRadius={250} innerRadius={150} fill="green" /> </PieChart>);} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Output
React-Questions
Recharts
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components
How to pass data from one component to other component in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jul, 2021"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). "
},
{
"code": null,
"e": 527,
"s": 246,
"text": "To create Donut Chart using Recharts, we create a dataset that contains actual data. Then we define the slices using donaut element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices."
},
{
"code": null,
"e": 577,
"s": 527,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 672,
"s": 577,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername"
},
{
"code": null,
"e": 736,
"s": 672,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 768,
"s": 736,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 881,
"s": 768,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 981,
"s": 881,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 995,
"s": 981,
"text": "cd foldername"
},
{
"code": null,
"e": 1128,
"s": 995,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts"
},
{
"code": null,
"e": 1234,
"s": 1128,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command."
},
{
"code": null,
"e": 1262,
"s": 1234,
"text": "npm install --save recharts"
},
{
"code": null,
"e": 1314,
"s": 1262,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1444,
"s": 1314,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1451,
"s": 1444,
"text": "App.js"
},
{
"code": "import React from 'react';import { PieChart, Pie} from 'recharts'; const App = () => { // Sample dataconst data = [ {name: 'Geeksforgeeks', students: 400}, {name: 'Technical scripter', students: 700}, {name: 'Geek-i-knack', students: 200}, {name: 'Geek-o-mania', students: 1000}]; return ( <PieChart width={700} height={700}> <Pie data={data} dataKey=\"students\" outerRadius={250} innerRadius={150} fill=\"green\" /> </PieChart>);} export default App;",
"e": 1935,
"s": 1451,
"text": null
},
{
"code": null,
"e": 2048,
"s": 1935,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2058,
"s": 2048,
"text": "npm start"
},
{
"code": null,
"e": 2157,
"s": 2058,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2164,
"s": 2157,
"text": "Output"
},
{
"code": null,
"e": 2180,
"s": 2164,
"text": "React-Questions"
},
{
"code": null,
"e": 2189,
"s": 2180,
"text": "Recharts"
},
{
"code": null,
"e": 2200,
"s": 2189,
"text": "JavaScript"
},
{
"code": null,
"e": 2208,
"s": 2200,
"text": "ReactJS"
},
{
"code": null,
"e": 2225,
"s": 2208,
"text": "Web Technologies"
},
{
"code": null,
"e": 2323,
"s": 2225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2384,
"s": 2323,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2424,
"s": 2384,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2466,
"s": 2424,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2507,
"s": 2466,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2529,
"s": 2507,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2572,
"s": 2529,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2610,
"s": 2572,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2655,
"s": 2610,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 2685,
"s": 2655,
"text": "ReactJS Functional Components"
}
] |
Difference between Static binding and dynamic binding in Java
|
Binding is a mechanism creating link between method call and method actual implementation. As per the polymorphism concept in Java , object can have many different forms. Object forms can be resolved at compile time and run time. If linking between method call and method implementation is resolved at compile time then we call it static binding or If it is resolved at run time then it dynamic binding. Dynamic binding uses object to resolve binding but static binding use type of the class and fields.
1
Basic
It is resolved at compile time
It is resolved at run time
2
Resolve mechanism
static binding use type of the class and fields
Dynamic binding uses object to resolve binding
3
Example
Overloading is an example of static binding
Method overriding is the example of Dynamic binding
4.
Type of Methods
private, final and static methods and variables uses static binding
Virtual methods use dynamic binding
public class FastFood {
public void create() {
System.out.println("Creating in FastFood class");
}
}
public class Pizza extends FastFood {
public void create() {
System.out.println("Creating in Pizza class");
}
}
public class Main {
public static void main(String[] args) {
FastFood fastFood= new FastFood();
fastFood.create();
//Dynamic binding
FastFood pza= new Pizza();
pza.create();
}
}
|
[
{
"code": null,
"e": 1569,
"s": 1062,
"text": "Binding is a mechanism creating link between method call and method actual implementation. As per the polymorphism concept in Java , object can have many different forms. Object forms can be resolved at compile time and run time. If linking between method call and method implementation is resolved at compile time then we call it static binding or If it is resolved at run time then it dynamic binding. Dynamic binding uses object to resolve binding but static binding use type of the class and fields. "
},
{
"code": null,
"e": 1571,
"s": 1569,
"text": "1"
},
{
"code": null,
"e": 1578,
"s": 1571,
"text": "Basic "
},
{
"code": null,
"e": 1610,
"s": 1578,
"text": "It is resolved at compile time "
},
{
"code": null,
"e": 1638,
"s": 1610,
"text": "It is resolved at run time "
},
{
"code": null,
"e": 1640,
"s": 1638,
"text": "2"
},
{
"code": null,
"e": 1667,
"s": 1640,
"text": " Resolve mechanism "
},
{
"code": null,
"e": 1716,
"s": 1667,
"text": " static binding use type of the class and fields"
},
{
"code": null,
"e": 1764,
"s": 1716,
"text": "Dynamic binding uses object to resolve binding "
},
{
"code": null,
"e": 1766,
"s": 1764,
"text": "3"
},
{
"code": null,
"e": 1775,
"s": 1766,
"text": "Example "
},
{
"code": null,
"e": 1820,
"s": 1775,
"text": "Overloading is an example of static binding "
},
{
"code": null,
"e": 1873,
"s": 1820,
"text": "Method overriding is the example of Dynamic binding "
},
{
"code": null,
"e": 1876,
"s": 1873,
"text": "4."
},
{
"code": null,
"e": 1893,
"s": 1876,
"text": "Type of Methods "
},
{
"code": null,
"e": 1961,
"s": 1893,
"text": "private, final and static methods and variables uses static binding"
},
{
"code": null,
"e": 1998,
"s": 1961,
"text": "Virtual methods use dynamic binding "
},
{
"code": null,
"e": 2449,
"s": 1998,
"text": "public class FastFood {\n public void create() {\n System.out.println(\"Creating in FastFood class\");\n }\n}\npublic class Pizza extends FastFood {\n public void create() {\n System.out.println(\"Creating in Pizza class\");\n }\n}\npublic class Main {\n public static void main(String[] args) {\n FastFood fastFood= new FastFood();\n fastFood.create();\n //Dynamic binding\n FastFood pza= new Pizza();\n pza.create();\n }\n}"
}
] |
SQL INSERT INTO Statement
|
The INSERT INTO statement is used to insert new records in a table.
It is possible to write the INSERT INTO
statement in two ways:
1. Specify both the column names and the values to be inserted:
2. If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query. However, make sure the order of the
values is in the same order as the columns in the table. Here, the
INSERT INTO syntax
would be as follows:
Below is a selection from the "Customers" table in the Northwind
sample database:
The following SQL statement inserts a new record in the "Customers" table:
The selection from the "Customers" table will now look like this:
Did you notice that we did not insert any number into the CustomerID
field?The CustomerID column is
an auto-increment field and will be
generated automatically when a new record is inserted into the table.
It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record, but only insert data in the "CustomerName",
"City", and "Country" columns (CustomerID will
be updated automatically):
The selection from the "Customers" table will now look like this:
Insert a new record in the Customers table.
Customers
CustomerName,
Address,
City,
PostalCode,
Country
'Hekkan Burger',
'Gateveien 15',
'Sandnes',
'4306',
'Norway';
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 68,
"s": 0,
"text": "The INSERT INTO statement is used to insert new records in a table."
},
{
"code": null,
"e": 132,
"s": 68,
"text": "It is possible to write the INSERT INTO \nstatement in two ways:"
},
{
"code": null,
"e": 196,
"s": 132,
"text": "1. Specify both the column names and the values to be inserted:"
},
{
"code": null,
"e": 467,
"s": 196,
"text": "2. If you are adding values for all the columns of the table, you do not need to \nspecify the column names in the SQL query. However, make sure the order of the \nvalues is in the same order as the columns in the table. Here, the \nINSERT INTO syntax \nwould be as follows:"
},
{
"code": null,
"e": 550,
"s": 467,
"text": "Below is a selection from the \"Customers\" table in the Northwind \nsample database:"
},
{
"code": null,
"e": 625,
"s": 550,
"text": "The following SQL statement inserts a new record in the \"Customers\" table:"
},
{
"code": null,
"e": 691,
"s": 625,
"text": "The selection from the \"Customers\" table will now look like this:"
},
{
"code": null,
"e": 900,
"s": 691,
"text": "Did you notice that we did not insert any number into the CustomerID \nfield?The CustomerID column is \nan auto-increment field and will be \ngenerated automatically when a new record is inserted into the table."
},
{
"code": null,
"e": 961,
"s": 900,
"text": "It is also possible to only insert data in specific columns."
},
{
"code": null,
"e": 1135,
"s": 961,
"text": "The following SQL statement will insert a new record, but only insert data in the \"CustomerName\", \n\"City\", and \"Country\" columns (CustomerID will \nbe updated automatically):"
},
{
"code": null,
"e": 1201,
"s": 1135,
"text": "The selection from the \"Customers\" table will now look like this:"
},
{
"code": null,
"e": 1245,
"s": 1201,
"text": "Insert a new record in the Customers table."
},
{
"code": null,
"e": 1374,
"s": 1245,
"text": " Customers \nCustomerName, \nAddress, \nCity, \nPostalCode,\nCountry\n \n'Hekkan Burger',\n'Gateveien 15',\n'Sandnes',\n'4306',\n'Norway';\n"
},
{
"code": null,
"e": 1393,
"s": 1374,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1426,
"s": 1393,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1468,
"s": 1426,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1575,
"s": 1468,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1594,
"s": 1575,
"text": "[email protected]"
}
] |
How to use an animated image in HTML page?
|
Animated images in HTML are an image on a web page that moves. It is in GIF format i.e. Graphics Interchange Format file.
To add an animated image in HTML is quite easy. You need to use the <image> tag with the src attribute. The src attribute adds the URL of the image.
Also, set the height and width of the image using the height and width attribute.
You can try to run the following to work with the animated image in HTML −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Animated Image</title>
</head>
<body>
<h1>Animated Image</h1>
<img src="https://media.giphy.com/media/3o6UBpHgaXFDNAuttm/giphy.gif">
</body>
</html>
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "Animated images in HTML are an image on a web page that moves. It is in GIF format i.e. Graphics Interchange Format file."
},
{
"code": null,
"e": 1333,
"s": 1184,
"text": "To add an animated image in HTML is quite easy. You need to use the <image> tag with the src attribute. The src attribute adds the URL of the image."
},
{
"code": null,
"e": 1415,
"s": 1333,
"text": "Also, set the height and width of the image using the height and width attribute."
},
{
"code": null,
"e": 1490,
"s": 1415,
"text": "You can try to run the following to work with the animated image in HTML −"
},
{
"code": null,
"e": 1500,
"s": 1490,
"text": "Live Demo"
},
{
"code": null,
"e": 1716,
"s": 1500,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Animated Image</title>\n </head>\n <body>\n <h1>Animated Image</h1>\n <img src=\"https://media.giphy.com/media/3o6UBpHgaXFDNAuttm/giphy.gif\">\n </body>\n</html>"
}
] |
How can I change the text color with jQuery?
|
To change the text color with jQuery, use the jQuery css() method. The color css property is used to change text color.
You can try to run the following code to learn how to change text color with jQuery −
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("color", "red");
}
});
});
</script>
</head>
<body>
<p>Move the mouse pointer on the text to change the text color.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "To change the text color with jQuery, use the jQuery css() method. The color css property is used to change text color."
},
{
"code": null,
"e": 1268,
"s": 1182,
"text": "You can try to run the following code to learn how to change text color with jQuery −"
},
{
"code": null,
"e": 1278,
"s": 1268,
"text": "Live Demo"
},
{
"code": null,
"e": 1660,
"s": 1278,
"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(\"color\", \"red\");\n }\n }); \n});\n</script>\n</head>\n<body>\n<p>Move the mouse pointer on the text to change the text color.</p>\n</body>\n</html>"
}
] |
Dorkify - Perform Google Dork Search - GeeksforGeeks
|
28 Nov, 2021
Dorkify is a free and open-source tool available on GitHub. Dorkify is used to perform google Dorking from the Linux terminal. Google Dorking is a technique used by hackers to find security loopholes in websites and servers. Google Dorking can be performed using mathematical operators such as ? ,” ” etc. Google search engine uses different strings to specify which query is user searching for. Dorkify helps to perform google Dorking easily by using the kali Linux command line(Terminal).
Step 1: Open your kali Linux operating system and use the following command to install the tool. Use the second command to move into the directory of the tool.
git clone https://github.com/hhhrrrttt222111/Dorkify.git
cd Dorkify
Step 2: Use the following command to install the requirements of the tool.
python3 -m pip install -r requirements.txt
Step 3: Use the following command to run the tool.
python3 dorkify.py --help
The tool has been downloaded and installed successfully. Now we will see examples to use the tool.
choose option 1 "google"
The tool has started performing google search Dorking.
choose option 2
Now choose option 2.
The tool has started searching on specific URL google dork. The tool is free and open source. This is one of the most famous tools used for google dorking.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
Thread functions in C/C++
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
Named Pipe or FIFO with example C program
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 24898,
"s": 24406,
"text": "Dorkify is a free and open-source tool available on GitHub. Dorkify is used to perform google Dorking from the Linux terminal. Google Dorking is a technique used by hackers to find security loopholes in websites and servers. Google Dorking can be performed using mathematical operators such as ? ,” ” etc. Google search engine uses different strings to specify which query is user searching for. Dorkify helps to perform google Dorking easily by using the kali Linux command line(Terminal)."
},
{
"code": null,
"e": 25058,
"s": 24898,
"text": "Step 1: Open your kali Linux operating system and use the following command to install the tool. Use the second command to move into the directory of the tool."
},
{
"code": null,
"e": 25126,
"s": 25058,
"text": "git clone https://github.com/hhhrrrttt222111/Dorkify.git\ncd Dorkify"
},
{
"code": null,
"e": 25201,
"s": 25126,
"text": "Step 2: Use the following command to install the requirements of the tool."
},
{
"code": null,
"e": 25244,
"s": 25201,
"text": "python3 -m pip install -r requirements.txt"
},
{
"code": null,
"e": 25295,
"s": 25244,
"text": "Step 3: Use the following command to run the tool."
},
{
"code": null,
"e": 25321,
"s": 25295,
"text": "python3 dorkify.py --help"
},
{
"code": null,
"e": 25420,
"s": 25321,
"text": "The tool has been downloaded and installed successfully. Now we will see examples to use the tool."
},
{
"code": null,
"e": 25445,
"s": 25420,
"text": "choose option 1 \"google\""
},
{
"code": null,
"e": 25500,
"s": 25445,
"text": "The tool has started performing google search Dorking."
},
{
"code": null,
"e": 25516,
"s": 25500,
"text": "choose option 2"
},
{
"code": null,
"e": 25537,
"s": 25516,
"text": "Now choose option 2."
},
{
"code": null,
"e": 25693,
"s": 25537,
"text": "The tool has started searching on specific URL google dork. The tool is free and open source. This is one of the most famous tools used for google dorking."
},
{
"code": null,
"e": 25704,
"s": 25693,
"text": "Kali-Linux"
},
{
"code": null,
"e": 25716,
"s": 25704,
"text": "Linux-Tools"
},
{
"code": null,
"e": 25727,
"s": 25716,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25825,
"s": 25727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25862,
"s": 25825,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25888,
"s": 25862,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25923,
"s": 25888,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 25957,
"s": 25923,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25994,
"s": 25957,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26023,
"s": 25994,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26049,
"s": 26023,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26089,
"s": 26049,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26124,
"s": 26089,
"text": "Basic Operators in Shell Scripting"
}
] |
Andrew Ng’s Machine Learning Course in Python (Regularized Logistic Regression) + Lasso Regression | by Benjamin Lau | Towards Data Science
|
Continuing from programming assignment 2 (Logistic Regression), we will now proceed to regularized logistic regression in python to help us deal with the problem of overfitting.
Regularizations are shrinkage methods that shrink coefficient towards zero to prevent overfitting by reducing the variance of the model.
Going straight into the assignment, we start by importing all relevant libraries and dataset. This time, the dataset contains two tests result of microchips in a factory and we are going to use the test results to predict whether the microchips should be accepted or rejected.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltdf=pd.read_csv("ex2data2.txt", header=None)df.head()df.describe()
As you can see, it is a multivariate, binary classification problem that we can solve using logistic regression.
Now to visual the data. As with the previous logistic regression visualization, each combination of x1 and x2 that leads to accepted microchips are plotted against combinations that result in a rejection
X=df.iloc[:,:-1].valuesy=df.iloc[:,-1].valuespos , neg = (y==1).reshape(118,1) , (y==0).reshape(118,1)plt.scatter(X[pos[:,0],0],X[pos[:,0],1],c="r",marker="+")plt.scatter(X[neg[:,0],0],X[neg[:,0],1],marker="o",s=10)plt.xlabel("Test 1")plt.ylabel("Test 2")plt.legend(["Accepted","Rejected"],loc=0)
Plotting the data clearly shows that the decision boundary that separates the different classes is a non-linear one. This lead to the next step of feature mapping, where we add additional polynomial terms to try and better fit the data (Normal logistic regression can only to able to fit a linear decision boundary which will not do well in this case). It is decided in the assignment that we will add polynomial terms up to the 6th power.
def mapFeature(x1,x2,degree): """ take in numpy array of x1 and x2, return all polynomial terms up to the given degree """ out = np.ones(len(x1)).reshape(len(x1),1) for i in range(1,degree+1): for j in range(i+1): terms= (x1**(i-j) * x2**j).reshape(len(x1),1) out= np.hstack((out,terms)) return outX = mapFeature(X[:,0], X[:,1],6)
The mapFeature function also adds a column of ones to X so we do not have to deal with it later on. Here, I decided to use np.hstack instead of np.append to add a new column to the numpy array. I found np.hstack to be much neater in the code compared to np.append that I normally used. Here, I allow degree as a parameter instead of fixing it to 6 like how it was done in the assignment, feel free to play around with different degree and compare the result.
This diagram is useful to visualize what we are doing and the polynomial terms involved.
Next, we carry on to define a function that computes the regularize cost function and gradient. Remember that the cost function now has an additional shrinkage penalty that is controlled by λ.
def sigmoid(z): """ return the sigmoid of z """ return 1/ (1 + np.exp(-z))def costFunctionReg(theta, X, y ,Lambda): """ Take in numpy array of theta, X, and y to return the regularize cost function and gradient of a logistic regression """ m=len(y) y=y[:,np.newaxis] predictions = sigmoid(X @ theta) error = (-y * np.log(predictions)) - ((1-y)*np.log(1-predictions)) cost = 1/m * sum(error) regCost= cost + Lambda/(2*m) * sum(theta**2) # compute gradient j_0= 1/m * (X.transpose() @ (predictions - y))[0] j_1 = 1/m * (X.transpose() @ (predictions - y))[1:] + (Lambda/m)* theta[1:] grad= np.vstack((j_0[:,np.newaxis],j_1)) return regCost[0], grad
You can use the same costFunction code and add-on a λ term to compute the regularized cost function. Another improvement from my last python implementation, I found that replacing np.dot with @ is the preferred option for matrix multiplication according to the official numpy documentation. Writing @ is also much easier so I am cool with that. In case you are not familiar with numpy broadcasting, you can check it out here. Broadcasting is the reason I need to add a new axis to y using y=y[:,np.newaxis] ,to ensure that the linear algebra manipulation is as I expected. If you had noticed, I used reshape() in the previous implementation to deal with broadcasting (Told you guys I am learning as I go). By the way, np.vstack here add to a new row instead of a column for np.hstack .
# Initialize fitting parametersinitial_theta = np.zeros((X.shape[1], 1))# Set regularization parameter lambda to 1Lambda = 1#Compute and display initial cost and gradient for regularized logistic regressioncost, grad=costFunctionReg(initial_theta, X, y, Lambda)print("Cost at initial theta (zeros):",cost)
The print statement print: Cost at initial theta (zeros): 0.6931471805599461
As for the optimizing algorithm, I again make use of the standard gradient descent instead of fminunc . The python way of doing fminunc can be found here.
def gradientDescent(X,y,theta,alpha,num_iters,Lambda): """ Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration """ m=len(y) J_history =[] for i in range(num_iters): cost, grad = costFunctionReg(theta,X,y,Lambda) theta = theta - (alpha * grad) J_history.append(cost) return theta , J_historytheta , J_history = gradientDescent(X,y,initial_theta,1,800,0.2)print("The regularized theta using ridge regression:\n",theta)
The print statement will print:
Again, alpha, num_iters and λ values were not given, try a few combinations of values and come up with the best.
plt.plot(J_history)plt.xlabel("Iteration")plt.ylabel("$J(\Theta)$")plt.title("Cost function using Gradient Descent")
Using the values I stated, this is the resulting cost function against the number of iterations plot.
Decreasing cost function — CheckCost function plateau — Check
def mapFeaturePlot(x1,x2,degree): """ take in numpy array of x1 and x2, return all polynomial terms up to the given degree """ out = np.ones(1) for i in range(1,degree+1): for j in range(i+1): terms= (x1**(i-j) * x2**j) out= np.hstack((out,terms)) return outplt.scatter(X[pos[:,0],1],X[pos[:,0],2],c="r",marker="+",label="Admitted")plt.scatter(X[neg[:,0],1],X[neg[:,0],2],c="b",marker="x",label="Not admitted")# Plotting decision boundaryu_vals = np.linspace(-1,1.5,50)v_vals= np.linspace(-1,1.5,50)z=np.zeros((len(u_vals),len(v_vals)))for i in range(len(u_vals)): for j in range(len(v_vals)): z[i,j] =mapFeaturePlot(u_vals[i],v_vals[j],6) @ thetaplt.contour(u_vals,v_vals,z.T,0)plt.xlabel("Exam 1 score")plt.ylabel("Exam 2 score")plt.legend(loc=0)
Plotting of non-linear decision boundary involving plotting of a contour that separates the different classes. I did some googling and this stackoverflow answer might help some of you here. The code is just simple translating of the octave code given in the assignment, for the maths and intuitive behind the code, check out the stackoverflow link given above.
Pretty good I would say!
To check the accuracy of the model, we again make use of the % of correct classification on the training data.
def classifierPredict(theta,X): """ take in numpy array of theta and X and predict the class """ predictions = X.dot(theta) return predictions>0p=classifierPredict(theta,X)print("Train Accuracy:", (sum(p==y[:,np.newaxis])/len(y) *100)[0],"%")
The print statement print: Train Accuracy: 83.05084745762711% .Close, but not as high as the 88.983051% obtained in the assignment using fminunc .
Next, I would like to touch on Lasso Regression, another regularization method used to prevent overfitting. With reference from ‘Introduction to Statistical Learning’, Lasso regression has a clear advantage over ridge regression (regularization that we just did). That is, while ridge regression shrink coefficients towards zero, it can never reduce it to zero and hence, all features will be included in the model no matter how small the value of the coefficients. Lasso regression, on the other hand, is able to shrink coefficient to exactly zero, reducing the number of features and serve as a feature selection tools at the same time. This makes Lasso regression useful in cases with high dimension and helps with model interpretability.
For Lasso Regression, the cost function to be minimized is very similar to ridge regression.
Instead of adding the sum of Θ squared, it use the absolute value instead, and since it involves absolute values, computing it is difficult as it is not differentiable. Various algorithms are available to compute this and one such example can be found using sklearn library.
from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(penalty="l1")clf.fit(X,y)thetaLasso=clf.coef_print("The regularized theta using lasso regression:\n",thetaLasso.reshape(28,1))
A side-by-side comparison of the theta values.
As you can see, the lasso regression reduces several features to 0, reducing the dimension of the problem and improve model interpretability.
This is all I have for regularization. The Jupyter notebook will be uploaded to my GitHub at (https://github.com/Benlau93/Machine-Learning-by-Andrew-Ng-in-Python).
For other python implementation in the series,
Linear Regression
Logistic Regression
Neural Networks
Support Vector Machines
Unsupervised Learning
Anomaly Detection
Thank you for reading.
|
[
{
"code": null,
"e": 350,
"s": 172,
"text": "Continuing from programming assignment 2 (Logistic Regression), we will now proceed to regularized logistic regression in python to help us deal with the problem of overfitting."
},
{
"code": null,
"e": 487,
"s": 350,
"text": "Regularizations are shrinkage methods that shrink coefficient towards zero to prevent overfitting by reducing the variance of the model."
},
{
"code": null,
"e": 764,
"s": 487,
"text": "Going straight into the assignment, we start by importing all relevant libraries and dataset. This time, the dataset contains two tests result of microchips in a factory and we are going to use the test results to predict whether the microchips should be accepted or rejected."
},
{
"code": null,
"e": 898,
"s": 764,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltdf=pd.read_csv(\"ex2data2.txt\", header=None)df.head()df.describe()"
},
{
"code": null,
"e": 1011,
"s": 898,
"text": "As you can see, it is a multivariate, binary classification problem that we can solve using logistic regression."
},
{
"code": null,
"e": 1215,
"s": 1011,
"text": "Now to visual the data. As with the previous logistic regression visualization, each combination of x1 and x2 that leads to accepted microchips are plotted against combinations that result in a rejection"
},
{
"code": null,
"e": 1512,
"s": 1215,
"text": "X=df.iloc[:,:-1].valuesy=df.iloc[:,-1].valuespos , neg = (y==1).reshape(118,1) , (y==0).reshape(118,1)plt.scatter(X[pos[:,0],0],X[pos[:,0],1],c=\"r\",marker=\"+\")plt.scatter(X[neg[:,0],0],X[neg[:,0],1],marker=\"o\",s=10)plt.xlabel(\"Test 1\")plt.ylabel(\"Test 2\")plt.legend([\"Accepted\",\"Rejected\"],loc=0)"
},
{
"code": null,
"e": 1952,
"s": 1512,
"text": "Plotting the data clearly shows that the decision boundary that separates the different classes is a non-linear one. This lead to the next step of feature mapping, where we add additional polynomial terms to try and better fit the data (Normal logistic regression can only to able to fit a linear decision boundary which will not do well in this case). It is decided in the assignment that we will add polynomial terms up to the 6th power."
},
{
"code": null,
"e": 2330,
"s": 1952,
"text": "def mapFeature(x1,x2,degree): \"\"\" take in numpy array of x1 and x2, return all polynomial terms up to the given degree \"\"\" out = np.ones(len(x1)).reshape(len(x1),1) for i in range(1,degree+1): for j in range(i+1): terms= (x1**(i-j) * x2**j).reshape(len(x1),1) out= np.hstack((out,terms)) return outX = mapFeature(X[:,0], X[:,1],6)"
},
{
"code": null,
"e": 2789,
"s": 2330,
"text": "The mapFeature function also adds a column of ones to X so we do not have to deal with it later on. Here, I decided to use np.hstack instead of np.append to add a new column to the numpy array. I found np.hstack to be much neater in the code compared to np.append that I normally used. Here, I allow degree as a parameter instead of fixing it to 6 like how it was done in the assignment, feel free to play around with different degree and compare the result."
},
{
"code": null,
"e": 2878,
"s": 2789,
"text": "This diagram is useful to visualize what we are doing and the polynomial terms involved."
},
{
"code": null,
"e": 3071,
"s": 2878,
"text": "Next, we carry on to define a function that computes the regularize cost function and gradient. Remember that the cost function now has an additional shrinkage penalty that is controlled by λ."
},
{
"code": null,
"e": 3786,
"s": 3071,
"text": "def sigmoid(z): \"\"\" return the sigmoid of z \"\"\" return 1/ (1 + np.exp(-z))def costFunctionReg(theta, X, y ,Lambda): \"\"\" Take in numpy array of theta, X, and y to return the regularize cost function and gradient of a logistic regression \"\"\" m=len(y) y=y[:,np.newaxis] predictions = sigmoid(X @ theta) error = (-y * np.log(predictions)) - ((1-y)*np.log(1-predictions)) cost = 1/m * sum(error) regCost= cost + Lambda/(2*m) * sum(theta**2) # compute gradient j_0= 1/m * (X.transpose() @ (predictions - y))[0] j_1 = 1/m * (X.transpose() @ (predictions - y))[1:] + (Lambda/m)* theta[1:] grad= np.vstack((j_0[:,np.newaxis],j_1)) return regCost[0], grad"
},
{
"code": null,
"e": 4572,
"s": 3786,
"text": "You can use the same costFunction code and add-on a λ term to compute the regularized cost function. Another improvement from my last python implementation, I found that replacing np.dot with @ is the preferred option for matrix multiplication according to the official numpy documentation. Writing @ is also much easier so I am cool with that. In case you are not familiar with numpy broadcasting, you can check it out here. Broadcasting is the reason I need to add a new axis to y using y=y[:,np.newaxis] ,to ensure that the linear algebra manipulation is as I expected. If you had noticed, I used reshape() in the previous implementation to deal with broadcasting (Told you guys I am learning as I go). By the way, np.vstack here add to a new row instead of a column for np.hstack ."
},
{
"code": null,
"e": 4878,
"s": 4572,
"text": "# Initialize fitting parametersinitial_theta = np.zeros((X.shape[1], 1))# Set regularization parameter lambda to 1Lambda = 1#Compute and display initial cost and gradient for regularized logistic regressioncost, grad=costFunctionReg(initial_theta, X, y, Lambda)print(\"Cost at initial theta (zeros):\",cost)"
},
{
"code": null,
"e": 4955,
"s": 4878,
"text": "The print statement print: Cost at initial theta (zeros): 0.6931471805599461"
},
{
"code": null,
"e": 5110,
"s": 4955,
"text": "As for the optimizing algorithm, I again make use of the standard gradient descent instead of fminunc . The python way of doing fminunc can be found here."
},
{
"code": null,
"e": 5723,
"s": 5110,
"text": "def gradientDescent(X,y,theta,alpha,num_iters,Lambda): \"\"\" Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration \"\"\" m=len(y) J_history =[] for i in range(num_iters): cost, grad = costFunctionReg(theta,X,y,Lambda) theta = theta - (alpha * grad) J_history.append(cost) return theta , J_historytheta , J_history = gradientDescent(X,y,initial_theta,1,800,0.2)print(\"The regularized theta using ridge regression:\\n\",theta)"
},
{
"code": null,
"e": 5755,
"s": 5723,
"text": "The print statement will print:"
},
{
"code": null,
"e": 5868,
"s": 5755,
"text": "Again, alpha, num_iters and λ values were not given, try a few combinations of values and come up with the best."
},
{
"code": null,
"e": 5985,
"s": 5868,
"text": "plt.plot(J_history)plt.xlabel(\"Iteration\")plt.ylabel(\"$J(\\Theta)$\")plt.title(\"Cost function using Gradient Descent\")"
},
{
"code": null,
"e": 6087,
"s": 5985,
"text": "Using the values I stated, this is the resulting cost function against the number of iterations plot."
},
{
"code": null,
"e": 6149,
"s": 6087,
"text": "Decreasing cost function — CheckCost function plateau — Check"
},
{
"code": null,
"e": 6955,
"s": 6149,
"text": "def mapFeaturePlot(x1,x2,degree): \"\"\" take in numpy array of x1 and x2, return all polynomial terms up to the given degree \"\"\" out = np.ones(1) for i in range(1,degree+1): for j in range(i+1): terms= (x1**(i-j) * x2**j) out= np.hstack((out,terms)) return outplt.scatter(X[pos[:,0],1],X[pos[:,0],2],c=\"r\",marker=\"+\",label=\"Admitted\")plt.scatter(X[neg[:,0],1],X[neg[:,0],2],c=\"b\",marker=\"x\",label=\"Not admitted\")# Plotting decision boundaryu_vals = np.linspace(-1,1.5,50)v_vals= np.linspace(-1,1.5,50)z=np.zeros((len(u_vals),len(v_vals)))for i in range(len(u_vals)): for j in range(len(v_vals)): z[i,j] =mapFeaturePlot(u_vals[i],v_vals[j],6) @ thetaplt.contour(u_vals,v_vals,z.T,0)plt.xlabel(\"Exam 1 score\")plt.ylabel(\"Exam 2 score\")plt.legend(loc=0)"
},
{
"code": null,
"e": 7316,
"s": 6955,
"text": "Plotting of non-linear decision boundary involving plotting of a contour that separates the different classes. I did some googling and this stackoverflow answer might help some of you here. The code is just simple translating of the octave code given in the assignment, for the maths and intuitive behind the code, check out the stackoverflow link given above."
},
{
"code": null,
"e": 7341,
"s": 7316,
"text": "Pretty good I would say!"
},
{
"code": null,
"e": 7452,
"s": 7341,
"text": "To check the accuracy of the model, we again make use of the % of correct classification on the training data."
},
{
"code": null,
"e": 7715,
"s": 7452,
"text": "def classifierPredict(theta,X): \"\"\" take in numpy array of theta and X and predict the class \"\"\" predictions = X.dot(theta) return predictions>0p=classifierPredict(theta,X)print(\"Train Accuracy:\", (sum(p==y[:,np.newaxis])/len(y) *100)[0],\"%\")"
},
{
"code": null,
"e": 7862,
"s": 7715,
"text": "The print statement print: Train Accuracy: 83.05084745762711% .Close, but not as high as the 88.983051% obtained in the assignment using fminunc ."
},
{
"code": null,
"e": 8604,
"s": 7862,
"text": "Next, I would like to touch on Lasso Regression, another regularization method used to prevent overfitting. With reference from ‘Introduction to Statistical Learning’, Lasso regression has a clear advantage over ridge regression (regularization that we just did). That is, while ridge regression shrink coefficients towards zero, it can never reduce it to zero and hence, all features will be included in the model no matter how small the value of the coefficients. Lasso regression, on the other hand, is able to shrink coefficient to exactly zero, reducing the number of features and serve as a feature selection tools at the same time. This makes Lasso regression useful in cases with high dimension and helps with model interpretability."
},
{
"code": null,
"e": 8697,
"s": 8604,
"text": "For Lasso Regression, the cost function to be minimized is very similar to ridge regression."
},
{
"code": null,
"e": 8972,
"s": 8697,
"text": "Instead of adding the sum of Θ squared, it use the absolute value instead, and since it involves absolute values, computing it is difficult as it is not differentiable. Various algorithms are available to compute this and one such example can be found using sklearn library."
},
{
"code": null,
"e": 9175,
"s": 8972,
"text": "from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(penalty=\"l1\")clf.fit(X,y)thetaLasso=clf.coef_print(\"The regularized theta using lasso regression:\\n\",thetaLasso.reshape(28,1))"
},
{
"code": null,
"e": 9222,
"s": 9175,
"text": "A side-by-side comparison of the theta values."
},
{
"code": null,
"e": 9364,
"s": 9222,
"text": "As you can see, the lasso regression reduces several features to 0, reducing the dimension of the problem and improve model interpretability."
},
{
"code": null,
"e": 9528,
"s": 9364,
"text": "This is all I have for regularization. The Jupyter notebook will be uploaded to my GitHub at (https://github.com/Benlau93/Machine-Learning-by-Andrew-Ng-in-Python)."
},
{
"code": null,
"e": 9575,
"s": 9528,
"text": "For other python implementation in the series,"
},
{
"code": null,
"e": 9593,
"s": 9575,
"text": "Linear Regression"
},
{
"code": null,
"e": 9613,
"s": 9593,
"text": "Logistic Regression"
},
{
"code": null,
"e": 9629,
"s": 9613,
"text": "Neural Networks"
},
{
"code": null,
"e": 9653,
"s": 9629,
"text": "Support Vector Machines"
},
{
"code": null,
"e": 9675,
"s": 9653,
"text": "Unsupervised Learning"
},
{
"code": null,
"e": 9693,
"s": 9675,
"text": "Anomaly Detection"
}
] |
Detecting Abnormal Weather Patterns With Data Science Tools | by Chua Chin Hon | Towards Data Science
|
Around the world, extreme weather events are becoming more intense and frequent.
There’s no missing some of these major weather abnormalities, such as flash floods or prolonged droughts, which can affect large swathes of a country’s population.
But not every weather outlier can be easily observed, particularly in Singapore where the seasonal changes are less obvious to the naked eye. Yet, these “milder” anomalies could be just as important in understanding future changes in the weather pattern.
Data visualisation, such as the range of charts in my earlier Medium post on the subject, provide a quick way to spot such outliers in a dataset. The classic Seaborn pair plot is one way to do this.
But when you have 36 years of weather data, it won’t be easy or efficient to rely on charts to accurately pick out the outliers.
In this third of a multi-part data science project using historical weather data from Singapore, I’ll use Scikit-learn’s Isolation Forest model as well as the PyOD library (Python Outlier Detection) to try to pinpoint outliers in the dataset.
It will be interesting to see the precise dates where these abnormal weather patterns took place. This is also important pre-work for Part IV of the project — time series forecasting, where removal of the outliers would be key to more accurate predictions.
The original source of the weather data in this project can be found here. The Jupyter notebook for this post is here, and you can download the interactive Plotly charts here to explore the outlier data in greater detail.
For the benefit of those who might have no interest in plowing through the detailed data workflow, I’ll start with a quick overview of the results.
The chart below is a slice of the results from two of the PyOD models used to pick out outliers from daily weather in Singapore from January 1 1983 to June 30 2019. I aggregated the results from 4 models in all, and got 816 unique outliers from the dataset comprising 13,330 rows. In other words, outliers comprised about 6% of the data. You can download and explore this subset of weather outliers here.
March 2010, December 1991, and January 1987 tie for the most number of abnormal weather occurrences in a month — 10.
Year Month Number of days with outlier weather 2010 3 101987 1 101991 12 101983 4 91992 12 91983 12 82006 12 81998 12 82008 3 71986 1 7
The year 1998 had the most number of abnormal weather occurrences, followed by 1983 and 2013. The highest temperature of 36.0°C was recorded on March 26 1998.
Over the last 36 years in Singapore, December and January were the months with the highest number of days with outlier weather — not surprising given the more intense storms during the end and the beginning of the year.
Some outliers in the weather dataset are more extreme than others, as expected. Plotting the 816 outliers together, we can see a a clear cluster in the centre, bounded by maximum temperatures between 26–34°C and max wind speed of between 20–50kmh. The bigger circles represent days with heavier rainfall.
The more extreme outliers lie to the right, bottom left and top of the chart. Below is a detail of the main clusters in the outliers. Download and explore the interactive version here.
Next, I’ll detail how I arrived at the outlier data and plot a bunch more charts.
Intuitively, we know it doesn’t make sense to try to pick out weather outliers in isolation. For instance, a major storm would obviously result in extreme rainfall, strong winds and lower temperatures.
But I am curious to see what the outlier analysis of a single variable would turn up. I reckon it would be helpful to have some basis of comparison as well with the multivariate PyOD technique.
So let’s see what we can find when the Isolation Forest model is applied to 36 years of daily rainfall data in Singapore. But first, let’s check on the skewness and kurtosis scores of the daily rainfall column.
Skewness: 5.140533Kurtosis: 40.778205
Skewness is a measure of the degree of distortion in a dataset. A symmetrical dataset with a normal distribution will have a skewness value of 0.
Kurtosis is a measure of the outliers in the distribution. See this article here for a reader-friendly explanation.
In the case of the daily rainfall column, we see that the data is highly skewed (skewness score greater than 1) to the right due to days where there are unusual amounts of rain. There’s no rain for about half the time as well (hence the sharp column at 0).
The kurtosis score for the daily rainfall variable is also high (a normal distribution has a kurtosis of three), indicating the presence of a considerable number of outliers.
I ran the rainfall data on the Isolation Forest model, a tree-based model widely used to identify outliers. See these two articles(here and here) for an in-depth explanation.
The key parameter to adjust here is for “contamination”, or the proportion of outliers. I opted for the old default value of 0.1 instead of the new default of “auto”, which would have given me a far higher proportion of outliers.
The main outlier region, in pink, starts from about 19.4mm of rain. In our dataset, there are 1,300 entries that have rainfall higher than 19.4mm. This seems an awfully large number of outliers to try to remove, and I don’t have the domain knowledge to know how best to re-adjust the contamination level.
I repeated the same steps for the daily maximum temperature column, and ended up with a similarly high number of outliers — 1,223. I won’t go into details here but the charts and code are available in my notebook.
Overall, it doesn’t seem right to try to remove such large numbers of outliers in isolation. Let’s see if the PyOD approach is better.
In the Singapore context, the two variables that are most closely associated with abnormal weather would be maximum daily temperature and daily rainfall, making them the obvious choices for outlier detection in PyOD’s models. You can use more than two variables, but doing so will obviously complicate the visualisation of the results.
PyOD has over 20 detection algorithms, many of which you can mix and match together. What I find useful is that the toolkit allows for easy combination of the results from multiple detectors (further details in this paper here).
For the weather dataset, I picked 4 algorithms — the Cluster-based Local Outlier Factor, the Histogram-base Outlier Detection, the Isolation Forest, and the classic K Nearest Neighbors. The results from the 4 models were slightly different, as the charts below show.
I then aggregated the results and filtered out the duplicates via a few simple steps in pandas.
The PyOD library works great out of the box, but the challenge yet again is domain knowledge. Like in the case of the univariate analysis earlier, one key parameter you’ll have to set for PyOD is the contamination/outliers_fraction — the percentage of outliers you expect to find in the dataset.
The default value is 0.1, or 10%, which could be an over or under-estimation. Without better meteorological knowledge, it is hard to say what’s a “correct” outliers fraction to set.
Since I have no expertise in this area, I used a trial-and-error process to see if the outliers identified by the models matched certain key dates where extreme weather, such as flash floods, were reported. Examples include the flash floods in 2010, 2011 and 2018.
Eventually, I settled on an outliers_fraction of 0.04. Anything lower would have missed key dates where abnormal weather patterns had been reported. Anything higher would result in the removal of a very significant proportion of the dataset.
In all, the PyOD models picked out 816 unique outliers out of a total of 13,330 data points, or about 6% of the dataset.
On inspection, the models managed to pick out the heaviest single day of rainfall in the last 36 years — Jan 30 2011 when 216.2mm of rain fell. The PyOD models also successfully picked out the highest daily temperature measured — 36°C, on March 26 1998.
Let’s build on some of the visualisation techniques in notebook2.0 and apply them here for a closer look at the outlier patterns by year, month and year-month combination.
As mentioned in the overview of results earlier, March 2010, December 1991, and January 1987 tie for the most number of abnormal weather occurrences in a month — 10. These are the 10 weather outliers for March 2010:
The maximum temperature and daily rainfall columns clearly show why the weather on these dates are considered outliers. The maximum daily temperatures for March 3, 4, 6, 7 and 9 for instances were very high, at 35°C and higher.
The average daily maximum temperature over the last 36 years is 31.5°C, with a standard deviation of 1.6°C. On the other end of the spectrum, PyOD’s algorithms caught an interesting outlier on March 20 2010, when the daily maximum temperature was just 25.9°C — unusually low by Singapore standards.
March 2010 also saw several days of heavy rainfall, particularly on March 23 (57.6mm) and March 31 (49.1mm). The average daily rainfall over the last 36 years is 5.85mm.
The 10 outliers for Jan 1987 are also obvious at a glance:
Check out the record for the massive downpour of 127.4mm on January 11 1987. That amount of rain in 1 day was about 80% of the median monthly rainfall that Singapore got over the last 36 years (160.1mm).
The Plotly Express interactive charts make it much easier to explore the outliers. I’ve separately plotted the outliers for March 2010 and and Jan 1987.
Unfortunately, Medium doesn’t make it easy for interactive charts to be embedded in the posts, so what you are seeing above and below are screen-caps-gifs. Download the full interactive charts here.
We can also break down the outliers weather data by year, and see which year had the most number of abnormal records. 1998 had the most number of outlier weather occurrences, followed by 1983 and 2013. The highest temperature of 36.0°C was recorded on March 26 1998.
Year Number of outlier weather days 1998 381983 342013 312006 291984 291986 292010 292007 292008 281988 28
Using a format I had tried in notebook2.0, I picked 3 years with the highest number of abnormal weather patterns — 2013, 1998, and 1983 — and broke them down in a series of matrix panels for easy comparisons.
In the panels below, the larger circles represent days of higher rainfall. The darker and more highly placed a circle is, the higher the maximum temperature and maximum wind speed for that day.
1998 looks to have the most interesting distribution of outliers, with a noticeable stretch of abnormal weather seen from April to September, aside from the heavy rainfall usually seen in January and December.
Some outliers are obviously more extreme than the others. Let’s try to isolate the extreme outliers from the “standard outliers”. In the chart below, the bigger circles signal heavier rainfall. The circles with a darker shade refer to outlier points which are more recent.
We can see a clear cluster in the centre, bounded by maximum temperatures between 26–34°C and max wind speed of between 20–50kmh. The bigger circles represent days with heavier rainfall.
The more extreme outliers lie to the right, bottom left and top of the chart. It’ll be interesting to see if the central cluster moves upward and towards the right in the coming decades.
Analysis of outliers can go in a dozen different directions, depending on the choices and assumptions you make. Share your insights if you use the same dataset for a similar project.
As usual, if you spot any errors, ping me @
Twitter: @chinhon
LinkedIn: www.linkedin.com/in/chuachinhon
And here’s my earlier project on visualising Singapore’s changing weather patterns.
|
[
{
"code": null,
"e": 128,
"s": 47,
"text": "Around the world, extreme weather events are becoming more intense and frequent."
},
{
"code": null,
"e": 292,
"s": 128,
"text": "There’s no missing some of these major weather abnormalities, such as flash floods or prolonged droughts, which can affect large swathes of a country’s population."
},
{
"code": null,
"e": 547,
"s": 292,
"text": "But not every weather outlier can be easily observed, particularly in Singapore where the seasonal changes are less obvious to the naked eye. Yet, these “milder” anomalies could be just as important in understanding future changes in the weather pattern."
},
{
"code": null,
"e": 746,
"s": 547,
"text": "Data visualisation, such as the range of charts in my earlier Medium post on the subject, provide a quick way to spot such outliers in a dataset. The classic Seaborn pair plot is one way to do this."
},
{
"code": null,
"e": 875,
"s": 746,
"text": "But when you have 36 years of weather data, it won’t be easy or efficient to rely on charts to accurately pick out the outliers."
},
{
"code": null,
"e": 1118,
"s": 875,
"text": "In this third of a multi-part data science project using historical weather data from Singapore, I’ll use Scikit-learn’s Isolation Forest model as well as the PyOD library (Python Outlier Detection) to try to pinpoint outliers in the dataset."
},
{
"code": null,
"e": 1375,
"s": 1118,
"text": "It will be interesting to see the precise dates where these abnormal weather patterns took place. This is also important pre-work for Part IV of the project — time series forecasting, where removal of the outliers would be key to more accurate predictions."
},
{
"code": null,
"e": 1597,
"s": 1375,
"text": "The original source of the weather data in this project can be found here. The Jupyter notebook for this post is here, and you can download the interactive Plotly charts here to explore the outlier data in greater detail."
},
{
"code": null,
"e": 1745,
"s": 1597,
"text": "For the benefit of those who might have no interest in plowing through the detailed data workflow, I’ll start with a quick overview of the results."
},
{
"code": null,
"e": 2150,
"s": 1745,
"text": "The chart below is a slice of the results from two of the PyOD models used to pick out outliers from daily weather in Singapore from January 1 1983 to June 30 2019. I aggregated the results from 4 models in all, and got 816 unique outliers from the dataset comprising 13,330 rows. In other words, outliers comprised about 6% of the data. You can download and explore this subset of weather outliers here."
},
{
"code": null,
"e": 2267,
"s": 2150,
"text": "March 2010, December 1991, and January 1987 tie for the most number of abnormal weather occurrences in a month — 10."
},
{
"code": null,
"e": 2489,
"s": 2267,
"text": "Year Month Number of days with outlier weather 2010 3 101987 1 101991 12 101983 4 91992 12 91983 12 82006 12 81998 12 82008 3 71986 1 7"
},
{
"code": null,
"e": 2648,
"s": 2489,
"text": "The year 1998 had the most number of abnormal weather occurrences, followed by 1983 and 2013. The highest temperature of 36.0°C was recorded on March 26 1998."
},
{
"code": null,
"e": 2868,
"s": 2648,
"text": "Over the last 36 years in Singapore, December and January were the months with the highest number of days with outlier weather — not surprising given the more intense storms during the end and the beginning of the year."
},
{
"code": null,
"e": 3173,
"s": 2868,
"text": "Some outliers in the weather dataset are more extreme than others, as expected. Plotting the 816 outliers together, we can see a a clear cluster in the centre, bounded by maximum temperatures between 26–34°C and max wind speed of between 20–50kmh. The bigger circles represent days with heavier rainfall."
},
{
"code": null,
"e": 3358,
"s": 3173,
"text": "The more extreme outliers lie to the right, bottom left and top of the chart. Below is a detail of the main clusters in the outliers. Download and explore the interactive version here."
},
{
"code": null,
"e": 3440,
"s": 3358,
"text": "Next, I’ll detail how I arrived at the outlier data and plot a bunch more charts."
},
{
"code": null,
"e": 3642,
"s": 3440,
"text": "Intuitively, we know it doesn’t make sense to try to pick out weather outliers in isolation. For instance, a major storm would obviously result in extreme rainfall, strong winds and lower temperatures."
},
{
"code": null,
"e": 3836,
"s": 3642,
"text": "But I am curious to see what the outlier analysis of a single variable would turn up. I reckon it would be helpful to have some basis of comparison as well with the multivariate PyOD technique."
},
{
"code": null,
"e": 4047,
"s": 3836,
"text": "So let’s see what we can find when the Isolation Forest model is applied to 36 years of daily rainfall data in Singapore. But first, let’s check on the skewness and kurtosis scores of the daily rainfall column."
},
{
"code": null,
"e": 4085,
"s": 4047,
"text": "Skewness: 5.140533Kurtosis: 40.778205"
},
{
"code": null,
"e": 4231,
"s": 4085,
"text": "Skewness is a measure of the degree of distortion in a dataset. A symmetrical dataset with a normal distribution will have a skewness value of 0."
},
{
"code": null,
"e": 4347,
"s": 4231,
"text": "Kurtosis is a measure of the outliers in the distribution. See this article here for a reader-friendly explanation."
},
{
"code": null,
"e": 4604,
"s": 4347,
"text": "In the case of the daily rainfall column, we see that the data is highly skewed (skewness score greater than 1) to the right due to days where there are unusual amounts of rain. There’s no rain for about half the time as well (hence the sharp column at 0)."
},
{
"code": null,
"e": 4779,
"s": 4604,
"text": "The kurtosis score for the daily rainfall variable is also high (a normal distribution has a kurtosis of three), indicating the presence of a considerable number of outliers."
},
{
"code": null,
"e": 4954,
"s": 4779,
"text": "I ran the rainfall data on the Isolation Forest model, a tree-based model widely used to identify outliers. See these two articles(here and here) for an in-depth explanation."
},
{
"code": null,
"e": 5184,
"s": 4954,
"text": "The key parameter to adjust here is for “contamination”, or the proportion of outliers. I opted for the old default value of 0.1 instead of the new default of “auto”, which would have given me a far higher proportion of outliers."
},
{
"code": null,
"e": 5489,
"s": 5184,
"text": "The main outlier region, in pink, starts from about 19.4mm of rain. In our dataset, there are 1,300 entries that have rainfall higher than 19.4mm. This seems an awfully large number of outliers to try to remove, and I don’t have the domain knowledge to know how best to re-adjust the contamination level."
},
{
"code": null,
"e": 5703,
"s": 5489,
"text": "I repeated the same steps for the daily maximum temperature column, and ended up with a similarly high number of outliers — 1,223. I won’t go into details here but the charts and code are available in my notebook."
},
{
"code": null,
"e": 5838,
"s": 5703,
"text": "Overall, it doesn’t seem right to try to remove such large numbers of outliers in isolation. Let’s see if the PyOD approach is better."
},
{
"code": null,
"e": 6174,
"s": 5838,
"text": "In the Singapore context, the two variables that are most closely associated with abnormal weather would be maximum daily temperature and daily rainfall, making them the obvious choices for outlier detection in PyOD’s models. You can use more than two variables, but doing so will obviously complicate the visualisation of the results."
},
{
"code": null,
"e": 6403,
"s": 6174,
"text": "PyOD has over 20 detection algorithms, many of which you can mix and match together. What I find useful is that the toolkit allows for easy combination of the results from multiple detectors (further details in this paper here)."
},
{
"code": null,
"e": 6670,
"s": 6403,
"text": "For the weather dataset, I picked 4 algorithms — the Cluster-based Local Outlier Factor, the Histogram-base Outlier Detection, the Isolation Forest, and the classic K Nearest Neighbors. The results from the 4 models were slightly different, as the charts below show."
},
{
"code": null,
"e": 6766,
"s": 6670,
"text": "I then aggregated the results and filtered out the duplicates via a few simple steps in pandas."
},
{
"code": null,
"e": 7062,
"s": 6766,
"text": "The PyOD library works great out of the box, but the challenge yet again is domain knowledge. Like in the case of the univariate analysis earlier, one key parameter you’ll have to set for PyOD is the contamination/outliers_fraction — the percentage of outliers you expect to find in the dataset."
},
{
"code": null,
"e": 7244,
"s": 7062,
"text": "The default value is 0.1, or 10%, which could be an over or under-estimation. Without better meteorological knowledge, it is hard to say what’s a “correct” outliers fraction to set."
},
{
"code": null,
"e": 7509,
"s": 7244,
"text": "Since I have no expertise in this area, I used a trial-and-error process to see if the outliers identified by the models matched certain key dates where extreme weather, such as flash floods, were reported. Examples include the flash floods in 2010, 2011 and 2018."
},
{
"code": null,
"e": 7751,
"s": 7509,
"text": "Eventually, I settled on an outliers_fraction of 0.04. Anything lower would have missed key dates where abnormal weather patterns had been reported. Anything higher would result in the removal of a very significant proportion of the dataset."
},
{
"code": null,
"e": 7872,
"s": 7751,
"text": "In all, the PyOD models picked out 816 unique outliers out of a total of 13,330 data points, or about 6% of the dataset."
},
{
"code": null,
"e": 8126,
"s": 7872,
"text": "On inspection, the models managed to pick out the heaviest single day of rainfall in the last 36 years — Jan 30 2011 when 216.2mm of rain fell. The PyOD models also successfully picked out the highest daily temperature measured — 36°C, on March 26 1998."
},
{
"code": null,
"e": 8298,
"s": 8126,
"text": "Let’s build on some of the visualisation techniques in notebook2.0 and apply them here for a closer look at the outlier patterns by year, month and year-month combination."
},
{
"code": null,
"e": 8514,
"s": 8298,
"text": "As mentioned in the overview of results earlier, March 2010, December 1991, and January 1987 tie for the most number of abnormal weather occurrences in a month — 10. These are the 10 weather outliers for March 2010:"
},
{
"code": null,
"e": 8742,
"s": 8514,
"text": "The maximum temperature and daily rainfall columns clearly show why the weather on these dates are considered outliers. The maximum daily temperatures for March 3, 4, 6, 7 and 9 for instances were very high, at 35°C and higher."
},
{
"code": null,
"e": 9041,
"s": 8742,
"text": "The average daily maximum temperature over the last 36 years is 31.5°C, with a standard deviation of 1.6°C. On the other end of the spectrum, PyOD’s algorithms caught an interesting outlier on March 20 2010, when the daily maximum temperature was just 25.9°C — unusually low by Singapore standards."
},
{
"code": null,
"e": 9211,
"s": 9041,
"text": "March 2010 also saw several days of heavy rainfall, particularly on March 23 (57.6mm) and March 31 (49.1mm). The average daily rainfall over the last 36 years is 5.85mm."
},
{
"code": null,
"e": 9270,
"s": 9211,
"text": "The 10 outliers for Jan 1987 are also obvious at a glance:"
},
{
"code": null,
"e": 9474,
"s": 9270,
"text": "Check out the record for the massive downpour of 127.4mm on January 11 1987. That amount of rain in 1 day was about 80% of the median monthly rainfall that Singapore got over the last 36 years (160.1mm)."
},
{
"code": null,
"e": 9627,
"s": 9474,
"text": "The Plotly Express interactive charts make it much easier to explore the outliers. I’ve separately plotted the outliers for March 2010 and and Jan 1987."
},
{
"code": null,
"e": 9826,
"s": 9627,
"text": "Unfortunately, Medium doesn’t make it easy for interactive charts to be embedded in the posts, so what you are seeing above and below are screen-caps-gifs. Download the full interactive charts here."
},
{
"code": null,
"e": 10093,
"s": 9826,
"text": "We can also break down the outliers weather data by year, and see which year had the most number of abnormal records. 1998 had the most number of outlier weather occurrences, followed by 1983 and 2013. The highest temperature of 36.0°C was recorded on March 26 1998."
},
{
"code": null,
"e": 10231,
"s": 10093,
"text": "Year Number of outlier weather days 1998 381983 342013 312006 291984 291986 292010 292007 292008 281988 28"
},
{
"code": null,
"e": 10440,
"s": 10231,
"text": "Using a format I had tried in notebook2.0, I picked 3 years with the highest number of abnormal weather patterns — 2013, 1998, and 1983 — and broke them down in a series of matrix panels for easy comparisons."
},
{
"code": null,
"e": 10634,
"s": 10440,
"text": "In the panels below, the larger circles represent days of higher rainfall. The darker and more highly placed a circle is, the higher the maximum temperature and maximum wind speed for that day."
},
{
"code": null,
"e": 10844,
"s": 10634,
"text": "1998 looks to have the most interesting distribution of outliers, with a noticeable stretch of abnormal weather seen from April to September, aside from the heavy rainfall usually seen in January and December."
},
{
"code": null,
"e": 11117,
"s": 10844,
"text": "Some outliers are obviously more extreme than the others. Let’s try to isolate the extreme outliers from the “standard outliers”. In the chart below, the bigger circles signal heavier rainfall. The circles with a darker shade refer to outlier points which are more recent."
},
{
"code": null,
"e": 11304,
"s": 11117,
"text": "We can see a clear cluster in the centre, bounded by maximum temperatures between 26–34°C and max wind speed of between 20–50kmh. The bigger circles represent days with heavier rainfall."
},
{
"code": null,
"e": 11491,
"s": 11304,
"text": "The more extreme outliers lie to the right, bottom left and top of the chart. It’ll be interesting to see if the central cluster moves upward and towards the right in the coming decades."
},
{
"code": null,
"e": 11674,
"s": 11491,
"text": "Analysis of outliers can go in a dozen different directions, depending on the choices and assumptions you make. Share your insights if you use the same dataset for a similar project."
},
{
"code": null,
"e": 11718,
"s": 11674,
"text": "As usual, if you spot any errors, ping me @"
},
{
"code": null,
"e": 11736,
"s": 11718,
"text": "Twitter: @chinhon"
},
{
"code": null,
"e": 11778,
"s": 11736,
"text": "LinkedIn: www.linkedin.com/in/chuachinhon"
}
] |
Left View of Binary Tree | Practice | GeeksforGeeks
|
Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument.
Left view of following tree is 1 2 4 8.
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Example 1:
Input:
1
/ \
3 2
Output: 1 3
Example 2:
Input:
Output: 10 20 40
Your Task:
You just have to complete the function leftView() that prints the left view. The newline is automatically appended by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
0 <= Number of nodes <= 100
1 <= Data of a node <= 1000
0
binayshaw7777in 2 hours
Simple Java Code:
class Tree
{
//Function to return list containing elements of left view of binary tree.
ArrayList<Integer> leftView(Node root) {
ArrayList<Integer> list = new ArrayList<>();
LV(root, list, 0);
return list;
}
public void LV(Node root, ArrayList<Integer> list, int level) {
if (root == null) return;
if (level == list.size()) list.add(root.data);
LV(root.left, list, level+1);
LV(root.right, list, level+1);
}
}
0
tarunkanade1 day ago
0.83/1.91 Java Theta(n), Theta(w)
ArrayList<Integer> leftView(Node root)
{
// Your code here
ArrayList<Integer> list = new ArrayList<>();
if(root == null){
return list;
}
ArrayDeque<Node> q = new ArrayDeque<>();
int count;
Node cur;
q.offer(root);
while(!q.isEmpty()){
count = q.size();
for(int i=0; i<count; i++){
cur = q.poll();
if(i == 0){
list.add(cur.data);
}
if(cur.left != null) q.offer(cur.left);
if(cur.right != null) q.offer(cur.right);
}
}
return list;
}
0
shulabhgill2 days ago
class Tree{ //Function to return list containing elements of left view of binary tree. ArrayList<Integer> leftView(Node root) { // Your code here ArrayList<Integer> res =new ArrayList<>(); if(root==null) return res; Queue<Node> qu=new LinkedList<>(); qu.add(root); while(!qu.isEmpty()){ int k= qu.size(); for(int i=0;i<k;i++){ Node temp=qu.poll(); if(i==0) res.add(temp.data); if(temp.left!=null) qu.add(temp.left); if(temp.right!=null) qu.add(temp.right); } } return res; }}
0
shubham211019973 days ago
ArrayList<Integer> arr=new ArrayList<Integer>();
if(root==null)return arr;
Queue<Node>q=new LinkedList<>();
q.add(root);
while(q.isEmpty()==false){
int size=q.size();
for(int i=0;i<size;i++){
Node curr=q.poll();
if(i==0){
arr.add(curr.data);
}
if(curr.left!=null)q.add(curr.left);
if(curr.right!=null)q.add(curr.right);
}
}
return arr;
0
iamtkarthikreddy
This comment was deleted.
0
osamu1 week ago
vector<int> leftView(Node *root){ // Your code here vector<int> ans; if(!root) return ans; queue<pair<Node*,int>> q; // Store Node and level q.push({root,0}); map<int,int> mp; //store level and value at that level while(!q.empty()) { auto it= q.front(); q.pop(); Node* curr=it.first; int lev=it.second; if(mp.count(lev)==0) // in this condition it will check if on that level there exist an element than it will not work else it will insert a value at that key making its count as 1 so after next time it will not work { mp[lev]=curr->data; } if(curr->left) { int temp=lev+1; q.push({curr->left,temp}); } if(curr->right) { int temp=lev+1; q.push({curr->right,temp}); } } for(auto it: mp) { ans.push_back(it.second); } return ans;}
//Basically what are we doing is we are making a queue of pair<Node*,int> where here int will be the level as its left view so if any level is counter first during bfs we will make it put in map in which map will have key as level and value as data
+3
bipulharsh1232 weeks ago
void getLeftView(Node *ptr, vector<int>&result, int level=1){ if(!ptr) return; if(level > result.scd ize()) result.push_back(ptr->data); getLeftView(ptr->left, result, level+1); getLeftView(ptr->right, result, level+1);}
//Function to return a list containing elements of left view of the binary tree.vector<int> leftView(Node *root){ // Your code here vector<int> result; int level=1; getLeftView(root, result, level); return result;}
+2
jainmuskan5652 weeks ago
vector<int>v;void fxn(Node* node, int level){ if(node== NULL){ return; } if(v.size()<= level){ v.push_back(node->data); } fxn(node->left, level+1); fxn(node->right, level+1);}vector<int> leftView(Node *root){ // left side view // first node of every level // traversing left root right <-- v.clear(); fxn(root,0); return v; }
0
mkbastronaut4412 weeks ago
vector<int> leftView(Node *root){ // Your code here //Your code here if(root==NULL) return {}; queue<Node*>q; vector<int> v; q.push(root); while(!q.empty()){ int n=q.size(); for(int i=0;i<n;i++){ Node*t=q.front(); q.pop(); if(i==0) v.push_back(t->data); if(t->left) q.push(t->left); if(t->right)q.push(t->right); } } return v;
0
jatin2k19ec0822 weeks ago
int height(Node* root){ if(root==NULL) return 0; int lh=height(root->left); int rh=height(root->right); if(lh>rh) return lh+1; else return rh+1;}int left(Node* root,int level){ if(root==NULL) return 0; if(level==1) { if(root==NULL) return 0; else return root->data; } int k=left(root->left,level-1); if(k==0) return left(root->right,level-1); else return k;}vector<int> leftView(Node *root){ // Your code here vector<int>arr; int h=height(root); for(int i=1;i<=h;i++) { int j=left(root,i); arr.push_back(j); } return arr;}
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": 463,
"s": 238,
"text": "Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument."
},
{
"code": null,
"e": 503,
"s": 463,
"text": "Left view of following tree is 1 2 4 8."
},
{
"code": null,
"e": 601,
"s": 503,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\\n 8 "
},
{
"code": null,
"e": 612,
"s": 601,
"text": "Example 1:"
},
{
"code": null,
"e": 651,
"s": 612,
"text": "Input:\n 1\n / \\\n3 2\nOutput: 1 3\n\n"
},
{
"code": null,
"e": 662,
"s": 651,
"text": "Example 2:"
},
{
"code": null,
"e": 688,
"s": 662,
"text": "Input:\n\nOutput: 10 20 40\n"
},
{
"code": null,
"e": 915,
"s": 688,
"text": "Your Task:\nYou just have to complete the function leftView() that prints the left view. The newline is automatically appended by the driver code.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 984,
"s": 915,
"text": "Constraints:\n0 <= Number of nodes <= 100\n1 <= Data of a node <= 1000"
},
{
"code": null,
"e": 986,
"s": 984,
"text": "0"
},
{
"code": null,
"e": 1010,
"s": 986,
"text": "binayshaw7777in 2 hours"
},
{
"code": null,
"e": 1028,
"s": 1010,
"text": "Simple Java Code:"
},
{
"code": null,
"e": 1513,
"s": 1028,
"text": "class Tree\n{\n //Function to return list containing elements of left view of binary tree.\n ArrayList<Integer> leftView(Node root) {\n ArrayList<Integer> list = new ArrayList<>();\n LV(root, list, 0);\n return list;\n }\n \n public void LV(Node root, ArrayList<Integer> list, int level) {\n if (root == null) return;\n if (level == list.size()) list.add(root.data);\n LV(root.left, list, level+1);\n LV(root.right, list, level+1);\n }\n}"
},
{
"code": null,
"e": 1515,
"s": 1513,
"text": "0"
},
{
"code": null,
"e": 1536,
"s": 1515,
"text": "tarunkanade1 day ago"
},
{
"code": null,
"e": 1570,
"s": 1536,
"text": "0.83/1.91 Java Theta(n), Theta(w)"
},
{
"code": null,
"e": 2265,
"s": 1570,
"text": "ArrayList<Integer> leftView(Node root)\n {\n // Your code here\n ArrayList<Integer> list = new ArrayList<>();\n \n if(root == null){\n return list;\n }\n \n ArrayDeque<Node> q = new ArrayDeque<>();\n int count;\n Node cur;\n \n q.offer(root);\n \n while(!q.isEmpty()){\n count = q.size();\n \n for(int i=0; i<count; i++){\n cur = q.poll();\n if(i == 0){\n list.add(cur.data);\n }\n \n if(cur.left != null) q.offer(cur.left);\n if(cur.right != null) q.offer(cur.right);\n }\n }\n \n return list;\n }"
},
{
"code": null,
"e": 2267,
"s": 2265,
"text": "0"
},
{
"code": null,
"e": 2289,
"s": 2267,
"text": "shulabhgill2 days ago"
},
{
"code": null,
"e": 2991,
"s": 2289,
"text": "class Tree{ //Function to return list containing elements of left view of binary tree. ArrayList<Integer> leftView(Node root) { // Your code here ArrayList<Integer> res =new ArrayList<>(); if(root==null) return res; Queue<Node> qu=new LinkedList<>(); qu.add(root); while(!qu.isEmpty()){ int k= qu.size(); for(int i=0;i<k;i++){ Node temp=qu.poll(); if(i==0) res.add(temp.data); if(temp.left!=null) qu.add(temp.left); if(temp.right!=null) qu.add(temp.right); } } return res; }}"
},
{
"code": null,
"e": 2993,
"s": 2991,
"text": "0"
},
{
"code": null,
"e": 3019,
"s": 2993,
"text": "shubham211019973 days ago"
},
{
"code": null,
"e": 3482,
"s": 3019,
"text": "ArrayList<Integer> arr=new ArrayList<Integer>();\n if(root==null)return arr;\n Queue<Node>q=new LinkedList<>();\n q.add(root);\n while(q.isEmpty()==false){\n int size=q.size();\n for(int i=0;i<size;i++){\n Node curr=q.poll();\n if(i==0){\n arr.add(curr.data);\n }\n if(curr.left!=null)q.add(curr.left);\n if(curr.right!=null)q.add(curr.right);\n }\n }\n return arr;"
},
{
"code": null,
"e": 3484,
"s": 3482,
"text": "0"
},
{
"code": null,
"e": 3501,
"s": 3484,
"text": "iamtkarthikreddy"
},
{
"code": null,
"e": 3527,
"s": 3501,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3529,
"s": 3527,
"text": "0"
},
{
"code": null,
"e": 3545,
"s": 3529,
"text": "osamu1 week ago"
},
{
"code": null,
"e": 4566,
"s": 3545,
"text": "vector<int> leftView(Node *root){ // Your code here vector<int> ans; if(!root) return ans; queue<pair<Node*,int>> q; // Store Node and level q.push({root,0}); map<int,int> mp; //store level and value at that level while(!q.empty()) { auto it= q.front(); q.pop(); Node* curr=it.first; int lev=it.second; if(mp.count(lev)==0) // in this condition it will check if on that level there exist an element than it will not work else it will insert a value at that key making its count as 1 so after next time it will not work { mp[lev]=curr->data; } if(curr->left) { int temp=lev+1; q.push({curr->left,temp}); } if(curr->right) { int temp=lev+1; q.push({curr->right,temp}); } } for(auto it: mp) { ans.push_back(it.second); } return ans;}"
},
{
"code": null,
"e": 4817,
"s": 4568,
"text": "//Basically what are we doing is we are making a queue of pair<Node*,int> where here int will be the level as its left view so if any level is counter first during bfs we will make it put in map in which map will have key as level and value as data"
},
{
"code": null,
"e": 4820,
"s": 4817,
"text": "+3"
},
{
"code": null,
"e": 4845,
"s": 4820,
"text": "bipulharsh1232 weeks ago"
},
{
"code": null,
"e": 5086,
"s": 4845,
"text": "void getLeftView(Node *ptr, vector<int>&result, int level=1){ if(!ptr) return; if(level > result.scd ize()) result.push_back(ptr->data); getLeftView(ptr->left, result, level+1); getLeftView(ptr->right, result, level+1);}"
},
{
"code": null,
"e": 5306,
"s": 5086,
"text": "//Function to return a list containing elements of left view of the binary tree.vector<int> leftView(Node *root){ // Your code here vector<int> result; int level=1; getLeftView(root, result, level); return result;}"
},
{
"code": null,
"e": 5309,
"s": 5306,
"text": "+2"
},
{
"code": null,
"e": 5334,
"s": 5309,
"text": "jainmuskan5652 weeks ago"
},
{
"code": null,
"e": 5692,
"s": 5334,
"text": "vector<int>v;void fxn(Node* node, int level){ if(node== NULL){ return; } if(v.size()<= level){ v.push_back(node->data); } fxn(node->left, level+1); fxn(node->right, level+1);}vector<int> leftView(Node *root){ // left side view // first node of every level // traversing left root right <-- v.clear(); fxn(root,0); return v; }"
},
{
"code": null,
"e": 5694,
"s": 5692,
"text": "0"
},
{
"code": null,
"e": 5721,
"s": 5694,
"text": "mkbastronaut4412 weeks ago"
},
{
"code": null,
"e": 6124,
"s": 5721,
"text": "vector<int> leftView(Node *root){ // Your code here //Your code here if(root==NULL) return {}; queue<Node*>q; vector<int> v; q.push(root); while(!q.empty()){ int n=q.size(); for(int i=0;i<n;i++){ Node*t=q.front(); q.pop(); if(i==0) v.push_back(t->data); if(t->left) q.push(t->left); if(t->right)q.push(t->right); } } return v;"
},
{
"code": null,
"e": 6126,
"s": 6124,
"text": "0"
},
{
"code": null,
"e": 6152,
"s": 6126,
"text": "jatin2k19ec0822 weeks ago"
},
{
"code": null,
"e": 6751,
"s": 6152,
"text": "int height(Node* root){ if(root==NULL) return 0; int lh=height(root->left); int rh=height(root->right); if(lh>rh) return lh+1; else return rh+1;}int left(Node* root,int level){ if(root==NULL) return 0; if(level==1) { if(root==NULL) return 0; else return root->data; } int k=left(root->left,level-1); if(k==0) return left(root->right,level-1); else return k;}vector<int> leftView(Node *root){ // Your code here vector<int>arr; int h=height(root); for(int i=1;i<=h;i++) { int j=left(root,i); arr.push_back(j); } return arr;}"
},
{
"code": null,
"e": 6897,
"s": 6751,
"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": 6933,
"s": 6897,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6943,
"s": 6933,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6953,
"s": 6943,
"text": "\nContest\n"
},
{
"code": null,
"e": 7016,
"s": 6953,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7164,
"s": 7016,
"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": 7372,
"s": 7164,
"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": 7478,
"s": 7372,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Find the largest pair sum in an unsorted array - GeeksforGeeks
|
12 Aug, 2021
Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum in {12, 34, 10, 6, 40} is 74.Difficulty Level: Rookie Expected Time Complexity: O(n) [Only one traversal of an array is allowed]
This problem mainly boils down to finding the largest and second-largest element in an array. We can find the largest and second-largest in O(n) time by traversing the array once.
1) Initialize the
first = Integer.MIN_VALUE
second = Integer.MIN_VALUE
2) Loop through the elements
a) If the current element is greater than the first max element, then update second max to the first
max and update the first max to the current element.
3) Return (first + second)
Below is the implementation of the above algorithm:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find largest pair sum in a given array#include <iostream>using namespace std; /* Function to return largest pair sum. Assumes that there are at-least two elements in arr[] */int findLargestSumPair(int arr[], int n){ // Initialize first and second largest element int first, second; if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } // Traverse remaining array and find first and second // largest elements in overall array for (int i = 2; i < n; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then * update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } return (first + second);} /* Driver program to test above function */int main(){ int arr[] = { 12, 34, 10, 6, 40 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Max Pair Sum is " << findLargestSumPair(arr, n); return 0;}
public class LargestPairSum { public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = { 12, 34, 10, 6, 40}; System.out.println(largestPairSum(arr, arr.length)); } private static int largestPairSum(int[] arr, int n) { int j = 0; int max = n == 1 ? arr[0] + arr[1] : arr[0]; for (int i = 0; i < n; i++) { int sum = arr[j] + arr[i]; if (sum > max) { max = sum; if (arr[j] < arr[i]) { j = i; } } } return max; }}/** * This code is contributed by Tanveer Baba */
# Python3 program to find largest# pair sum in a given array # Function to return largest pair# sum. Assumes that there are# at-least two elements in arr[] def findLargestSumPair(arr, n): # Initialize first and second # largest element if arr[0] > arr[1]: first = arr[0] second = arr[1] else: first = arr[1] second = arr[0] # Traverse remaining array and # find first and second largest # elements in overall array for i in range(2, n): # If current element is greater # than first then update both # first and second if arr[i] > first: second = first first = arr[i] # If arr[i] is in between first # and second then update second elif arr[i] > second and arr[i] != first: second = arr[i] return (first + second) # Driver program to test above function */arr = [12, 34, 10, 6, 40]n = len(arr)print("Max Pair Sum is", findLargestSumPair(arr, n)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find largest// pair sum in a given arrayusing System; class GFG { /* Method to return largest pair sum. Assumes that there are at-least two elements in arr[] */ static int findLargestSumPair(int[] arr) { // Initialize first and // second largest element int first, second; if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } // Traverse remaining array and // find first and second largest // elements in overall array for (int i = 2; i < arr.Length; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } return (first + second); } // Driver Code public static void Main() { int[] arr1 = new int[] { 12, 34, 10, 6, 40 }; Console.Write("Max Pair Sum is " + findLargestSumPair(arr1)); }}
<?php// PHP program to find largest// pair sum in a given array // Function to return largest// pair sum. Assumes that// there are at-least two// elements in arr[] */function findLargestSumPair($arr, $n){ // Initialize first and // second largest element $first; $second; if ($arr[0] > $arr[1]) { $first = $arr[0]; $second = $arr[1]; } else { $first = $arr[1]; $second = $arr[0]; } // Traverse remaining array // and find first and second // largest elements in overall // array for ( $i = 2; $i<$n; $i ++) { // If current element is greater // than first then update both // first and second if ($arr[$i] > $first) { $second = $first; $first = $arr[$i]; } // If arr[i] is in between first // and second then update second else if ($arr[$i] > $second and $arr[$i] != $first) $second = $arr[$i]; } return ($first + $second);} // Driver Code $arr = array(12, 34, 10, 6, 40); $n = count($arr); echo "Max Pair Sum is " , findLargestSumPair($arr, $n); // This code is contributed by anuj_67.?>
<script> // Javascript program to find largest // pair sum in a given array /* Method to return largest pair sum. Assumes that there are at-least two elements in arr[] */ function findLargestSumPair(arr) { // Initialize first and // second largest element let first, second; if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } // Traverse remaining array and // find first and second largest // elements in overall array for (let i = 2; i < arr.length; i ++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } return (first + second); } let arr1 = [12, 34, 10, 6, 40]; document.write("Max Pair Sum is " + findLargestSumPair(arr1)); // This code is contributed by divyeshrabadiy07.</script>
Max Pair Sum is 74
The time complexity of the above solution is O(n).The space complexity of the above solution is O(1).
This article is contributed by Rishabh and improved by Akshita Patel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
vt_m
divyeshrabadiya07
akshitapatel02
tanveerbaba30
lovishtater
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find largest element in an array
k largest(or smallest) elements in an array
Search an element in a sorted and rotated array
Given an array of size n and a number k, find all elements that appear more than n/k times
Find the index of an array element in Java
Most frequent element in an array
Two Pointers Technique
Count number of occurrences (or frequency) in a sorted array
Best First Search (Informed Search)
|
[
{
"code": null,
"e": 25152,
"s": 25124,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 25389,
"s": 25152,
"text": "Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum in {12, 34, 10, 6, 40} is 74.Difficulty Level: Rookie Expected Time Complexity: O(n) [Only one traversal of an array is allowed] "
},
{
"code": null,
"e": 25571,
"s": 25389,
"text": "This problem mainly boils down to finding the largest and second-largest element in an array. We can find the largest and second-largest in O(n) time by traversing the array once. "
},
{
"code": null,
"e": 25874,
"s": 25571,
"text": "1) Initialize the \n first = Integer.MIN_VALUE\n second = Integer.MIN_VALUE\n2) Loop through the elements\n a) If the current element is greater than the first max element, then update second max to the first \n max and update the first max to the current element. \n3) Return (first + second)"
},
{
"code": null,
"e": 25928,
"s": 25874,
"text": "Below is the implementation of the above algorithm: "
},
{
"code": null,
"e": 25932,
"s": 25928,
"text": "C++"
},
{
"code": null,
"e": 25937,
"s": 25932,
"text": "Java"
},
{
"code": null,
"e": 25945,
"s": 25937,
"text": "Python3"
},
{
"code": null,
"e": 25948,
"s": 25945,
"text": "C#"
},
{
"code": null,
"e": 25952,
"s": 25948,
"text": "PHP"
},
{
"code": null,
"e": 25963,
"s": 25952,
"text": "Javascript"
},
{
"code": "// C++ program to find largest pair sum in a given array#include <iostream>using namespace std; /* Function to return largest pair sum. Assumes that there are at-least two elements in arr[] */int findLargestSumPair(int arr[], int n){ // Initialize first and second largest element int first, second; if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } // Traverse remaining array and find first and second // largest elements in overall array for (int i = 2; i < n; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then * update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } return (first + second);} /* Driver program to test above function */int main(){ int arr[] = { 12, 34, 10, 6, 40 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Max Pair Sum is \" << findLargestSumPair(arr, n); return 0;}",
"e": 27148,
"s": 25963,
"text": null
},
{
"code": "public class LargestPairSum { public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = { 12, 34, 10, 6, 40}; System.out.println(largestPairSum(arr, arr.length)); } private static int largestPairSum(int[] arr, int n) { int j = 0; int max = n == 1 ? arr[0] + arr[1] : arr[0]; for (int i = 0; i < n; i++) { int sum = arr[j] + arr[i]; if (sum > max) { max = sum; if (arr[j] < arr[i]) { j = i; } } } return max; }}/** * This code is contributed by Tanveer Baba */",
"e": 27812,
"s": 27148,
"text": null
},
{
"code": "# Python3 program to find largest# pair sum in a given array # Function to return largest pair# sum. Assumes that there are# at-least two elements in arr[] def findLargestSumPair(arr, n): # Initialize first and second # largest element if arr[0] > arr[1]: first = arr[0] second = arr[1] else: first = arr[1] second = arr[0] # Traverse remaining array and # find first and second largest # elements in overall array for i in range(2, n): # If current element is greater # than first then update both # first and second if arr[i] > first: second = first first = arr[i] # If arr[i] is in between first # and second then update second elif arr[i] > second and arr[i] != first: second = arr[i] return (first + second) # Driver program to test above function */arr = [12, 34, 10, 6, 40]n = len(arr)print(\"Max Pair Sum is\", findLargestSumPair(arr, n)) # This code is contributed by Smitha Dinesh Semwal",
"e": 28858,
"s": 27812,
"text": null
},
{
"code": "// C# program to find largest// pair sum in a given arrayusing System; class GFG { /* Method to return largest pair sum. Assumes that there are at-least two elements in arr[] */ static int findLargestSumPair(int[] arr) { // Initialize first and // second largest element int first, second; if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } // Traverse remaining array and // find first and second largest // elements in overall array for (int i = 2; i < arr.Length; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } return (first + second); } // Driver Code public static void Main() { int[] arr1 = new int[] { 12, 34, 10, 6, 40 }; Console.Write(\"Max Pair Sum is \" + findLargestSumPair(arr1)); }}",
"e": 30173,
"s": 28858,
"text": null
},
{
"code": "<?php// PHP program to find largest// pair sum in a given array // Function to return largest// pair sum. Assumes that// there are at-least two// elements in arr[] */function findLargestSumPair($arr, $n){ // Initialize first and // second largest element $first; $second; if ($arr[0] > $arr[1]) { $first = $arr[0]; $second = $arr[1]; } else { $first = $arr[1]; $second = $arr[0]; } // Traverse remaining array // and find first and second // largest elements in overall // array for ( $i = 2; $i<$n; $i ++) { // If current element is greater // than first then update both // first and second if ($arr[$i] > $first) { $second = $first; $first = $arr[$i]; } // If arr[i] is in between first // and second then update second else if ($arr[$i] > $second and $arr[$i] != $first) $second = $arr[$i]; } return ($first + $second);} // Driver Code $arr = array(12, 34, 10, 6, 40); $n = count($arr); echo \"Max Pair Sum is \" , findLargestSumPair($arr, $n); // This code is contributed by anuj_67.?>",
"e": 31399,
"s": 30173,
"text": null
},
{
"code": "<script> // Javascript program to find largest // pair sum in a given array /* Method to return largest pair sum. Assumes that there are at-least two elements in arr[] */ function findLargestSumPair(arr) { // Initialize first and // second largest element let first, second; if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } // Traverse remaining array and // find first and second largest // elements in overall array for (let i = 2; i < arr.length; i ++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } return (first + second); } let arr1 = [12, 34, 10, 6, 40]; document.write(\"Max Pair Sum is \" + findLargestSumPair(arr1)); // This code is contributed by divyeshrabadiy07.</script>",
"e": 32749,
"s": 31399,
"text": null
},
{
"code": null,
"e": 32768,
"s": 32749,
"text": "Max Pair Sum is 74"
},
{
"code": null,
"e": 32870,
"s": 32768,
"text": "The time complexity of the above solution is O(n).The space complexity of the above solution is O(1)."
},
{
"code": null,
"e": 33065,
"s": 32870,
"text": "This article is contributed by Rishabh and improved by Akshita Patel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 33078,
"s": 33065,
"text": "nitin mittal"
},
{
"code": null,
"e": 33083,
"s": 33078,
"text": "vt_m"
},
{
"code": null,
"e": 33101,
"s": 33083,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33116,
"s": 33101,
"text": "akshitapatel02"
},
{
"code": null,
"e": 33130,
"s": 33116,
"text": "tanveerbaba30"
},
{
"code": null,
"e": 33142,
"s": 33130,
"text": "lovishtater"
},
{
"code": null,
"e": 33152,
"s": 33142,
"text": "Searching"
},
{
"code": null,
"e": 33162,
"s": 33152,
"text": "Searching"
},
{
"code": null,
"e": 33260,
"s": 33162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33269,
"s": 33260,
"text": "Comments"
},
{
"code": null,
"e": 33282,
"s": 33269,
"text": "Old Comments"
},
{
"code": null,
"e": 33326,
"s": 33282,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 33370,
"s": 33326,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 33418,
"s": 33370,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 33509,
"s": 33418,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 33552,
"s": 33509,
"text": "Find the index of an array element in Java"
},
{
"code": null,
"e": 33586,
"s": 33552,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 33609,
"s": 33586,
"text": "Two Pointers Technique"
},
{
"code": null,
"e": 33670,
"s": 33609,
"text": "Count number of occurrences (or frequency) in a sorted array"
}
] |
What is the difference between String.valueOf() and toString() in Java?
|
The toString() method of the String class returns itself a string.
Live Demo
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :");
System.out.println(Str.toString());
}
}
Return Value :Welcome to Tutorialspoint.com
The value of method variants of the String class accepts different variables such as integer, float, boolean etc.. and converts them into String.
Live Demo
public class Sample {
public static void main(String args[]){
int i = 200;
float f = 12.0f;
char c = 's';
char[] ch = {'h', 'e', 'l', 'l', 'o'};
String data = String.valueOf(i);
System.out.println(String.valueOf(i));
System.out.println(String.valueOf(f));
System.out.println(String.valueOf(c));
System.out.println(String.valueOf(ch));
}
}
200
12.0
s
hello
|
[
{
"code": null,
"e": 1254,
"s": 1187,
"text": "The toString() method of the String class returns itself a string."
},
{
"code": null,
"e": 1264,
"s": 1254,
"text": "Live Demo"
},
{
"code": null,
"e": 1501,
"s": 1264,
"text": "import java.io.*;\npublic class Test {\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n System.out.print(\"Return Value :\");\n System.out.println(Str.toString());\n }\n}"
},
{
"code": null,
"e": 1545,
"s": 1501,
"text": "Return Value :Welcome to Tutorialspoint.com"
},
{
"code": null,
"e": 1691,
"s": 1545,
"text": "The value of method variants of the String class accepts different variables such as integer, float, boolean etc.. and converts them into String."
},
{
"code": null,
"e": 1701,
"s": 1691,
"text": "Live Demo"
},
{
"code": null,
"e": 2100,
"s": 1701,
"text": "public class Sample {\n public static void main(String args[]){\n int i = 200;\n float f = 12.0f;\n char c = 's';\n char[] ch = {'h', 'e', 'l', 'l', 'o'};\n String data = String.valueOf(i);\n System.out.println(String.valueOf(i));\n System.out.println(String.valueOf(f));\n System.out.println(String.valueOf(c));\n System.out.println(String.valueOf(ch));\n }\n}"
},
{
"code": null,
"e": 2117,
"s": 2100,
"text": "200\n12.0\ns\nhello"
}
] |
GATE | GATE-CS-2014-(Set-1) | Question 65
|
10 Nov, 2021
A machine has a 32-bit architecture, with 1-word long instructions. It has 64 registers, each of which is 32 bits long. It needs to support 45 instructions, which have an immediate operand in addition to two register operands. Assuming that the immediate operand is an unsigned integer, the maximum value of the immediate operand is ____________.(A) 16383(B) 16338(C) 16388(D) 16484Answer: (A)Explanation:
1 Word = 32 bits
Each instruction has 32 bits. To support 45 instructions, opcode must contain 6-bits
Register operand1 requires 6 bits, since the total registers are 64. Register operand 2 also requires 6 bits. So total 18 bits for all 45 instruction and two register operands. So
32-18 = 14
14-bits are left over for immediate Operand Using 14-bits, now
2^14 - 1 = 16383
We can give maximum 16383.
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=luB_5ufimJg" 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
Akhilesh_Raturi
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
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-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 1996 | Question 63
GATE | Gate IT 2005 | Question 52
GATE | GATE CS 2012 | Question 18
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2001 | Question 50
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 434,
"s": 28,
"text": "A machine has a 32-bit architecture, with 1-word long instructions. It has 64 registers, each of which is 32 bits long. It needs to support 45 instructions, which have an immediate operand in addition to two register operands. Assuming that the immediate operand is an unsigned integer, the maximum value of the immediate operand is ____________.(A) 16383(B) 16338(C) 16388(D) 16484Answer: (A)Explanation:"
},
{
"code": null,
"e": 452,
"s": 434,
"text": "1 Word = 32 bits "
},
{
"code": null,
"e": 537,
"s": 452,
"text": "Each instruction has 32 bits. To support 45 instructions, opcode must contain 6-bits"
},
{
"code": null,
"e": 717,
"s": 537,
"text": "Register operand1 requires 6 bits, since the total registers are 64. Register operand 2 also requires 6 bits. So total 18 bits for all 45 instruction and two register operands. So"
},
{
"code": null,
"e": 729,
"s": 717,
"text": "32-18 = 14 "
},
{
"code": null,
"e": 792,
"s": 729,
"text": "14-bits are left over for immediate Operand Using 14-bits, now"
},
{
"code": null,
"e": 810,
"s": 792,
"text": "2^14 - 1 = 16383 "
},
{
"code": null,
"e": 837,
"s": 810,
"text": "We can give maximum 16383."
},
{
"code": null,
"e": 1150,
"s": 837,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=luB_5ufimJg\" 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": 1166,
"s": 1150,
"text": "Akhilesh_Raturi"
},
{
"code": null,
"e": 1187,
"s": 1166,
"text": "GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 1213,
"s": 1187,
"text": "GATE-GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 1218,
"s": 1213,
"text": "GATE"
},
{
"code": null,
"e": 1316,
"s": 1218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1358,
"s": 1316,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1420,
"s": 1358,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1462,
"s": 1420,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1504,
"s": 1462,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1538,
"s": 1504,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1572,
"s": 1538,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1606,
"s": 1572,
"text": "GATE | Gate IT 2005 | Question 52"
},
{
"code": null,
"e": 1640,
"s": 1606,
"text": "GATE | GATE CS 2012 | Question 18"
},
{
"code": null,
"e": 1674,
"s": 1640,
"text": "GATE | GATE CS 2008 | Question 40"
}
] |
Palindrome Substring Queries
|
04 Jul, 2022
Given a string and several queries on the substrings of the given input string to check whether the substring is a palindrome or not.
Examples :
Suppose our input string is “abaaabaaaba” and the queries- [0, 10], [5, 8], [2, 5], [5, 9]We have to tell that the substring having the starting and ending indices as above is a palindrome or not.[0, 10] → Substring is “abaaabaaaba” which is a palindrome. [5, 8] → Substring is “baaa” which is not a palindrome. [2, 5] → Substring is “aaab” which is not a palindrome. [5, 9] → Substring is “baaab” which is a palindrome.
Let us assume that there are Q such queries to be answered and N be the length of our input string. There are the following two ways to answer these queries
Method 1 (Naive) :
One by one we go through all the substrings of the queries and check whether the substring under consideration is a palindrome or not.Since there are Q queries and each query can take O(N) worse case time to answer, this method takes O(Q.N) time in the worst case. Although this is an in-place/space-efficient algorithm, still there is a more efficient method to do this.
Method 2 (Cumulative Hash):
The idea is similar to Rabin Karp string matching. We use string hashing. What we do is that we calculate cumulative hash values of the string in the original string as well as the reversed string in two arrays- prefix[] and suffix[].How to calculate the cumulative hash values?Suppose our string is str[], then the cumulative hash function to fill our prefix[] array used is-
prefix[0] = 0 prefix[i] = str[0] + str[1] * 101 + str[2] * 1012 + ...... + str[i-1] * 101i-1For example, take the string- “abaaabxyaba”prefix[0] = 0 prefix[1] = 97 (ASCII Value of ‘a’ is 97) prefix[2] = 97 + 98 * 101 prefix[3] = 97 + 98 * 101 + 97 * 1012 ........................... ........................... prefix[11] = 97 + 98 * 101 + 97 * 1012 + ........+ 97 * 10110
Now the reason to store in that way is that we can easily find the hash value of any substring in O(1) time using-
hash(L, R) = prefix[R+1] – prefix[L]
For example, hash (1, 5) = hash (“baaab”) = prefix[6] – prefix[1] = 98 * 101 + 97 * 1012 + 97 * 1013 + 97 * 1014 + 98 * 1015 = 1040184646587 [We will use this weird value later to explain what’s happening].Similar to this we will fill our suffix[] array as-
suffix[0] = 0 suffix[i] = str[n-1] + str[n-2] * 1011 + str[n-3] * 1012 + ...... + str[n-i] * 101i-1For example, take the string- “abaaabxyaba”suffix[0] = 0 suffix[1] = 97 (ASCII Value of ‘a’ is 97) suffix[2] = 97 + 98 * 101 suffix[3] = 97 + 98 * 101 + 97 * 1012 ........................... ........................... suffix[11] = 97 + 98 * 101 + 97 * 1012 + ........+ 97 * 10110Now the reason to store in that way is that we can easily find the reverse hash value of any substring in O(1) time using
reverse_hash(L, R) = hash (R, L) = suffix[n-L] – suffix[n-R-1]
where n = length of string.
For “abaaabxyaba”, n = 11 reverse_hash(1, 5) = reverse_hash(“baaab”) = hash(“baaab”) [Reversing “baaab” gives “baaab”]hash(“baaab”) = suffix[11-1] – suffix[11-5-1] = suffix[10] – suffix[5] = 98 * 1015 + 97 * 1016 + 97 * 1017 + 97 * 1018 + 98 * 1019 = 108242031437886501387
Now there doesn’t seem to be any relationship between these two weird integers – 1040184646587 and 108242031437886501387 Think again. Is there any relation between these two massive integers ?Yes, there is and this observation is the core of this program/article.
1040184646587 * 1014 = 108242031437886501387
Try thinking about this and you will find that any substring starting at index- L and ending at index- R (both inclusive) will be a palindrome if
(prefix[R + 1] – prefix[L]) / (101L) = (suffix [n – L] – suffix [n – R- 1] ) / (101n – R – 1)
The rest part is just implementation.The function computerPowers() in the program computes the powers of 101 using dynamic programming.
Overflow Issues:
As, we can see that the hash values and the reverse hash values can become huge for even the small strings of length – 8. Since C and C++ doesn’t provide support for such large numbers, so it will cause overflows. To avoid this we will take modulo of a prime (a prime number is chosen for some specific mathematical reasons). We choose the biggest possible prime which fits in an integer value. The best such value is 1000000007. Hence all the operations are done modulo 1000000007.However, Java and Python has no such issues and can be implemented without the modulo operator.The fundamental modulo operations which are used extensively in the program are listed below.
1) Addition-
(a + b) %M = (a %M + b % M) % M (a + b + c) % M = (a % M + b % M + c % M) % M (a + b + c + d) % M = (a % M + b % M + c % M+ d% M) % M .... ..... ..... ...... .... ..... ..... ......
2) Multiplication-
(a * b) % M = (a * b) % M (a * b * c) % M = ((a * b) % M * c % M) % M (a * b * c * d) % M = ((((a * b) % M * c) % M) * d) % M .... ..... ..... ...... .... ..... ..... ......
This property is used by modPow() function which computes power of a number modulo M
3) Mixture of addition and multiplication-
(a * x + b * y + c) % M = ( (a * x) % M +(b * y) % M+ c % M ) % M
4) Subtraction-
(a – b) % M = (a % M – b % M + M) % M [Correct] (a – b) % M = (a % M – b % M) % M [Wrong]
5) Division-
(a / b) % M = (a * MMI(b)) % MWhere MMI() is a function to calculate Modulo Multiplicative Inverse. In our program this is implemented by the function- findMMI().
Implementation of the above approach:
C++
Java
C#
/* A C++ program to answer queries to check whetherthe substrings are palindrome or not efficiently */#include <bits/stdc++.h>using namespace std; #define p 101#define MOD 1000000007 // Structure to represent a query. A query consists// of (L, R) and we have to answer whether the substring// from index-L to R is a palindrome or notstruct Query { int L, R;}; // A function to check if a string str is palindrome// in the range L to Rbool isPalindrome(string str, int L, int R){ // Keep comparing characters while they are same while (R > L) if (str[L++] != str[R--]) return (false); return (true);} // A Function to find pow (base, exponent) % MOD// in log (exponent) timeunsigned long long int modPow( unsigned long long int base, unsigned long long int exponent){ if (exponent == 0) return 1; if (exponent == 1) return base; unsigned long long int temp = modPow(base, exponent / 2); if (exponent % 2 == 0) return (temp % MOD * temp % MOD) % MOD; else return (((temp % MOD * temp % MOD) % MOD) * base % MOD) % MOD;} // A Function to calculate Modulo Multiplicative Inverse of 'n'unsigned long long int findMMI(unsigned long long int n){ return modPow(n, MOD - 2);} // A Function to calculate the prefix hashvoid computePrefixHash( string str, int n, unsigned long long int prefix[], unsigned long long int power[]){ prefix[0] = 0; prefix[1] = str[0]; for (int i = 2; i <= n; i++) prefix[i] = (prefix[i - 1] % MOD + (str[i - 1] % MOD * power[i - 1] % MOD) % MOD) % MOD; return;} // A Function to calculate the suffix hash// Suffix hash is nothing but the prefix hash of// the reversed stringvoid computeSuffixHash( string str, int n, unsigned long long int suffix[], unsigned long long int power[]){ suffix[0] = 0; suffix[1] = str[n - 1]; for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) suffix[j] = (suffix[j - 1] % MOD + (str[i] % MOD * power[j - 1] % MOD) % MOD) % MOD; return;} // A Function to answer the Queriesvoid queryResults(string str, Query q[], int m, int n, unsigned long long int prefix[], unsigned long long int suffix[], unsigned long long int power[]){ for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] unsigned long long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] unsigned long long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then // the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) printf("The Substring [%d %d] is a " "palindrome\n", L, R); else printf("The Substring [%d %d] is not a " "palindrome\n", L, R); } else printf("The Substring [%d %d] is not a " "palindrome\n", L, R); } return;} // A Dynamic Programming Based Approach to compute the// powers of 101void computePowers(unsigned long long int power[], int n){ // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) power[i] = (power[i - 1] % MOD * p % MOD) % MOD; return;} /* Driver program to test above function */int main(){ string str = "abaaabaaaba"; int n = str.length(); // A Table to store the powers of 101 unsigned long long int power[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values unsigned long long int prefix[n + 1], suffix[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query q[] = { { 0, 10 }, { 5, 8 }, { 2, 5 }, { 5, 9 } }; int m = sizeof(q) / sizeof(q[0]); queryResults(str, q, m, n, prefix, suffix, power); return (0);}
/* A Java program to answer queries to check whetherthe substrings are palindrome or not efficiently */ public class GFG { static int p = 101; static int MOD = 1000000007; // Structure to represent a query. A query consists // of (L, R) and we have to answer whether the substring // from index-L to R is a palindrome or not static class Query { int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // A function to check if a string str is palindrome // in the ranfe L to R static boolean isPalindrome(String str, int L, int R) { // Keep comparing characters while they are same while (R > L) { if (str.charAt(L++) != str.charAt(R--)) { return (false); } } return (true); } // A Function to find pow (base, exponent) % MOD // in log (exponent) time static int modPow(int base, int exponent) { if (exponent == 0) { return 1; } if (exponent == 1) { return base; } int temp = modPow(base, exponent / 2); if (exponent % 2 == 0) { return (temp % MOD * temp % MOD) % MOD; } else { return (((temp % MOD * temp % MOD) % MOD) * base % MOD) % MOD; } } // A Function to calculate // Modulo Multiplicative Inverse of 'n' static int findMMI(int n) { return modPow(n, MOD - 2); } // A Function to calculate the prefix hash static void computePrefixHash(String str, int n, int prefix[], int power[]) { prefix[0] = 0; prefix[1] = str.charAt(0); for (int i = 2; i <= n; i++) { prefix[i] = (prefix[i - 1] % MOD + (str.charAt(i - 1) % MOD * power[i - 1] % MOD) % MOD) % MOD; } return; } // A Function to calculate the suffix hash // Suffix hash is nothing but the prefix hash of // the reversed string static void computeSuffixHash(String str, int n, int suffix[], int power[]) { suffix[0] = 0; suffix[1] = str.charAt(n - 1); for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) { suffix[j] = (suffix[j - 1] % MOD + (str.charAt(i) % MOD * power[j - 1] % MOD) % MOD) % MOD; } return; } // A Function to answer the Queries static void queryResults( String str, Query q[], int m, int n, int prefix[], int suffix[], int power[]) { for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) { System.out.printf("The Substring [%d %d] is a " + "palindrome\n", L, R); } else { System.out.printf("The Substring [%d %d] is not a " + "palindrome\n", L, R); } } else { System.out.printf("The Substring [%d %d] is not a " + "palindrome\n", L, R); } } return; } // A Dynamic Programming Based Approach to compute the // powers of 101 static void computePowers(int power[], int n) { // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) { power[i] = (power[i - 1] % MOD * p % MOD) % MOD; } return; } /* Driver code */ public static void main(String[] args) { String str = "abaaabaaaba"; int n = str.length(); // A Table to store the powers of 101 int[] power = new int[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values int[] prefix = new int[n + 1]; int[] suffix = new int[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query q[] = { new Query(0, 10), new Query(5, 8), new Query(2, 5), new Query(5, 9) }; int m = q.length; queryResults(str, q, m, n, prefix, suffix, power); }} // This code is contributed by Princi Singh
/* A C# program to answer queries to check whetherthe substrings are palindrome or not efficiently */using System; class GFG { static int p = 101; static int MOD = 1000000007; // Structure to represent a query. A query consists // of (L, R) and we have to answer whether the substring // from index-L to R is a palindrome or not public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // A function to check if a string str is palindrome // in the ranfe L to R static Boolean isPalindrome(String str, int L, int R) { // Keep comparing characters while they are same while (R > L) { if (str[L++] != str[R--]) { return (false); } } return (true); } // A Function to find pow (base, exponent) % MOD // in log (exponent) time static int modPow(int Base, int exponent) { if (exponent == 0) { return 1; } if (exponent == 1) { return Base; } int temp = modPow(Base, exponent / 2); if (exponent % 2 == 0) { return (temp % MOD * temp % MOD) % MOD; } else { return (((temp % MOD * temp % MOD) % MOD) * Base % MOD) % MOD; } } // A Function to calculate Modulo Multiplicative Inverse of 'n' static int findMMI(int n) { return modPow(n, MOD - 2); } // A Function to calculate the prefix hash static void computePrefixHash(String str, int n, int[] prefix, int[] power) { prefix[0] = 0; prefix[1] = str[0]; for (int i = 2; i <= n; i++) { prefix[i] = (prefix[i - 1] % MOD + (str[i - 1] % MOD * power[i - 1] % MOD) % MOD) % MOD; } return; } // A Function to calculate the suffix hash // Suffix hash is nothing but the prefix hash of // the reversed string static void computeSuffixHash(String str, int n, int[] suffix, int[] power) { suffix[0] = 0; suffix[1] = str[n - 1]; for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) { suffix[j] = (suffix[j - 1] % MOD + (str[i] % MOD * power[j - 1] % MOD) % MOD) % MOD; } return; } // A Function to answer the Queries static void queryResults(String str, Query[] q, int m, int n, int[] prefix, int[] suffix, int[] power) { for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) { Console.Write("The Substring [{0} {1}] is a " + "palindrome\n", L, R); } else { Console.Write("The Substring [{0} {1}] is not a " + "palindrome\n", L, R); } } else { Console.Write("The Substring [{0} {1}] is not a " + "palindrome\n", L, R); } } return; } // A Dynamic Programming Based Approach to compute the // powers of 101 static void computePowers(int[] power, int n) { // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) { power[i] = (power[i - 1] % MOD * p % MOD) % MOD; } return; } /* Driver code */ public static void Main(String[] args) { String str = "abaaabaaaba"; int n = str.Length; // A Table to store the powers of 101 int[] power = new int[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values int[] prefix = new int[n + 1]; int[] suffix = new int[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query[] q = { new Query(0, 10), new Query(5, 8), new Query(2, 5), new Query(5, 9) }; int m = q.Length; queryResults(str, q, m, n, prefix, suffix, power); }} // This code is contributed by Rajput-Ji
The Substring [0 10] is a palindrome
The Substring [5 8] is not a palindrome
The Substring [2 5] is not a palindrome
The Substring [5 9] is a palindrome
Time complexity: O(n*m) where m is the number of queries and n is the length of the string.Auxiliary Space: O(n)
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.
princi singh
Rajput-Ji
naithanipkpiyush
nikhilis18
rkbhola5
riya55
hardikkoriintern
palindrome
substring
Dynamic Programming
Hash
Strings
Hash
Strings
Dynamic Programming
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Count pairs with given sum
Longest Consecutive Subsequence
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 186,
"s": 52,
"text": "Given a string and several queries on the substrings of the given input string to check whether the substring is a palindrome or not."
},
{
"code": null,
"e": 198,
"s": 186,
"text": "Examples : "
},
{
"code": null,
"e": 621,
"s": 198,
"text": "Suppose our input string is “abaaabaaaba” and the queries- [0, 10], [5, 8], [2, 5], [5, 9]We have to tell that the substring having the starting and ending indices as above is a palindrome or not.[0, 10] → Substring is “abaaabaaaba” which is a palindrome. [5, 8] → Substring is “baaa” which is not a palindrome. [2, 5] → Substring is “aaab” which is not a palindrome. [5, 9] → Substring is “baaab” which is a palindrome. "
},
{
"code": null,
"e": 779,
"s": 621,
"text": "Let us assume that there are Q such queries to be answered and N be the length of our input string. There are the following two ways to answer these queries "
},
{
"code": null,
"e": 798,
"s": 779,
"text": "Method 1 (Naive) :"
},
{
"code": null,
"e": 1170,
"s": 798,
"text": "One by one we go through all the substrings of the queries and check whether the substring under consideration is a palindrome or not.Since there are Q queries and each query can take O(N) worse case time to answer, this method takes O(Q.N) time in the worst case. Although this is an in-place/space-efficient algorithm, still there is a more efficient method to do this."
},
{
"code": null,
"e": 1198,
"s": 1170,
"text": "Method 2 (Cumulative Hash):"
},
{
"code": null,
"e": 1576,
"s": 1198,
"text": "The idea is similar to Rabin Karp string matching. We use string hashing. What we do is that we calculate cumulative hash values of the string in the original string as well as the reversed string in two arrays- prefix[] and suffix[].How to calculate the cumulative hash values?Suppose our string is str[], then the cumulative hash function to fill our prefix[] array used is- "
},
{
"code": null,
"e": 1950,
"s": 1576,
"text": "prefix[0] = 0 prefix[i] = str[0] + str[1] * 101 + str[2] * 1012 + ...... + str[i-1] * 101i-1For example, take the string- “abaaabxyaba”prefix[0] = 0 prefix[1] = 97 (ASCII Value of ‘a’ is 97) prefix[2] = 97 + 98 * 101 prefix[3] = 97 + 98 * 101 + 97 * 1012 ........................... ........................... prefix[11] = 97 + 98 * 101 + 97 * 1012 + ........+ 97 * 10110 "
},
{
"code": null,
"e": 2066,
"s": 1950,
"text": "Now the reason to store in that way is that we can easily find the hash value of any substring in O(1) time using- "
},
{
"code": null,
"e": 2104,
"s": 2066,
"text": " hash(L, R) = prefix[R+1] – prefix[L]"
},
{
"code": null,
"e": 2363,
"s": 2104,
"text": "For example, hash (1, 5) = hash (“baaab”) = prefix[6] – prefix[1] = 98 * 101 + 97 * 1012 + 97 * 1013 + 97 * 1014 + 98 * 1015 = 1040184646587 [We will use this weird value later to explain what’s happening].Similar to this we will fill our suffix[] array as- "
},
{
"code": null,
"e": 2866,
"s": 2363,
"text": "suffix[0] = 0 suffix[i] = str[n-1] + str[n-2] * 1011 + str[n-3] * 1012 + ...... + str[n-i] * 101i-1For example, take the string- “abaaabxyaba”suffix[0] = 0 suffix[1] = 97 (ASCII Value of ‘a’ is 97) suffix[2] = 97 + 98 * 101 suffix[3] = 97 + 98 * 101 + 97 * 1012 ........................... ........................... suffix[11] = 97 + 98 * 101 + 97 * 1012 + ........+ 97 * 10110Now the reason to store in that way is that we can easily find the reverse hash value of any substring in O(1) time using "
},
{
"code": null,
"e": 2930,
"s": 2866,
"text": "reverse_hash(L, R) = hash (R, L) = suffix[n-L] – suffix[n-R-1] "
},
{
"code": null,
"e": 2959,
"s": 2930,
"text": "where n = length of string. "
},
{
"code": null,
"e": 3233,
"s": 2959,
"text": "For “abaaabxyaba”, n = 11 reverse_hash(1, 5) = reverse_hash(“baaab”) = hash(“baaab”) [Reversing “baaab” gives “baaab”]hash(“baaab”) = suffix[11-1] – suffix[11-5-1] = suffix[10] – suffix[5] = 98 * 1015 + 97 * 1016 + 97 * 1017 + 97 * 1018 + 98 * 1019 = 108242031437886501387 "
},
{
"code": null,
"e": 3498,
"s": 3233,
"text": "Now there doesn’t seem to be any relationship between these two weird integers – 1040184646587 and 108242031437886501387 Think again. Is there any relation between these two massive integers ?Yes, there is and this observation is the core of this program/article. "
},
{
"code": null,
"e": 3544,
"s": 3498,
"text": "1040184646587 * 1014 = 108242031437886501387 "
},
{
"code": null,
"e": 3692,
"s": 3544,
"text": "Try thinking about this and you will find that any substring starting at index- L and ending at index- R (both inclusive) will be a palindrome if "
},
{
"code": null,
"e": 3787,
"s": 3692,
"text": "(prefix[R + 1] – prefix[L]) / (101L) = (suffix [n – L] – suffix [n – R- 1] ) / (101n – R – 1) "
},
{
"code": null,
"e": 3923,
"s": 3787,
"text": "The rest part is just implementation.The function computerPowers() in the program computes the powers of 101 using dynamic programming."
},
{
"code": null,
"e": 3941,
"s": 3923,
"text": "Overflow Issues: "
},
{
"code": null,
"e": 4613,
"s": 3941,
"text": "As, we can see that the hash values and the reverse hash values can become huge for even the small strings of length – 8. Since C and C++ doesn’t provide support for such large numbers, so it will cause overflows. To avoid this we will take modulo of a prime (a prime number is chosen for some specific mathematical reasons). We choose the biggest possible prime which fits in an integer value. The best such value is 1000000007. Hence all the operations are done modulo 1000000007.However, Java and Python has no such issues and can be implemented without the modulo operator.The fundamental modulo operations which are used extensively in the program are listed below. "
},
{
"code": null,
"e": 4627,
"s": 4613,
"text": "1) Addition- "
},
{
"code": null,
"e": 4810,
"s": 4627,
"text": "(a + b) %M = (a %M + b % M) % M (a + b + c) % M = (a % M + b % M + c % M) % M (a + b + c + d) % M = (a % M + b % M + c % M+ d% M) % M .... ..... ..... ...... .... ..... ..... ...... "
},
{
"code": null,
"e": 4830,
"s": 4810,
"text": "2) Multiplication- "
},
{
"code": null,
"e": 5006,
"s": 4830,
"text": " (a * b) % M = (a * b) % M (a * b * c) % M = ((a * b) % M * c % M) % M (a * b * c * d) % M = ((((a * b) % M * c) % M) * d) % M .... ..... ..... ...... .... ..... ..... ...... "
},
{
"code": null,
"e": 5092,
"s": 5006,
"text": "This property is used by modPow() function which computes power of a number modulo M "
},
{
"code": null,
"e": 5136,
"s": 5092,
"text": "3) Mixture of addition and multiplication- "
},
{
"code": null,
"e": 5204,
"s": 5136,
"text": " (a * x + b * y + c) % M = ( (a * x) % M +(b * y) % M+ c % M ) % M "
},
{
"code": null,
"e": 5221,
"s": 5204,
"text": "4) Subtraction- "
},
{
"code": null,
"e": 5312,
"s": 5221,
"text": "(a – b) % M = (a % M – b % M + M) % M [Correct] (a – b) % M = (a % M – b % M) % M [Wrong] "
},
{
"code": null,
"e": 5326,
"s": 5312,
"text": "5) Division- "
},
{
"code": null,
"e": 5490,
"s": 5326,
"text": "(a / b) % M = (a * MMI(b)) % MWhere MMI() is a function to calculate Modulo Multiplicative Inverse. In our program this is implemented by the function- findMMI(). "
},
{
"code": null,
"e": 5528,
"s": 5490,
"text": "Implementation of the above approach:"
},
{
"code": null,
"e": 5532,
"s": 5528,
"text": "C++"
},
{
"code": null,
"e": 5537,
"s": 5532,
"text": "Java"
},
{
"code": null,
"e": 5540,
"s": 5537,
"text": "C#"
},
{
"code": "/* A C++ program to answer queries to check whetherthe substrings are palindrome or not efficiently */#include <bits/stdc++.h>using namespace std; #define p 101#define MOD 1000000007 // Structure to represent a query. A query consists// of (L, R) and we have to answer whether the substring// from index-L to R is a palindrome or notstruct Query { int L, R;}; // A function to check if a string str is palindrome// in the range L to Rbool isPalindrome(string str, int L, int R){ // Keep comparing characters while they are same while (R > L) if (str[L++] != str[R--]) return (false); return (true);} // A Function to find pow (base, exponent) % MOD// in log (exponent) timeunsigned long long int modPow( unsigned long long int base, unsigned long long int exponent){ if (exponent == 0) return 1; if (exponent == 1) return base; unsigned long long int temp = modPow(base, exponent / 2); if (exponent % 2 == 0) return (temp % MOD * temp % MOD) % MOD; else return (((temp % MOD * temp % MOD) % MOD) * base % MOD) % MOD;} // A Function to calculate Modulo Multiplicative Inverse of 'n'unsigned long long int findMMI(unsigned long long int n){ return modPow(n, MOD - 2);} // A Function to calculate the prefix hashvoid computePrefixHash( string str, int n, unsigned long long int prefix[], unsigned long long int power[]){ prefix[0] = 0; prefix[1] = str[0]; for (int i = 2; i <= n; i++) prefix[i] = (prefix[i - 1] % MOD + (str[i - 1] % MOD * power[i - 1] % MOD) % MOD) % MOD; return;} // A Function to calculate the suffix hash// Suffix hash is nothing but the prefix hash of// the reversed stringvoid computeSuffixHash( string str, int n, unsigned long long int suffix[], unsigned long long int power[]){ suffix[0] = 0; suffix[1] = str[n - 1]; for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) suffix[j] = (suffix[j - 1] % MOD + (str[i] % MOD * power[j - 1] % MOD) % MOD) % MOD; return;} // A Function to answer the Queriesvoid queryResults(string str, Query q[], int m, int n, unsigned long long int prefix[], unsigned long long int suffix[], unsigned long long int power[]){ for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] unsigned long long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] unsigned long long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then // the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) printf(\"The Substring [%d %d] is a \" \"palindrome\\n\", L, R); else printf(\"The Substring [%d %d] is not a \" \"palindrome\\n\", L, R); } else printf(\"The Substring [%d %d] is not a \" \"palindrome\\n\", L, R); } return;} // A Dynamic Programming Based Approach to compute the// powers of 101void computePowers(unsigned long long int power[], int n){ // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) power[i] = (power[i - 1] % MOD * p % MOD) % MOD; return;} /* Driver program to test above function */int main(){ string str = \"abaaabaaaba\"; int n = str.length(); // A Table to store the powers of 101 unsigned long long int power[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values unsigned long long int prefix[n + 1], suffix[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query q[] = { { 0, 10 }, { 5, 8 }, { 2, 5 }, { 5, 9 } }; int m = sizeof(q) / sizeof(q[0]); queryResults(str, q, m, n, prefix, suffix, power); return (0);}",
"e": 9990,
"s": 5540,
"text": null
},
{
"code": "/* A Java program to answer queries to check whetherthe substrings are palindrome or not efficiently */ public class GFG { static int p = 101; static int MOD = 1000000007; // Structure to represent a query. A query consists // of (L, R) and we have to answer whether the substring // from index-L to R is a palindrome or not static class Query { int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // A function to check if a string str is palindrome // in the ranfe L to R static boolean isPalindrome(String str, int L, int R) { // Keep comparing characters while they are same while (R > L) { if (str.charAt(L++) != str.charAt(R--)) { return (false); } } return (true); } // A Function to find pow (base, exponent) % MOD // in log (exponent) time static int modPow(int base, int exponent) { if (exponent == 0) { return 1; } if (exponent == 1) { return base; } int temp = modPow(base, exponent / 2); if (exponent % 2 == 0) { return (temp % MOD * temp % MOD) % MOD; } else { return (((temp % MOD * temp % MOD) % MOD) * base % MOD) % MOD; } } // A Function to calculate // Modulo Multiplicative Inverse of 'n' static int findMMI(int n) { return modPow(n, MOD - 2); } // A Function to calculate the prefix hash static void computePrefixHash(String str, int n, int prefix[], int power[]) { prefix[0] = 0; prefix[1] = str.charAt(0); for (int i = 2; i <= n; i++) { prefix[i] = (prefix[i - 1] % MOD + (str.charAt(i - 1) % MOD * power[i - 1] % MOD) % MOD) % MOD; } return; } // A Function to calculate the suffix hash // Suffix hash is nothing but the prefix hash of // the reversed string static void computeSuffixHash(String str, int n, int suffix[], int power[]) { suffix[0] = 0; suffix[1] = str.charAt(n - 1); for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) { suffix[j] = (suffix[j - 1] % MOD + (str.charAt(i) % MOD * power[j - 1] % MOD) % MOD) % MOD; } return; } // A Function to answer the Queries static void queryResults( String str, Query q[], int m, int n, int prefix[], int suffix[], int power[]) { for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) { System.out.printf(\"The Substring [%d %d] is a \" + \"palindrome\\n\", L, R); } else { System.out.printf(\"The Substring [%d %d] is not a \" + \"palindrome\\n\", L, R); } } else { System.out.printf(\"The Substring [%d %d] is not a \" + \"palindrome\\n\", L, R); } } return; } // A Dynamic Programming Based Approach to compute the // powers of 101 static void computePowers(int power[], int n) { // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) { power[i] = (power[i - 1] % MOD * p % MOD) % MOD; } return; } /* Driver code */ public static void main(String[] args) { String str = \"abaaabaaaba\"; int n = str.length(); // A Table to store the powers of 101 int[] power = new int[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values int[] prefix = new int[n + 1]; int[] suffix = new int[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query q[] = { new Query(0, 10), new Query(5, 8), new Query(2, 5), new Query(5, 9) }; int m = q.length; queryResults(str, q, m, n, prefix, suffix, power); }} // This code is contributed by Princi Singh",
"e": 15188,
"s": 9990,
"text": null
},
{
"code": "/* A C# program to answer queries to check whetherthe substrings are palindrome or not efficiently */using System; class GFG { static int p = 101; static int MOD = 1000000007; // Structure to represent a query. A query consists // of (L, R) and we have to answer whether the substring // from index-L to R is a palindrome or not public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // A function to check if a string str is palindrome // in the ranfe L to R static Boolean isPalindrome(String str, int L, int R) { // Keep comparing characters while they are same while (R > L) { if (str[L++] != str[R--]) { return (false); } } return (true); } // A Function to find pow (base, exponent) % MOD // in log (exponent) time static int modPow(int Base, int exponent) { if (exponent == 0) { return 1; } if (exponent == 1) { return Base; } int temp = modPow(Base, exponent / 2); if (exponent % 2 == 0) { return (temp % MOD * temp % MOD) % MOD; } else { return (((temp % MOD * temp % MOD) % MOD) * Base % MOD) % MOD; } } // A Function to calculate Modulo Multiplicative Inverse of 'n' static int findMMI(int n) { return modPow(n, MOD - 2); } // A Function to calculate the prefix hash static void computePrefixHash(String str, int n, int[] prefix, int[] power) { prefix[0] = 0; prefix[1] = str[0]; for (int i = 2; i <= n; i++) { prefix[i] = (prefix[i - 1] % MOD + (str[i - 1] % MOD * power[i - 1] % MOD) % MOD) % MOD; } return; } // A Function to calculate the suffix hash // Suffix hash is nothing but the prefix hash of // the reversed string static void computeSuffixHash(String str, int n, int[] suffix, int[] power) { suffix[0] = 0; suffix[1] = str[n - 1]; for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) { suffix[j] = (suffix[j - 1] % MOD + (str[i] % MOD * power[j - 1] % MOD) % MOD) % MOD; } return; } // A Function to answer the Queries static void queryResults(String str, Query[] q, int m, int n, int[] prefix, int[] suffix, int[] power) { for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) { Console.Write(\"The Substring [{0} {1}] is a \" + \"palindrome\\n\", L, R); } else { Console.Write(\"The Substring [{0} {1}] is not a \" + \"palindrome\\n\", L, R); } } else { Console.Write(\"The Substring [{0} {1}] is not a \" + \"palindrome\\n\", L, R); } } return; } // A Dynamic Programming Based Approach to compute the // powers of 101 static void computePowers(int[] power, int n) { // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) { power[i] = (power[i - 1] % MOD * p % MOD) % MOD; } return; } /* Driver code */ public static void Main(String[] args) { String str = \"abaaabaaaba\"; int n = str.Length; // A Table to store the powers of 101 int[] power = new int[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values int[] prefix = new int[n + 1]; int[] suffix = new int[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query[] q = { new Query(0, 10), new Query(5, 8), new Query(2, 5), new Query(5, 9) }; int m = q.Length; queryResults(str, q, m, n, prefix, suffix, power); }} // This code is contributed by Rajput-Ji",
"e": 20179,
"s": 15188,
"text": null
},
{
"code": null,
"e": 20332,
"s": 20179,
"text": "The Substring [0 10] is a palindrome\nThe Substring [5 8] is not a palindrome\nThe Substring [2 5] is not a palindrome\nThe Substring [5 9] is a palindrome"
},
{
"code": null,
"e": 20445,
"s": 20332,
"text": "Time complexity: O(n*m) where m is the number of queries and n is the length of the string.Auxiliary Space: O(n)"
},
{
"code": null,
"e": 20716,
"s": 20445,
"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."
},
{
"code": null,
"e": 20729,
"s": 20716,
"text": "princi singh"
},
{
"code": null,
"e": 20739,
"s": 20729,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 20756,
"s": 20739,
"text": "naithanipkpiyush"
},
{
"code": null,
"e": 20767,
"s": 20756,
"text": "nikhilis18"
},
{
"code": null,
"e": 20776,
"s": 20767,
"text": "rkbhola5"
},
{
"code": null,
"e": 20783,
"s": 20776,
"text": "riya55"
},
{
"code": null,
"e": 20800,
"s": 20783,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 20811,
"s": 20800,
"text": "palindrome"
},
{
"code": null,
"e": 20821,
"s": 20811,
"text": "substring"
},
{
"code": null,
"e": 20841,
"s": 20821,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 20846,
"s": 20841,
"text": "Hash"
},
{
"code": null,
"e": 20854,
"s": 20846,
"text": "Strings"
},
{
"code": null,
"e": 20859,
"s": 20854,
"text": "Hash"
},
{
"code": null,
"e": 20867,
"s": 20859,
"text": "Strings"
},
{
"code": null,
"e": 20887,
"s": 20867,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 20898,
"s": 20887,
"text": "palindrome"
},
{
"code": null,
"e": 20996,
"s": 20898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21028,
"s": 20996,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 21058,
"s": 21028,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 21087,
"s": 21058,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 21121,
"s": 21087,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 21148,
"s": 21121,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 21233,
"s": 21148,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 21271,
"s": 21233,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 21307,
"s": 21271,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 21334,
"s": 21307,
"text": "Count pairs with given sum"
}
] |
Smallest integer with digit sum M and multiple of N
|
23 Jun, 2022
Given two positive integers N and M, the task is to find the smallest positive integer which is divisible by N and whose digit sum is M. Print -1 if no such integer exists within the range of int.
Examples:
Input: N = 13, M = 32
Output: 8879
8879 is divisible by 13 and its
Sum of digits of 8879 is 8+8+7+9 = 32
i.e. equals to M
Input: N = 8, M = 32;
Output: 8888
Approach: Start with N and iterate over all the multiples of n, and check whether its digit sum is equal to m or not. This problem can be solved in logn(INT_MAX) * log10(INT_MAX) time. The efficiency of this approach can be increased by starting the iteration with a number which has at least m/9 digit.
Below is the implementation of the approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return digit sumint digitSum(int n){ int ans = 0; while (n) { ans += n % 10; n /= 10; } return ans;} // Function to find out the smallest integerint findInt(int n, int m){ int minDigit = floor(m / 9); // Start of the iterator (Smallest multiple of n) int start = pow(10, minDigit) - (int)pow(10, minDigit) % n; while (start < INT_MAX) { if (digitSum(start) == m) return start; else start += n; } return -1;} // Driver codeint main(){ int n = 13, m = 32; cout << findInt(n, m); return 0;}
// Java implementation of the above approach class GFG{ // Function to return digit sum static int digitSum(int n) { int ans = 0; while (n != 0) { ans += n % 10; n /= 10; } return ans; } // Function to find out the // smallest integer static int findInt(int n, int m) { int minDigit = (int)Math.floor((double)(m / 9)); // Start of the iterator (Smallest multiple of n) int start = (int)Math.pow(10, minDigit) - (int)Math.pow(10, minDigit) % n; while (start < Integer.MAX_VALUE) { if (digitSum(start) == m) return start; else start += n; } return -1; } // Driver code static public void main(String args[]) { int n = 13, m = 32; System.out.print(findInt(n, m)); }} // This code is contributed// by Akanksha Rai
# Python 3 implementation of the# above approachfrom math import floor, pow import sys # Function to return digit sumdef digitSum(n): ans = 0; while (n): ans += n % 10; n = int(n / 10); return ans # Function to find out the smallest# integerdef findInt(n, m): minDigit = floor(m / 9) # Start of the iterator (Smallest # multiple of n) start = (int(pow(10, minDigit)) - int(pow(10, minDigit)) % n) while (start < sys.maxsize): if (digitSum(start) == m): return start else: start += n return -1 # Driver codeif __name__ == '__main__': n = 13 m = 32 print(findInt(n, m)) # This code is contributed by# Surendra_Gangwar
// C# implementation of the above approachusing System; class GFG{ // Function to return digit sum static int digitSum(int n) { int ans = 0; while (n != 0) { ans += n % 10; n /= 10; } return ans; } // Function to find out the // smallest integer static int findInt(int n, int m) { int minDigit = (int)Math.Floor((double)(m / 9)); // Start of the iterator (Smallest multiple of n) int start = (int)Math.Pow(10, minDigit) - (int)Math.Pow(10, minDigit) % n; while (start < int.MaxValue) { if (digitSum(start) == m) return start; else start += n; } return -1; } // Driver code static public void Main() { int n = 13, m = 32; Console.WriteLine(findInt(n, m)); }} // This code is contributed by Ryuga
<?php//PHP implementation of the above approach// Function to return digit sumfunction digitSum($n){ $ans = 0; while ($n) { $ans += $n % 10; $n /= 10; } return $ans;} // Function to find out the smallest integerfunction findInt($n, $m){ $minDigit = floor($m / 9); // Start of the iterator (Smallest multiple of n) $start = pow(10, $minDigit) - (int)pow(10, $minDigit) % $n; while ($start < PHP_INT_MAX) { if (digitSum($start) == $m) return $start; else $start += $n; } return -1;} // Driver code $n = 13; $m = 32; echo findInt($n, $m); # This code is contributed by ajit.?>
<script> // Javascript implementation of the above approach // Function to return digit sumfunction digitSum(n){ var ans = 0; while (n) { ans += n % 10; n = parseInt(n/10); } return ans;} // Function to find out the smallest integerfunction findInt(n, m){ var minDigit = Math.floor(m / 9); // Start of the iterator (Smallest multiple of n) var start = Math.pow(10, minDigit) - Math.pow(10, minDigit) % n; while (start < 1000000000) { if (digitSum(start) == m) return start; else start += n; } return -1;} // Driver codevar n = 13, m = 32;document.write( findInt(n, m)); </script>
8879
Auxiliary Space: O(1)
jit_t
ankthon
SURENDRA_GANGWAR
Akanksha_Rai
itsok
simmytarika5
rishavmahato348
divisors
number-digits
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of strings whose prefix match with the given string to a given length k
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
C++: Methods of code shortening in competitive programming
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": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 249,
"s": 52,
"text": "Given two positive integers N and M, the task is to find the smallest positive integer which is divisible by N and whose digit sum is M. Print -1 if no such integer exists within the range of int."
},
{
"code": null,
"e": 260,
"s": 249,
"text": "Examples: "
},
{
"code": null,
"e": 420,
"s": 260,
"text": "Input: N = 13, M = 32\nOutput: 8879\n8879 is divisible by 13 and its \nSum of digits of 8879 is 8+8+7+9 = 32 \ni.e. equals to M\n\nInput: N = 8, M = 32;\nOutput: 8888"
},
{
"code": null,
"e": 725,
"s": 420,
"text": "Approach: Start with N and iterate over all the multiples of n, and check whether its digit sum is equal to m or not. This problem can be solved in logn(INT_MAX) * log10(INT_MAX) time. The efficiency of this approach can be increased by starting the iteration with a number which has at least m/9 digit. "
},
{
"code": null,
"e": 771,
"s": 725,
"text": "Below is the implementation of the approach: "
},
{
"code": null,
"e": 775,
"s": 771,
"text": "C++"
},
{
"code": null,
"e": 780,
"s": 775,
"text": "Java"
},
{
"code": null,
"e": 788,
"s": 780,
"text": "Python3"
},
{
"code": null,
"e": 791,
"s": 788,
"text": "C#"
},
{
"code": null,
"e": 795,
"s": 791,
"text": "PHP"
},
{
"code": null,
"e": 806,
"s": 795,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return digit sumint digitSum(int n){ int ans = 0; while (n) { ans += n % 10; n /= 10; } return ans;} // Function to find out the smallest integerint findInt(int n, int m){ int minDigit = floor(m / 9); // Start of the iterator (Smallest multiple of n) int start = pow(10, minDigit) - (int)pow(10, minDigit) % n; while (start < INT_MAX) { if (digitSum(start) == m) return start; else start += n; } return -1;} // Driver codeint main(){ int n = 13, m = 32; cout << findInt(n, m); return 0;}",
"e": 1504,
"s": 806,
"text": null
},
{
"code": "// Java implementation of the above approach class GFG{ // Function to return digit sum static int digitSum(int n) { int ans = 0; while (n != 0) { ans += n % 10; n /= 10; } return ans; } // Function to find out the // smallest integer static int findInt(int n, int m) { int minDigit = (int)Math.floor((double)(m / 9)); // Start of the iterator (Smallest multiple of n) int start = (int)Math.pow(10, minDigit) - (int)Math.pow(10, minDigit) % n; while (start < Integer.MAX_VALUE) { if (digitSum(start) == m) return start; else start += n; } return -1; } // Driver code static public void main(String args[]) { int n = 13, m = 32; System.out.print(findInt(n, m)); }} // This code is contributed// by Akanksha Rai",
"e": 2466,
"s": 1504,
"text": null
},
{
"code": "# Python 3 implementation of the# above approachfrom math import floor, pow import sys # Function to return digit sumdef digitSum(n): ans = 0; while (n): ans += n % 10; n = int(n / 10); return ans # Function to find out the smallest# integerdef findInt(n, m): minDigit = floor(m / 9) # Start of the iterator (Smallest # multiple of n) start = (int(pow(10, minDigit)) - int(pow(10, minDigit)) % n) while (start < sys.maxsize): if (digitSum(start) == m): return start else: start += n return -1 # Driver codeif __name__ == '__main__': n = 13 m = 32 print(findInt(n, m)) # This code is contributed by# Surendra_Gangwar",
"e": 3183,
"s": 2466,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to return digit sum static int digitSum(int n) { int ans = 0; while (n != 0) { ans += n % 10; n /= 10; } return ans; } // Function to find out the // smallest integer static int findInt(int n, int m) { int minDigit = (int)Math.Floor((double)(m / 9)); // Start of the iterator (Smallest multiple of n) int start = (int)Math.Pow(10, minDigit) - (int)Math.Pow(10, minDigit) % n; while (start < int.MaxValue) { if (digitSum(start) == m) return start; else start += n; } return -1; } // Driver code static public void Main() { int n = 13, m = 32; Console.WriteLine(findInt(n, m)); }} // This code is contributed by Ryuga",
"e": 4130,
"s": 3183,
"text": null
},
{
"code": "<?php//PHP implementation of the above approach// Function to return digit sumfunction digitSum($n){ $ans = 0; while ($n) { $ans += $n % 10; $n /= 10; } return $ans;} // Function to find out the smallest integerfunction findInt($n, $m){ $minDigit = floor($m / 9); // Start of the iterator (Smallest multiple of n) $start = pow(10, $minDigit) - (int)pow(10, $minDigit) % $n; while ($start < PHP_INT_MAX) { if (digitSum($start) == $m) return $start; else $start += $n; } return -1;} // Driver code $n = 13; $m = 32; echo findInt($n, $m); # This code is contributed by ajit.?>",
"e": 4821,
"s": 4130,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to return digit sumfunction digitSum(n){ var ans = 0; while (n) { ans += n % 10; n = parseInt(n/10); } return ans;} // Function to find out the smallest integerfunction findInt(n, m){ var minDigit = Math.floor(m / 9); // Start of the iterator (Smallest multiple of n) var start = Math.pow(10, minDigit) - Math.pow(10, minDigit) % n; while (start < 1000000000) { if (digitSum(start) == m) return start; else start += n; } return -1;} // Driver codevar n = 13, m = 32;document.write( findInt(n, m)); </script>",
"e": 5500,
"s": 4821,
"text": null
},
{
"code": null,
"e": 5505,
"s": 5500,
"text": "8879"
},
{
"code": null,
"e": 5529,
"s": 5507,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5535,
"s": 5529,
"text": "jit_t"
},
{
"code": null,
"e": 5543,
"s": 5535,
"text": "ankthon"
},
{
"code": null,
"e": 5560,
"s": 5543,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 5573,
"s": 5560,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5579,
"s": 5573,
"text": "itsok"
},
{
"code": null,
"e": 5592,
"s": 5579,
"text": "simmytarika5"
},
{
"code": null,
"e": 5608,
"s": 5592,
"text": "rishavmahato348"
},
{
"code": null,
"e": 5617,
"s": 5608,
"text": "divisors"
},
{
"code": null,
"e": 5631,
"s": 5617,
"text": "number-digits"
},
{
"code": null,
"e": 5655,
"s": 5631,
"text": "Competitive Programming"
},
{
"code": null,
"e": 5668,
"s": 5655,
"text": "Mathematical"
},
{
"code": null,
"e": 5681,
"s": 5668,
"text": "Mathematical"
},
{
"code": null,
"e": 5779,
"s": 5681,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5857,
"s": 5779,
"text": "Count of strings whose prefix match with the given string to a given length k"
},
{
"code": null,
"e": 5891,
"s": 5857,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 5929,
"s": 5891,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 5969,
"s": 5929,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 6028,
"s": 5969,
"text": "C++: Methods of code shortening in competitive programming"
},
{
"code": null,
"e": 6058,
"s": 6028,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 6101,
"s": 6058,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6161,
"s": 6101,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6176,
"s": 6161,
"text": "C++ Data Types"
}
] |
What does ‘<?=’ short open tag mean in PHP ?
|
05 Feb, 2019
The <php is used to identify the start of a PHP document.
In PHP whenever it reads a PHP document, It looks for:
<?php ?>
It process the codes in between the above tags only and leaves the other codes around them.
For example :
<?phpecho "Hello PHP !";?>
Hello PHP !
Note : But a special case is when you write a PHP file the end tag can be omitted, Only the start tag is needed.
The below code works fine as well:
<?php echo "Hello PHP !";
Hello PHP !
The <= tag is called short open tag in PHP. To use the short tags, one must have to enable it from settings in the PHP.ini file.
First of all ensure that short tags are not disabled, To check it, go into php.ini file On line 77 .(location in linux systems :/etc/php5/apache2/php.ini)
Find the below line in the file and add (On) instead of (Off):
short_open_tag=On
However, from PHP version 5.4.0, the short tags are available for use regardless of the settings in the PHP.ini file.
The below two examples produces the same output with and without short open tags.
Example 1 : Normal Way.
<?php $username = "GeeksforGeeks"; echo "$username";?>
GeeksforGeeks
Example 2 : The Short Hand Way.
<?php $username = "GeeksforGeeks";?> <?= $username ?>
GeeksforGeeks
As you can observe, both of the above codes gives us the same output. So, using short tags we told to php interpreter that:
<? ?>
can be treated same as
<?php ?>
The above example can be further modified as follows :
<?=$username = "GeeksforGeeks";?>
GeeksforGeeks
PHP-basics
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 110,
"s": 52,
"text": "The <php is used to identify the start of a PHP document."
},
{
"code": null,
"e": 165,
"s": 110,
"text": "In PHP whenever it reads a PHP document, It looks for:"
},
{
"code": "<?php ?>",
"e": 174,
"s": 165,
"text": null
},
{
"code": null,
"e": 266,
"s": 174,
"text": "It process the codes in between the above tags only and leaves the other codes around them."
},
{
"code": null,
"e": 280,
"s": 266,
"text": "For example :"
},
{
"code": "<?phpecho \"Hello PHP !\";?>",
"e": 307,
"s": 280,
"text": null
},
{
"code": null,
"e": 320,
"s": 307,
"text": "Hello PHP !\n"
},
{
"code": null,
"e": 433,
"s": 320,
"text": "Note : But a special case is when you write a PHP file the end tag can be omitted, Only the start tag is needed."
},
{
"code": null,
"e": 468,
"s": 433,
"text": "The below code works fine as well:"
},
{
"code": "<?php echo \"Hello PHP !\";",
"e": 495,
"s": 468,
"text": null
},
{
"code": null,
"e": 508,
"s": 495,
"text": "Hello PHP !\n"
},
{
"code": null,
"e": 637,
"s": 508,
"text": "The <= tag is called short open tag in PHP. To use the short tags, one must have to enable it from settings in the PHP.ini file."
},
{
"code": null,
"e": 792,
"s": 637,
"text": "First of all ensure that short tags are not disabled, To check it, go into php.ini file On line 77 .(location in linux systems :/etc/php5/apache2/php.ini)"
},
{
"code": null,
"e": 855,
"s": 792,
"text": "Find the below line in the file and add (On) instead of (Off):"
},
{
"code": null,
"e": 874,
"s": 855,
"text": "short_open_tag=On\n"
},
{
"code": null,
"e": 992,
"s": 874,
"text": "However, from PHP version 5.4.0, the short tags are available for use regardless of the settings in the PHP.ini file."
},
{
"code": null,
"e": 1074,
"s": 992,
"text": "The below two examples produces the same output with and without short open tags."
},
{
"code": null,
"e": 1098,
"s": 1074,
"text": "Example 1 : Normal Way."
},
{
"code": "<?php $username = \"GeeksforGeeks\"; echo \"$username\";?>",
"e": 1159,
"s": 1098,
"text": null
},
{
"code": null,
"e": 1174,
"s": 1159,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 1206,
"s": 1174,
"text": "Example 2 : The Short Hand Way."
},
{
"code": "<?php $username = \"GeeksforGeeks\";?> <?= $username ?>",
"e": 1264,
"s": 1206,
"text": null
},
{
"code": null,
"e": 1279,
"s": 1264,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 1403,
"s": 1279,
"text": "As you can observe, both of the above codes gives us the same output. So, using short tags we told to php interpreter that:"
},
{
"code": null,
"e": 1410,
"s": 1403,
"text": "<? ?>\n"
},
{
"code": null,
"e": 1433,
"s": 1410,
"text": "can be treated same as"
},
{
"code": null,
"e": 1443,
"s": 1433,
"text": "<?php ?>\n"
},
{
"code": null,
"e": 1498,
"s": 1443,
"text": "The above example can be further modified as follows :"
},
{
"code": "<?=$username = \"GeeksforGeeks\";?>",
"e": 1532,
"s": 1498,
"text": null
},
{
"code": null,
"e": 1547,
"s": 1532,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 1558,
"s": 1547,
"text": "PHP-basics"
},
{
"code": null,
"e": 1565,
"s": 1558,
"text": "Picked"
},
{
"code": null,
"e": 1569,
"s": 1565,
"text": "PHP"
},
{
"code": null,
"e": 1586,
"s": 1569,
"text": "Web Technologies"
},
{
"code": null,
"e": 1590,
"s": 1586,
"text": "PHP"
}
] |
Minimum number of edges between two vertices of a Graph
|
29 Jun, 2021
You are given a undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v).
Examples:
Input : For given graph G. Find minimum number
of edges between (1, 5).
Output : 2
Explanation: (1, 2) and (2, 5) are the only
edges resulting into shortest path between 1
and 5.
The idea is to perform BFS from one of given input vertex(u). At the time of BFS maintain an array of distance[n] and initialize it to zero for all vertices. Now, suppose during BFS, vertex x is popped from queue and we are pushing all adjacent non-visited vertices(i) back into queue at the same time we should update distance[i] = distance[x] + 1;. Finally, distance[v] gives the minimum number of edges between u and v.
Algorithm:
int minEdgeBFS(int u, int v, int n)
{
// visited[n] for keeping track of visited
// node in BFS
bool visited[n] = {0};
// Initialize distances as 0
int distance[n] = {0};
// queue to do BFS.
queue Q;
distance[u] = 0;
Q.push(u);
visited[u] = true;
while (!Q.empty())
{
int x = Q.front();
Q.pop();
for (int i=0; i<edges[x].size(); i++)
{
if (visited[edges[x][i]])
continue;
// update distance for i
distance[edges[x][i]] = distance[x] + 1;
Q.push(edges[x][i]);
visited[edges[x][i]] = 1;
}
}
return distance[v];
}
C++
Java
Python3
C#
Javascript
// C++ program to find minimum edge// between given two vertex of Graph#include<bits/stdc++.h>using namespace std; // function for finding minimum no. of edge// using BFSint minEdgeBFS(vector <int> edges[], int u, int v, int n){ // visited[n] for keeping track of visited // node in BFS vector<bool> visited(n, 0); // Initialize distances as 0 vector<int> distance(n, 0); // queue to do BFS. queue <int> Q; distance[u] = 0; Q.push(u); visited[u] = true; while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i=0; i<edges[x].size(); i++) { if (visited[edges[x][i]]) continue; // update distance for i distance[edges[x][i]] = distance[x] + 1; Q.push(edges[x][i]); visited[edges[x][i]] = 1; } } return distance[v];} // function for addition of edgevoid addEdge(vector <int> edges[], int u, int v){ edges[u].push_back(v); edges[v].push_back(u);} // Driver functionint main(){ // To store adjacency list of graph int n = 9; vector <int> edges[9]; addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; cout << minEdgeBFS(edges, u, v, n); return 0;}
// Java program to find minimum edge// between given two vertex of Graph import java.util.LinkedList;import java.util.Queue;import java.util.Vector; class Test{ // Method for finding minimum no. of edge // using BFS static int minEdgeBFS(Vector <Integer> edges[], int u, int v, int n) { // visited[n] for keeping track of visited // node in BFS Vector<Boolean> visited = new Vector<Boolean>(n); for (int i = 0; i < n; i++) { visited.addElement(false); } // Initialize distances as 0 Vector<Integer> distance = new Vector<Integer>(n); for (int i = 0; i < n; i++) { distance.addElement(0); } // queue to do BFS. Queue<Integer> Q = new LinkedList<>(); distance.setElementAt(0, u); Q.add(u); visited.setElementAt(true, u); while (!Q.isEmpty()) { int x = Q.peek(); Q.poll(); for (int i=0; i<edges[x].size(); i++) { if (visited.elementAt(edges[x].get(i))) continue; // update distance for i distance.setElementAt(distance.get(x) + 1,edges[x].get(i)); Q.add(edges[x].get(i)); visited.setElementAt(true,edges[x].get(i)); } } return distance.get(v); } // method for addition of edge static void addEdge(Vector <Integer> edges[], int u, int v) { edges[u].add(v); edges[v].add(u); } // Driver method public static void main(String args[]) { // To store adjacency list of graph int n = 9; Vector <Integer> edges[] = new Vector[9]; for (int i = 0; i < edges.length; i++) { edges[i] = new Vector<>(); } addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; System.out.println(minEdgeBFS(edges, u, v, n)); }}// This code is contributed by Gaurav Miglani
# Python3 program to find minimum edge# between given two vertex of Graphimport queue # function for finding minimum# no. of edge using BFSdef minEdgeBFS(edges, u, v, n): # visited[n] for keeping track # of visited node in BFS visited = [0] * n # Initialize distances as 0 distance = [0] * n # queue to do BFS. Q = queue.Queue() distance[u] = 0 Q.put(u) visited[u] = True while (not Q.empty()): x = Q.get() for i in range(len(edges[x])): if (visited[edges[x][i]]): continue # update distance for i distance[edges[x][i]] = distance[x] + 1 Q.put(edges[x][i]) visited[edges[x][i]] = 1 return distance[v] # function for addition of edgedef addEdge(edges, u, v): edges[u].append(v) edges[v].append(u) # Driver Codeif __name__ == '__main__': # To store adjacency list of graph n = 9 edges = [[] for i in range(n)] addEdge(edges, 0, 1) addEdge(edges, 0, 7) addEdge(edges, 1, 7) addEdge(edges, 1, 2) addEdge(edges, 2, 3) addEdge(edges, 2, 5) addEdge(edges, 2, 8) addEdge(edges, 3, 4) addEdge(edges, 3, 5) addEdge(edges, 4, 5) addEdge(edges, 5, 6) addEdge(edges, 6, 7) addEdge(edges, 7, 8) u = 0 v = 5 print(minEdgeBFS(edges, u, v, n)) # This code is contributed by PranchalK
// C# program to find minimum edge// between given two vertex of Graphusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Method for finding minimum no. of edge// using BFSstatic int minEdgeBFS(ArrayList []edges, int u, int v, int n){ // visited[n] for keeping track of visited // node in BFS ArrayList visited = new ArrayList(); for(int i = 0; i < n; i++) { visited.Add(false); } // Initialize distances as 0 ArrayList distance = new ArrayList(); for(int i = 0; i < n; i++) { distance.Add(0); } // queue to do BFS. Queue Q = new Queue(); distance[u] = 0; Q.Enqueue(u); visited[u] = true; while (Q.Count != 0) { int x = (int)Q.Dequeue(); for(int i = 0; i < edges[x].Count; i++) { if ((bool)visited[(int)edges[x][i]]) continue; // Update distance for i distance[(int)edges[x][i]] = (int)distance[x] + 1; Q.Enqueue((int)edges[x][i]); visited[(int)edges[x][i]] = true; } } return (int)distance[v];} // Method for addition of edgestatic void addEdge(ArrayList []edges, int u, int v){ edges[u].Add(v); edges[v].Add(u);} // Driver codepublic static void Main(string []args){ // To store adjacency list of graph int n = 9; ArrayList []edges = new ArrayList[9]; for(int i = 0; i < 9; i++) { edges[i] = new ArrayList(); } addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; Console.Write(minEdgeBFS(edges, u, v, n));}} // This code is contributed by rutvik_56
<script> // JavaScript program to find minimum edge// between given two vertex of Graph // Method for finding minimum no. of edge// using BFSfunction minEdgeBFS(edges,u,v,n){ // visited[n] for keeping track of visited // node in BFS let visited = []; for (let i = 0; i < n; i++) { visited.push(false); } // Initialize distances as 0 let distance = []; for (let i = 0; i < n; i++) { distance.push(0); } // queue to do BFS. let Q = []; distance[u] = 0; Q.push(u); visited[u] = true; while (Q.length!=0) { let x = Q.shift(); for (let i=0; i<edges[x].length; i++) { if (visited[edges[x][i]]) continue; // update distance for i distance[edges[x][i]] = distance[x] + 1; Q.push(edges[x][i]); visited[edges[x][i]]= true; } } return distance[v];} // method for addition of edgefunction addEdge(edges,u,v){ edges[u].push(v); edges[v].push(u);} // Driver method// To store adjacency list of graphlet n = 9;let edges = new Array(9); for (let i = 0; i < edges.length; i++) { edges[i] = [];} addEdge(edges, 0, 1);addEdge(edges, 0, 7);addEdge(edges, 1, 7);addEdge(edges, 1, 2);addEdge(edges, 2, 3);addEdge(edges, 2, 5);addEdge(edges, 2, 8);addEdge(edges, 3, 4);addEdge(edges, 3, 5);addEdge(edges, 4, 5);addEdge(edges, 5, 6);addEdge(edges, 6, 7);addEdge(edges, 7, 8);let u = 0;let v = 5;document.write(minEdgeBFS(edges, u, v, n)); // This code is contributed by rag2127 </script>
Output:
3
This article is contributed by Shivam Pradhan (anuj_charm). 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.
PranchalKatiyar
29AjayKumar
rutvik_56
rag2127
BFS
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Topological Sorting
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Detect Cycle in a Directed Graph
Find if there is a path between two vertices in an undirected graph
Introduction to Data Structures
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Floyd Warshall Algorithm | DP-16
Bellman–Ford Algorithm | DP-23
What is Data Structure: Types, Classifications and Applications
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 207,
"s": 52,
"text": "You are given a undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v)."
},
{
"code": null,
"e": 218,
"s": 207,
"text": "Examples: "
},
{
"code": null,
"e": 298,
"s": 218,
"text": "Input : For given graph G. Find minimum number\n of edges between (1, 5)."
},
{
"code": null,
"e": 405,
"s": 298,
"text": "Output : 2\nExplanation: (1, 2) and (2, 5) are the only\nedges resulting into shortest path between 1\nand 5."
},
{
"code": null,
"e": 829,
"s": 405,
"text": "The idea is to perform BFS from one of given input vertex(u). At the time of BFS maintain an array of distance[n] and initialize it to zero for all vertices. Now, suppose during BFS, vertex x is popped from queue and we are pushing all adjacent non-visited vertices(i) back into queue at the same time we should update distance[i] = distance[x] + 1;. Finally, distance[v] gives the minimum number of edges between u and v. "
},
{
"code": null,
"e": 841,
"s": 829,
"text": "Algorithm: "
},
{
"code": null,
"e": 1536,
"s": 841,
"text": "int minEdgeBFS(int u, int v, int n)\n{\n // visited[n] for keeping track of visited\n // node in BFS\n bool visited[n] = {0};\n\n // Initialize distances as 0\n int distance[n] = {0};\n \n // queue to do BFS.\n queue Q;\n distance[u] = 0;\n \n Q.push(u);\n visited[u] = true;\n while (!Q.empty())\n {\n int x = Q.front();\n Q.pop();\n \n for (int i=0; i<edges[x].size(); i++)\n {\n if (visited[edges[x][i]])\n continue;\n\n // update distance for i\n distance[edges[x][i]] = distance[x] + 1;\n Q.push(edges[x][i]);\n visited[edges[x][i]] = 1;\n }\n }\n return distance[v];\n}"
},
{
"code": null,
"e": 1540,
"s": 1536,
"text": "C++"
},
{
"code": null,
"e": 1545,
"s": 1540,
"text": "Java"
},
{
"code": null,
"e": 1553,
"s": 1545,
"text": "Python3"
},
{
"code": null,
"e": 1556,
"s": 1553,
"text": "C#"
},
{
"code": null,
"e": 1567,
"s": 1556,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum edge// between given two vertex of Graph#include<bits/stdc++.h>using namespace std; // function for finding minimum no. of edge// using BFSint minEdgeBFS(vector <int> edges[], int u, int v, int n){ // visited[n] for keeping track of visited // node in BFS vector<bool> visited(n, 0); // Initialize distances as 0 vector<int> distance(n, 0); // queue to do BFS. queue <int> Q; distance[u] = 0; Q.push(u); visited[u] = true; while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i=0; i<edges[x].size(); i++) { if (visited[edges[x][i]]) continue; // update distance for i distance[edges[x][i]] = distance[x] + 1; Q.push(edges[x][i]); visited[edges[x][i]] = 1; } } return distance[v];} // function for addition of edgevoid addEdge(vector <int> edges[], int u, int v){ edges[u].push_back(v); edges[v].push_back(u);} // Driver functionint main(){ // To store adjacency list of graph int n = 9; vector <int> edges[9]; addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; cout << minEdgeBFS(edges, u, v, n); return 0;}",
"e": 3113,
"s": 1567,
"text": null
},
{
"code": "// Java program to find minimum edge// between given two vertex of Graph import java.util.LinkedList;import java.util.Queue;import java.util.Vector; class Test{ // Method for finding minimum no. of edge // using BFS static int minEdgeBFS(Vector <Integer> edges[], int u, int v, int n) { // visited[n] for keeping track of visited // node in BFS Vector<Boolean> visited = new Vector<Boolean>(n); for (int i = 0; i < n; i++) { visited.addElement(false); } // Initialize distances as 0 Vector<Integer> distance = new Vector<Integer>(n); for (int i = 0; i < n; i++) { distance.addElement(0); } // queue to do BFS. Queue<Integer> Q = new LinkedList<>(); distance.setElementAt(0, u); Q.add(u); visited.setElementAt(true, u); while (!Q.isEmpty()) { int x = Q.peek(); Q.poll(); for (int i=0; i<edges[x].size(); i++) { if (visited.elementAt(edges[x].get(i))) continue; // update distance for i distance.setElementAt(distance.get(x) + 1,edges[x].get(i)); Q.add(edges[x].get(i)); visited.setElementAt(true,edges[x].get(i)); } } return distance.get(v); } // method for addition of edge static void addEdge(Vector <Integer> edges[], int u, int v) { edges[u].add(v); edges[v].add(u); } // Driver method public static void main(String args[]) { // To store adjacency list of graph int n = 9; Vector <Integer> edges[] = new Vector[9]; for (int i = 0; i < edges.length; i++) { edges[i] = new Vector<>(); } addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; System.out.println(minEdgeBFS(edges, u, v, n)); }}// This code is contributed by Gaurav Miglani",
"e": 5517,
"s": 3113,
"text": null
},
{
"code": "# Python3 program to find minimum edge# between given two vertex of Graphimport queue # function for finding minimum# no. of edge using BFSdef minEdgeBFS(edges, u, v, n): # visited[n] for keeping track # of visited node in BFS visited = [0] * n # Initialize distances as 0 distance = [0] * n # queue to do BFS. Q = queue.Queue() distance[u] = 0 Q.put(u) visited[u] = True while (not Q.empty()): x = Q.get() for i in range(len(edges[x])): if (visited[edges[x][i]]): continue # update distance for i distance[edges[x][i]] = distance[x] + 1 Q.put(edges[x][i]) visited[edges[x][i]] = 1 return distance[v] # function for addition of edgedef addEdge(edges, u, v): edges[u].append(v) edges[v].append(u) # Driver Codeif __name__ == '__main__': # To store adjacency list of graph n = 9 edges = [[] for i in range(n)] addEdge(edges, 0, 1) addEdge(edges, 0, 7) addEdge(edges, 1, 7) addEdge(edges, 1, 2) addEdge(edges, 2, 3) addEdge(edges, 2, 5) addEdge(edges, 2, 8) addEdge(edges, 3, 4) addEdge(edges, 3, 5) addEdge(edges, 4, 5) addEdge(edges, 5, 6) addEdge(edges, 6, 7) addEdge(edges, 7, 8) u = 0 v = 5 print(minEdgeBFS(edges, u, v, n)) # This code is contributed by PranchalK",
"e": 6887,
"s": 5517,
"text": null
},
{
"code": "// C# program to find minimum edge// between given two vertex of Graphusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Method for finding minimum no. of edge// using BFSstatic int minEdgeBFS(ArrayList []edges, int u, int v, int n){ // visited[n] for keeping track of visited // node in BFS ArrayList visited = new ArrayList(); for(int i = 0; i < n; i++) { visited.Add(false); } // Initialize distances as 0 ArrayList distance = new ArrayList(); for(int i = 0; i < n; i++) { distance.Add(0); } // queue to do BFS. Queue Q = new Queue(); distance[u] = 0; Q.Enqueue(u); visited[u] = true; while (Q.Count != 0) { int x = (int)Q.Dequeue(); for(int i = 0; i < edges[x].Count; i++) { if ((bool)visited[(int)edges[x][i]]) continue; // Update distance for i distance[(int)edges[x][i]] = (int)distance[x] + 1; Q.Enqueue((int)edges[x][i]); visited[(int)edges[x][i]] = true; } } return (int)distance[v];} // Method for addition of edgestatic void addEdge(ArrayList []edges, int u, int v){ edges[u].Add(v); edges[v].Add(u);} // Driver codepublic static void Main(string []args){ // To store adjacency list of graph int n = 9; ArrayList []edges = new ArrayList[9]; for(int i = 0; i < 9; i++) { edges[i] = new ArrayList(); } addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; Console.Write(minEdgeBFS(edges, u, v, n));}} // This code is contributed by rutvik_56",
"e": 8901,
"s": 6887,
"text": null
},
{
"code": "<script> // JavaScript program to find minimum edge// between given two vertex of Graph // Method for finding minimum no. of edge// using BFSfunction minEdgeBFS(edges,u,v,n){ // visited[n] for keeping track of visited // node in BFS let visited = []; for (let i = 0; i < n; i++) { visited.push(false); } // Initialize distances as 0 let distance = []; for (let i = 0; i < n; i++) { distance.push(0); } // queue to do BFS. let Q = []; distance[u] = 0; Q.push(u); visited[u] = true; while (Q.length!=0) { let x = Q.shift(); for (let i=0; i<edges[x].length; i++) { if (visited[edges[x][i]]) continue; // update distance for i distance[edges[x][i]] = distance[x] + 1; Q.push(edges[x][i]); visited[edges[x][i]]= true; } } return distance[v];} // method for addition of edgefunction addEdge(edges,u,v){ edges[u].push(v); edges[v].push(u);} // Driver method// To store adjacency list of graphlet n = 9;let edges = new Array(9); for (let i = 0; i < edges.length; i++) { edges[i] = [];} addEdge(edges, 0, 1);addEdge(edges, 0, 7);addEdge(edges, 1, 7);addEdge(edges, 1, 2);addEdge(edges, 2, 3);addEdge(edges, 2, 5);addEdge(edges, 2, 8);addEdge(edges, 3, 4);addEdge(edges, 3, 5);addEdge(edges, 4, 5);addEdge(edges, 5, 6);addEdge(edges, 6, 7);addEdge(edges, 7, 8);let u = 0;let v = 5;document.write(minEdgeBFS(edges, u, v, n)); // This code is contributed by rag2127 </script>",
"e": 10629,
"s": 8901,
"text": null
},
{
"code": null,
"e": 10638,
"s": 10629,
"text": "Output: "
},
{
"code": null,
"e": 10640,
"s": 10638,
"text": "3"
},
{
"code": null,
"e": 11076,
"s": 10640,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). 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": 11092,
"s": 11076,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 11104,
"s": 11092,
"text": "29AjayKumar"
},
{
"code": null,
"e": 11114,
"s": 11104,
"text": "rutvik_56"
},
{
"code": null,
"e": 11122,
"s": 11114,
"text": "rag2127"
},
{
"code": null,
"e": 11126,
"s": 11122,
"text": "BFS"
},
{
"code": null,
"e": 11132,
"s": 11126,
"text": "Graph"
},
{
"code": null,
"e": 11138,
"s": 11132,
"text": "Graph"
},
{
"code": null,
"e": 11142,
"s": 11138,
"text": "BFS"
},
{
"code": null,
"e": 11240,
"s": 11142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11305,
"s": 11240,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 11325,
"s": 11305,
"text": "Topological Sorting"
},
{
"code": null,
"e": 11383,
"s": 11325,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 11416,
"s": 11383,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 11484,
"s": 11416,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 11516,
"s": 11484,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 11591,
"s": 11516,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 11624,
"s": 11591,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 11655,
"s": 11624,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
File isAbsolute() method in Java with Examples
|
30 Jan, 2019
The isAbsolute() method is a part of File class. The function returns whether the abstract pathname is absolute or not.
For Example: if we create a file object using the path as “program.txt”, it points to the file present in the same directory where the executable program is kept (if you are using a IDE it will point to the file where you have saved the program ). Here the path of the file mentioned above is “program.txt” but this path is not absolute (i.e. not complete) .Absolute path is the complete path from the root directory.
Function Signature:
public boolean isAbsolute()
Function Syntax:
file.isAbsolute()
Parameters: This function does not accept any parameters.
Return value: The function returns boolean value which tells whether the abstract pathname is absolute or not.
Below programs will illustrate the use of the isAbsolute() function
Example 1: We are given a file object of a file, we have to check whether it is absolute or not
// Java program to demonstrate the// use of isAbsolute() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("c:\\users\\program.txt"); // Check if the given path // is absolute or not if (f.isAbsolute()) { // Display that the path is absolute // as the function returned true System.out.println("The path is absolute"); } else { // Display that the path is not absolute // as the function returned false System.out.println("The path is not absolute"); } } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
The path is absolute
Example 2: We are given a file object of a file, we have to check whether it is absolute or not
// Java program to demonstrate the// use of isAbsolute() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("program.txt"); // Check if the given path // is absolute or not if (f.isAbsolute()) { // Display that the path is absolute // as the function returned true System.out.println("The path is absolute"); } else { // Display that the path is not absolute // as the function returned false System.out.println("The path is not absolute"); } } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
The path is not absolute
The programs might not run in an online IDE. please use an offline IDE and set the Parent file of the file
Java-File Class
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "The isAbsolute() method is a part of File class. The function returns whether the abstract pathname is absolute or not."
},
{
"code": null,
"e": 566,
"s": 148,
"text": "For Example: if we create a file object using the path as “program.txt”, it points to the file present in the same directory where the executable program is kept (if you are using a IDE it will point to the file where you have saved the program ). Here the path of the file mentioned above is “program.txt” but this path is not absolute (i.e. not complete) .Absolute path is the complete path from the root directory."
},
{
"code": null,
"e": 586,
"s": 566,
"text": "Function Signature:"
},
{
"code": null,
"e": 614,
"s": 586,
"text": "public boolean isAbsolute()"
},
{
"code": null,
"e": 631,
"s": 614,
"text": "Function Syntax:"
},
{
"code": null,
"e": 649,
"s": 631,
"text": "file.isAbsolute()"
},
{
"code": null,
"e": 707,
"s": 649,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 818,
"s": 707,
"text": "Return value: The function returns boolean value which tells whether the abstract pathname is absolute or not."
},
{
"code": null,
"e": 886,
"s": 818,
"text": "Below programs will illustrate the use of the isAbsolute() function"
},
{
"code": null,
"e": 982,
"s": 886,
"text": "Example 1: We are given a file object of a file, we have to check whether it is absolute or not"
},
{
"code": "// Java program to demonstrate the// use of isAbsolute() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"c:\\\\users\\\\program.txt\"); // Check if the given path // is absolute or not if (f.isAbsolute()) { // Display that the path is absolute // as the function returned true System.out.println(\"The path is absolute\"); } else { // Display that the path is not absolute // as the function returned false System.out.println(\"The path is not absolute\"); } } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 1873,
"s": 982,
"text": null
},
{
"code": null,
"e": 1881,
"s": 1873,
"text": "Output:"
},
{
"code": null,
"e": 1903,
"s": 1881,
"text": "The path is absolute\n"
},
{
"code": null,
"e": 1999,
"s": 1903,
"text": "Example 2: We are given a file object of a file, we have to check whether it is absolute or not"
},
{
"code": "// Java program to demonstrate the// use of isAbsolute() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"program.txt\"); // Check if the given path // is absolute or not if (f.isAbsolute()) { // Display that the path is absolute // as the function returned true System.out.println(\"The path is absolute\"); } else { // Display that the path is not absolute // as the function returned false System.out.println(\"The path is not absolute\"); } } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 2879,
"s": 1999,
"text": null
},
{
"code": null,
"e": 2887,
"s": 2879,
"text": "Output:"
},
{
"code": null,
"e": 2913,
"s": 2887,
"text": "The path is not absolute\n"
},
{
"code": null,
"e": 3020,
"s": 2913,
"text": "The programs might not run in an online IDE. please use an offline IDE and set the Parent file of the file"
},
{
"code": null,
"e": 3036,
"s": 3020,
"text": "Java-File Class"
},
{
"code": null,
"e": 3051,
"s": 3036,
"text": "Java-Functions"
},
{
"code": null,
"e": 3067,
"s": 3051,
"text": "Java-IO package"
},
{
"code": null,
"e": 3072,
"s": 3067,
"text": "Java"
},
{
"code": null,
"e": 3077,
"s": 3072,
"text": "Java"
}
] |
Maximum path sum in matrix
|
25 May, 2022
Given a matrix of N * M. Find the maximum path sum in matrix. The maximum path is sum of all elements from first row to last row where you are allowed to move only down or diagonally to left or right. You can start from any element in first row.
Examples:
Input : mat[][] = 10 10 2 0 20 4
1 0 0 30 2 5
0 10 4 0 2 0
1 0 2 20 0 4
Output : 74
The maximum sum path is 20-30-4-20.
Input : mat[][] = 1 2 3
9 8 7
4 5 6
Output : 17
The maximum sum path is 3-8-6.
We are given a matrix of N * M. To find max path sum first we have to find max value in first row of matrix. Store this value in res. Now for every element in matrix update element with max value which can be included in max path. If the value is greater then res then update res. In last return res which consists of max path sum value.
C++
Java
Python3
C#
PHP
Javascript
// CPP program for finding max path in matrix#include <bits/stdc++.h>#define N 4#define M 6using namespace std; // To calculate max path in matrixint findMaxPath(int mat[][M]){ for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum } } int res = 0; for (int j = 0; j < M; j++) res = max(mat[N-1][j], res); return res;} // Driver program to check findMaxPathint main(){ int mat1[N][M] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; cout << findMaxPath(mat1) << endl; return 0;}
// Java program for finding max path in matrix import static java.lang.Math.max; class GFG{ public static int N = 4, M = 6; // Function to calculate max path in matrix static int findMaxPath(int mat[][]) { // To find max val in first row int res = -1; for (int i = 0; i < M; i++) res = max(res, mat[0][i]); for (int i = 1; i < N; i++) { res = -1; for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum res = max(mat[i][j], res); } } return res; } // driver program public static void main (String[] args) { int mat[][] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; System.out.println(findMaxPath(mat)); }} // Contributed by Pramod Kumar
# Python 3 program for finding max path in matrix# To calculate max path in matrix def findMaxPath(mat): for i in range(1, N): res = -1 for j in range(M): # When all paths are possible if (j > 0 and j < M - 1): mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])) # When diagonal right is not possible else if (j > 0): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]) # When diagonal left is not possible else if (j < M - 1): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]) # Store max path sum res = max(mat[i][j], res) return res # Driver program to check findMaxPathN=4M=6mat = ([[ 10, 10, 2, 0, 20, 4 ], [ 1, 0, 0, 30, 2, 5 ], [ 0, 10, 4, 0, 2, 0 ], [ 1, 0, 2, 20, 0, 4 ]]) print(findMaxPath(mat)) # This code is contributed by Azkia Anam.
// C# program for finding// max path in matrixusing System; class GFG{ static int N = 4, M = 6; // find the max element static int max(int a, int b) { if(a > b) return a; else return b; } // Function to calculate // max path in matrix static int findMaxPath(int [,]mat) { // To find max val // in first row int res = -1; for (int i = 0; i < M; i++) res = max(res, mat[0, i]); for (int i = 1; i < N; i++) { res = -1; for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i, j] += max(mat[i - 1, j], max(mat[i - 1, j - 1], mat[i - 1, j + 1])); // When diagonal right // is not possible else if (j > 0) mat[i, j] += max(mat[i - 1, j], mat[i - 1, j - 1]); // When diagonal left // is not possible else if (j < M - 1) mat[i, j] += max(mat[i - 1, j], mat[i - 1, j + 1]); // Store max path sum res = max(mat[i, j], res); } } return res; } // Driver code static public void Main (String[] args) { int[,] mat = {{10, 10, 2, 0, 20, 4}, {1, 0, 0, 30, 2, 5}, {0, 10, 4, 0, 2, 0}, {1, 0, 2, 20, 0, 4}}; Console.WriteLine(findMaxPath(mat)); }} // This code is contributed// by Arnab Kundu
<?php// PHP program for finding max// path in matrix$N = 4;$M = 6; // To calculate max path in matrixfunction findMaxPath($mat){ global $N; global $M; for ($i = 1; $i < $N; $i++) { for ( $j = 0; $j < $M; $j++) { // When all paths are possible if ($j > 0 && $j < ($M - 1)) $mat[$i][$j] += max($mat[$i - 1][$j], max($mat[$i - 1][$j - 1], $mat[$i - 1][$j + 1])); // When diagonal right is // not possible else if ($j > 0) $mat[$i][$j] += max($mat[$i - 1][$j], $mat[$i - 1][$j - 1]); // When diagonal left is // not possible else if ($j < ($M - 1)) $mat[$i][$j] += max($mat[$i - 1][$j], $mat[$i - 1][$j + 1]); // Store max path sum } } $res = 0; for ($j = 0; $j < $M; $j++) $res = max($mat[$N - 1][$j], $res); return $res;} // Driver Code$mat1 = array( array( 10, 10, 2, 0, 20, 4 ), array( 1, 0, 0, 30, 2, 5 ), array( 0, 10, 4, 0, 2, 0 ), array( 1, 0, 2, 20, 0, 4 )); echo findMaxPath($mat1),"\n"; // This code is contributed by Sach_Code?>
<script> // Javascript program for finding max path in matrixlet N = 4, M = 6; // Function to calculate max path in matrixfunction findMaxPath(mat){ // To find max val in first row let res = -1; for(let i = 0; i < M; i++) res = Math.max(res, mat[0][i]); for(let i = 1; i < N; i++) { res = -1; for(let j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += Math.max(mat[i - 1][j], Math.max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += Math.max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += Math.max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum res = Math.max(mat[i][j], res); } } return res;} // Driver Codelet mat = [ [ 10, 10, 2, 0, 20, 4 ], [ 1, 0, 0, 30, 2, 5 ], [ 0, 10, 4, 0, 2, 0 ], [ 1, 0, 2, 20, 0, 4 ] ]; document.write(findMaxPath(mat)); // This code is contributed by sravan kumar </script>
Output:
74
Time Complexity: O(N*M), where N and M are the dimensions of the matrix
Space Complexity: O(1)
This article is contributed by nuclode. 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.
andrew1234
Sach_Code
sravankumar8128
paramshendekar
as5853535
simmytarika5
sanskar84
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 300,
"s": 54,
"text": "Given a matrix of N * M. Find the maximum path sum in matrix. The maximum path is sum of all elements from first row to last row where you are allowed to move only down or diagonally to left or right. You can start from any element in first row."
},
{
"code": null,
"e": 311,
"s": 300,
"text": "Examples: "
},
{
"code": null,
"e": 619,
"s": 311,
"text": "Input : mat[][] = 10 10 2 0 20 4\n 1 0 0 30 2 5\n 0 10 4 0 2 0\n 1 0 2 20 0 4\nOutput : 74\nThe maximum sum path is 20-30-4-20.\n\nInput : mat[][] = 1 2 3\n 9 8 7\n 4 5 6\nOutput : 17\nThe maximum sum path is 3-8-6."
},
{
"code": null,
"e": 957,
"s": 619,
"text": "We are given a matrix of N * M. To find max path sum first we have to find max value in first row of matrix. Store this value in res. Now for every element in matrix update element with max value which can be included in max path. If the value is greater then res then update res. In last return res which consists of max path sum value."
},
{
"code": null,
"e": 961,
"s": 957,
"text": "C++"
},
{
"code": null,
"e": 966,
"s": 961,
"text": "Java"
},
{
"code": null,
"e": 974,
"s": 966,
"text": "Python3"
},
{
"code": null,
"e": 977,
"s": 974,
"text": "C#"
},
{
"code": null,
"e": 981,
"s": 977,
"text": "PHP"
},
{
"code": null,
"e": 992,
"s": 981,
"text": "Javascript"
},
{
"code": "// CPP program for finding max path in matrix#include <bits/stdc++.h>#define N 4#define M 6using namespace std; // To calculate max path in matrixint findMaxPath(int mat[][M]){ for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum } } int res = 0; for (int j = 0; j < M; j++) res = max(mat[N-1][j], res); return res;} // Driver program to check findMaxPathint main(){ int mat1[N][M] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; cout << findMaxPath(mat1) << endl; return 0;}",
"e": 2254,
"s": 992,
"text": null
},
{
"code": "// Java program for finding max path in matrix import static java.lang.Math.max; class GFG{ public static int N = 4, M = 6; // Function to calculate max path in matrix static int findMaxPath(int mat[][]) { // To find max val in first row int res = -1; for (int i = 0; i < M; i++) res = max(res, mat[0][i]); for (int i = 1; i < N; i++) { res = -1; for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum res = max(mat[i][j], res); } } return res; } // driver program public static void main (String[] args) { int mat[][] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; System.out.println(findMaxPath(mat)); }} // Contributed by Pramod Kumar",
"e": 3848,
"s": 2254,
"text": null
},
{
"code": "# Python 3 program for finding max path in matrix# To calculate max path in matrix def findMaxPath(mat): for i in range(1, N): res = -1 for j in range(M): # When all paths are possible if (j > 0 and j < M - 1): mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])) # When diagonal right is not possible else if (j > 0): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]) # When diagonal left is not possible else if (j < M - 1): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]) # Store max path sum res = max(mat[i][j], res) return res # Driver program to check findMaxPathN=4M=6mat = ([[ 10, 10, 2, 0, 20, 4 ], [ 1, 0, 0, 30, 2, 5 ], [ 0, 10, 4, 0, 2, 0 ], [ 1, 0, 2, 20, 0, 4 ]]) print(findMaxPath(mat)) # This code is contributed by Azkia Anam.",
"e": 4952,
"s": 3848,
"text": null
},
{
"code": "// C# program for finding// max path in matrixusing System; class GFG{ static int N = 4, M = 6; // find the max element static int max(int a, int b) { if(a > b) return a; else return b; } // Function to calculate // max path in matrix static int findMaxPath(int [,]mat) { // To find max val // in first row int res = -1; for (int i = 0; i < M; i++) res = max(res, mat[0, i]); for (int i = 1; i < N; i++) { res = -1; for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i, j] += max(mat[i - 1, j], max(mat[i - 1, j - 1], mat[i - 1, j + 1])); // When diagonal right // is not possible else if (j > 0) mat[i, j] += max(mat[i - 1, j], mat[i - 1, j - 1]); // When diagonal left // is not possible else if (j < M - 1) mat[i, j] += max(mat[i - 1, j], mat[i - 1, j + 1]); // Store max path sum res = max(mat[i, j], res); } } return res; } // Driver code static public void Main (String[] args) { int[,] mat = {{10, 10, 2, 0, 20, 4}, {1, 0, 0, 30, 2, 5}, {0, 10, 4, 0, 2, 0}, {1, 0, 2, 20, 0, 4}}; Console.WriteLine(findMaxPath(mat)); }} // This code is contributed// by Arnab Kundu",
"e": 6683,
"s": 4952,
"text": null
},
{
"code": "<?php// PHP program for finding max// path in matrix$N = 4;$M = 6; // To calculate max path in matrixfunction findMaxPath($mat){ global $N; global $M; for ($i = 1; $i < $N; $i++) { for ( $j = 0; $j < $M; $j++) { // When all paths are possible if ($j > 0 && $j < ($M - 1)) $mat[$i][$j] += max($mat[$i - 1][$j], max($mat[$i - 1][$j - 1], $mat[$i - 1][$j + 1])); // When diagonal right is // not possible else if ($j > 0) $mat[$i][$j] += max($mat[$i - 1][$j], $mat[$i - 1][$j - 1]); // When diagonal left is // not possible else if ($j < ($M - 1)) $mat[$i][$j] += max($mat[$i - 1][$j], $mat[$i - 1][$j + 1]); // Store max path sum } } $res = 0; for ($j = 0; $j < $M; $j++) $res = max($mat[$N - 1][$j], $res); return $res;} // Driver Code$mat1 = array( array( 10, 10, 2, 0, 20, 4 ), array( 1, 0, 0, 30, 2, 5 ), array( 0, 10, 4, 0, 2, 0 ), array( 1, 0, 2, 20, 0, 4 )); echo findMaxPath($mat1),\"\\n\"; // This code is contributed by Sach_Code?>",
"e": 8011,
"s": 6683,
"text": null
},
{
"code": "<script> // Javascript program for finding max path in matrixlet N = 4, M = 6; // Function to calculate max path in matrixfunction findMaxPath(mat){ // To find max val in first row let res = -1; for(let i = 0; i < M; i++) res = Math.max(res, mat[0][i]); for(let i = 1; i < N; i++) { res = -1; for(let j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += Math.max(mat[i - 1][j], Math.max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += Math.max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += Math.max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum res = Math.max(mat[i][j], res); } } return res;} // Driver Codelet mat = [ [ 10, 10, 2, 0, 20, 4 ], [ 1, 0, 0, 30, 2, 5 ], [ 0, 10, 4, 0, 2, 0 ], [ 1, 0, 2, 20, 0, 4 ] ]; document.write(findMaxPath(mat)); // This code is contributed by sravan kumar </script>",
"e": 9373,
"s": 8011,
"text": null
},
{
"code": null,
"e": 9382,
"s": 9373,
"text": "Output: "
},
{
"code": null,
"e": 9385,
"s": 9382,
"text": "74"
},
{
"code": null,
"e": 9457,
"s": 9385,
"text": "Time Complexity: O(N*M), where N and M are the dimensions of the matrix"
},
{
"code": null,
"e": 9480,
"s": 9457,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 9896,
"s": 9480,
"text": "This article is contributed by nuclode. 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": 9907,
"s": 9896,
"text": "andrew1234"
},
{
"code": null,
"e": 9917,
"s": 9907,
"text": "Sach_Code"
},
{
"code": null,
"e": 9933,
"s": 9917,
"text": "sravankumar8128"
},
{
"code": null,
"e": 9948,
"s": 9933,
"text": "paramshendekar"
},
{
"code": null,
"e": 9958,
"s": 9948,
"text": "as5853535"
},
{
"code": null,
"e": 9971,
"s": 9958,
"text": "simmytarika5"
},
{
"code": null,
"e": 9981,
"s": 9971,
"text": "sanskar84"
},
{
"code": null,
"e": 9988,
"s": 9981,
"text": "Matrix"
},
{
"code": null,
"e": 9995,
"s": 9988,
"text": "Matrix"
}
] |
Find the one missing number in range
|
28 Jun, 2022
Given an array of size n. It is also given that range of numbers is from smallestNumber to smallestNumber + n where smallestNumber is the smallest number in array. The array contains number in this range but one number is missing so the task is to find this missing number.Examples:
Input : arr[] = {13, 12, 11, 15}
Output : 14
Input : arr[] = {33, 36, 35, 34};
Output : 37
The problem is very close to find missing number.There are many approaches to solve this problem. A simple approach is to first find minimum, then one by one search all elements. Time complexity of this approach is O(n*n)A better solution is to sort the array. Then traverse the array and find the first element which is not present. Time complexity of this approach is O(n Log n)The best solution is to first XOR all the numbers. Then XOR this result to all numbers from smallest number to n+smallestNumber. The XOR is our result.Example:-
arr[n] = {13, 12, 11, 15}
smallestNumber = 11
first find the xor of this array
13^12^11^15 = 5
Then find the XOR first number to first number + n
11^12^13^14^15 = 11;
Then xor these two number's
5^11 = 14 // this is the missing number
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find missing// number in a range.#include <bits/stdc++.h>using namespace std; // Find the missing number// in a rangeint missingNum(int arr[], int n){ int minvalue = *min_element(arr, arr+n); // here we xor of all the number int xornum = 0; for (int i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} // Driver codeint main(){ int arr[] = { 13, 12, 11, 15 }; int n = sizeof(arr)/sizeof(arr[0]); cout << missingNum(arr, n); return 0;}
// Java program to find// missing number in a range.import java.io.*;import java.util.*; class GFG { // Find the missing number in a rangestatic int missingNum(int arr[], int n){ List<Integer> list = new ArrayList<>(arr.length); for (int i :arr) { list.add(Integer.valueOf(i)); } int minvalue = Collections.min(list);; // here we xor of all the number int xornum = 0; for (int i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} public static void main (String[] args) { int arr[] = { 13, 12, 11, 15 }; int n = arr.length; System.out.println(missingNum(arr, n)); }} //This code is contributed by Gitanjali.
# python3 program to check# missingnumber in a range # Find the missing number# in a rangedef missingNum( arr, n): minvalue = min(arr) # here we xor of all the number xornum = 0 for i in range (0,n): xornum ^= (minvalue) ^ arr[i] minvalue = minvalue+1 # xor last number return xornum ^ minvalue # Driver methodarr = [ 13, 12, 11, 15 ]n = len(arr)print (missingNum(arr, n)) # This code is contributed by Gitanjali.
// C# program to find// missing number in a range.using System;using System.Collections.Generic;using System.Linq; class GFG{ // Find the missing number in a rangestatic int missingNum(int []arr, int n){ List<int> list = new List<int>(arr.Length); foreach (int i in arr) { list.Add(i); } int minvalue = list.Min(); // here we xor of all the number int xornum = 0; for (int i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} // Driver Codepublic static void Main (String[] args){ int []arr = { 13, 12, 11, 15 }; int n = arr.Length; Console.WriteLine(missingNum(arr, n));}} // This code is contributed by Rajput-Ji
<?php// PHP program to find missing// number in a range. // Find the missing number// in a rangefunction missingNum($arr, $n){ $minvalue = min($arr); // here we xor of all the number $xornum = 0; for ($i = 0; $i < $n; $i++) { $xornum ^= ($minvalue) ^ $arr[$i]; $minvalue++; } // xor last number return $xornum ^ $minvalue;} // Driver code$arr = array( 13, 12, 11, 15 );$n = sizeof($arr);echo missingNum($arr, $n); // This code is contributed// by Sach_Code?>
<script>// Javascript program to find missing// number in a range. // Find the missing number// in a rangefunction missingNum(arr, n){ let minvalue = Math.min(...arr); // here we xor of all the number let xornum = 0; for (let i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} // Driver code let arr = [ 13, 12, 11, 15 ]; let n = arr.length; document.write(missingNum(arr, n)); </script>
14
Another Approach:
An efficient approach to find out the missing number can be performed using the concept that sum of the arithmetic progression smallestNumber, smallestNumber + 1, smallestNumber + 2, ..... , smallestNumber + n, which is (n + 1) x (2smallestNumber + 1) / 2 is equal to the sum of the array + the missing number.
In other words,
Sum of the AP – Sum of the array = Missing Number.
The advantage of this method is that we can utilize the inbuilt library methods to calculate the sum and minimum number of the array, which will reduce the execution time, especially for languages like Python3 and JavaScript.
C++
Java
Python3
C#
Javascript
// CPP program to find missing// number in a range.#include <bits/stdc++.h>using namespace std; // Function to find the missing number// in a rangeint missingNum(int arr[], int n){ // calculating the minimum of the array int& minNum = *min_element(arr, arr + n); // calculating the sum of the array int arrSum = 0; arrSum = accumulate(arr, arr + n, arrSum); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 int rangeSum = (minNum + minNum + n) * (n + 1) / 2; // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum;} // Driver codeint main(){ int arr[] = { 13, 12, 11, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // function call cout << missingNum(arr, n); return 0;} // this code is contributed by phasing17
// Java program to find missing// number in a range. import java.util.stream.*; class GFG { // Function to find the missing number // in a range static int missingNum(int[] arr, int n) { // calculating the minimum of the array int minNum = IntStream.of(arr).min().getAsInt(); // calculating the sum of the array int arrSum = IntStream.of(arr).sum(); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 int rangeSum = (minNum + minNum + n) * (n + 1) / 2; // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum; } // Driver Code public static void main(String[] args) { int[] arr = { 13, 12, 11, 15 }; int n = arr.length; // function call System.out.println(missingNum(arr, n)); }} //this code is contributed by phasing17
# Python3 program to find missing# number in a range. # Function to find the missing number# in a rangedef missingNum(arr, n): # calculating the minimum of the array minNum = min(arr) # calculating the sum of the array arrSum = sum(arr) # calculating the sum of the range [min, min + n] # given using the AP series sum formula # (n + 1) * (2 * min + 1) / 2 rangeSum = (minNum + minNum + n) * (n + 1) // 2 # the difference between the sum of range # and the sum of array is the missing element return rangeSum - arrSum # Driver codearr = [13, 12, 11, 15]n = len(arr)# function callprint(missingNum(arr, n)) # this code is contributed by phasing17
// C# program to find missing// number in a range.using System;using System.Linq; class GFG { // Function to find the missing number // in a range static int missingNum(int[] arr, int n) { // calculating the minimum of the array int minNum = arr.Min(); // calculating the sum of the array int arrSum = arr.Sum(); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 int rangeSum = (minNum + minNum + n) * (n + 1) / 2; // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum; } // Driver Code public static void Main(string[] args) { int[] arr = { 13, 12, 11, 15 }; int n = arr.Length; // function call Console.WriteLine(missingNum(arr, n)); }} // this code is contributed by phasing17
//JS program to find missing// number in a range. // Function to find the missing number// in a rangefunction missingNum(arr, n){ // calculating the minimum of the array var minNum = Math.min(...arr); // calculating the sum of the array var arrSum = arr.reduce((a, b) => a + b, 0); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 var rangeSum = Number((minNum + minNum + n) * (n + 1) / 2); // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum;} // Driver codevar arr = [ 13, 12, 11, 15 ];var n = arr.length;// function callconsole.log(missingNum(arr, n)); // this code is contributed by phasing17
14
Time Complexity: O(n)
Auxiliary Space: O(1)
Sach_Code
Rajput-Ji
rishavmahato348
phasing17
Bitwise-XOR
limited-range-elements
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 339,
"s": 54,
"text": "Given an array of size n. It is also given that range of numbers is from smallestNumber to smallestNumber + n where smallestNumber is the smallest number in array. The array contains number in this range but one number is missing so the task is to find this missing number.Examples: "
},
{
"code": null,
"e": 436,
"s": 339,
"text": "Input : arr[] = {13, 12, 11, 15}\nOutput : 14\n\nInput : arr[] = {33, 36, 35, 34};\nOutput : 37"
},
{
"code": null,
"e": 981,
"s": 438,
"text": "The problem is very close to find missing number.There are many approaches to solve this problem. A simple approach is to first find minimum, then one by one search all elements. Time complexity of this approach is O(n*n)A better solution is to sort the array. Then traverse the array and find the first element which is not present. Time complexity of this approach is O(n Log n)The best solution is to first XOR all the numbers. Then XOR this result to all numbers from smallest number to n+smallestNumber. The XOR is our result.Example:- "
},
{
"code": null,
"e": 1219,
"s": 981,
"text": "arr[n] = {13, 12, 11, 15}\nsmallestNumber = 11\n\nfirst find the xor of this array\n13^12^11^15 = 5\n\nThen find the XOR first number to first number + n\n11^12^13^14^15 = 11;\n\nThen xor these two number's\n5^11 = 14 // this is the missing number"
},
{
"code": null,
"e": 1225,
"s": 1221,
"text": "C++"
},
{
"code": null,
"e": 1230,
"s": 1225,
"text": "Java"
},
{
"code": null,
"e": 1238,
"s": 1230,
"text": "Python3"
},
{
"code": null,
"e": 1241,
"s": 1238,
"text": "C#"
},
{
"code": null,
"e": 1245,
"s": 1241,
"text": "PHP"
},
{
"code": null,
"e": 1256,
"s": 1245,
"text": "Javascript"
},
{
"code": "// CPP program to find missing// number in a range.#include <bits/stdc++.h>using namespace std; // Find the missing number// in a rangeint missingNum(int arr[], int n){ int minvalue = *min_element(arr, arr+n); // here we xor of all the number int xornum = 0; for (int i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} // Driver codeint main(){ int arr[] = { 13, 12, 11, 15 }; int n = sizeof(arr)/sizeof(arr[0]); cout << missingNum(arr, n); return 0;}",
"e": 1818,
"s": 1256,
"text": null
},
{
"code": "// Java program to find// missing number in a range.import java.io.*;import java.util.*; class GFG { // Find the missing number in a rangestatic int missingNum(int arr[], int n){ List<Integer> list = new ArrayList<>(arr.length); for (int i :arr) { list.add(Integer.valueOf(i)); } int minvalue = Collections.min(list);; // here we xor of all the number int xornum = 0; for (int i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} public static void main (String[] args) { int arr[] = { 13, 12, 11, 15 }; int n = arr.length; System.out.println(missingNum(arr, n)); }} //This code is contributed by Gitanjali.",
"e": 2563,
"s": 1818,
"text": null
},
{
"code": "# python3 program to check# missingnumber in a range # Find the missing number# in a rangedef missingNum( arr, n): minvalue = min(arr) # here we xor of all the number xornum = 0 for i in range (0,n): xornum ^= (minvalue) ^ arr[i] minvalue = minvalue+1 # xor last number return xornum ^ minvalue # Driver methodarr = [ 13, 12, 11, 15 ]n = len(arr)print (missingNum(arr, n)) # This code is contributed by Gitanjali.",
"e": 3025,
"s": 2563,
"text": null
},
{
"code": "// C# program to find// missing number in a range.using System;using System.Collections.Generic;using System.Linq; class GFG{ // Find the missing number in a rangestatic int missingNum(int []arr, int n){ List<int> list = new List<int>(arr.Length); foreach (int i in arr) { list.Add(i); } int minvalue = list.Min(); // here we xor of all the number int xornum = 0; for (int i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} // Driver Codepublic static void Main (String[] args){ int []arr = { 13, 12, 11, 15 }; int n = arr.Length; Console.WriteLine(missingNum(arr, n));}} // This code is contributed by Rajput-Ji",
"e": 3771,
"s": 3025,
"text": null
},
{
"code": "<?php// PHP program to find missing// number in a range. // Find the missing number// in a rangefunction missingNum($arr, $n){ $minvalue = min($arr); // here we xor of all the number $xornum = 0; for ($i = 0; $i < $n; $i++) { $xornum ^= ($minvalue) ^ $arr[$i]; $minvalue++; } // xor last number return $xornum ^ $minvalue;} // Driver code$arr = array( 13, 12, 11, 15 );$n = sizeof($arr);echo missingNum($arr, $n); // This code is contributed// by Sach_Code?>",
"e": 4274,
"s": 3771,
"text": null
},
{
"code": "<script>// Javascript program to find missing// number in a range. // Find the missing number// in a rangefunction missingNum(arr, n){ let minvalue = Math.min(...arr); // here we xor of all the number let xornum = 0; for (let i = 0; i < n; i++) { xornum ^= (minvalue) ^ arr[i]; minvalue++; } // xor last number return xornum ^ minvalue;} // Driver code let arr = [ 13, 12, 11, 15 ]; let n = arr.length; document.write(missingNum(arr, n)); </script>",
"e": 4769,
"s": 4274,
"text": null
},
{
"code": null,
"e": 4772,
"s": 4769,
"text": "14"
},
{
"code": null,
"e": 4790,
"s": 4772,
"text": "Another Approach:"
},
{
"code": null,
"e": 5101,
"s": 4790,
"text": "An efficient approach to find out the missing number can be performed using the concept that sum of the arithmetic progression smallestNumber, smallestNumber + 1, smallestNumber + 2, ..... , smallestNumber + n, which is (n + 1) x (2smallestNumber + 1) / 2 is equal to the sum of the array + the missing number."
},
{
"code": null,
"e": 5117,
"s": 5101,
"text": "In other words,"
},
{
"code": null,
"e": 5168,
"s": 5117,
"text": "Sum of the AP – Sum of the array = Missing Number."
},
{
"code": null,
"e": 5394,
"s": 5168,
"text": "The advantage of this method is that we can utilize the inbuilt library methods to calculate the sum and minimum number of the array, which will reduce the execution time, especially for languages like Python3 and JavaScript."
},
{
"code": null,
"e": 5398,
"s": 5394,
"text": "C++"
},
{
"code": null,
"e": 5403,
"s": 5398,
"text": "Java"
},
{
"code": null,
"e": 5411,
"s": 5403,
"text": "Python3"
},
{
"code": null,
"e": 5414,
"s": 5411,
"text": "C#"
},
{
"code": null,
"e": 5425,
"s": 5414,
"text": "Javascript"
},
{
"code": "// CPP program to find missing// number in a range.#include <bits/stdc++.h>using namespace std; // Function to find the missing number// in a rangeint missingNum(int arr[], int n){ // calculating the minimum of the array int& minNum = *min_element(arr, arr + n); // calculating the sum of the array int arrSum = 0; arrSum = accumulate(arr, arr + n, arrSum); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 int rangeSum = (minNum + minNum + n) * (n + 1) / 2; // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum;} // Driver codeint main(){ int arr[] = { 13, 12, 11, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // function call cout << missingNum(arr, n); return 0;} // this code is contributed by phasing17",
"e": 6319,
"s": 5425,
"text": null
},
{
"code": "// Java program to find missing// number in a range. import java.util.stream.*; class GFG { // Function to find the missing number // in a range static int missingNum(int[] arr, int n) { // calculating the minimum of the array int minNum = IntStream.of(arr).min().getAsInt(); // calculating the sum of the array int arrSum = IntStream.of(arr).sum(); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 int rangeSum = (minNum + minNum + n) * (n + 1) / 2; // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum; } // Driver Code public static void main(String[] args) { int[] arr = { 13, 12, 11, 15 }; int n = arr.length; // function call System.out.println(missingNum(arr, n)); }} //this code is contributed by phasing17",
"e": 7305,
"s": 6319,
"text": null
},
{
"code": "# Python3 program to find missing# number in a range. # Function to find the missing number# in a rangedef missingNum(arr, n): # calculating the minimum of the array minNum = min(arr) # calculating the sum of the array arrSum = sum(arr) # calculating the sum of the range [min, min + n] # given using the AP series sum formula # (n + 1) * (2 * min + 1) / 2 rangeSum = (minNum + minNum + n) * (n + 1) // 2 # the difference between the sum of range # and the sum of array is the missing element return rangeSum - arrSum # Driver codearr = [13, 12, 11, 15]n = len(arr)# function callprint(missingNum(arr, n)) # this code is contributed by phasing17",
"e": 7989,
"s": 7305,
"text": null
},
{
"code": "// C# program to find missing// number in a range.using System;using System.Linq; class GFG { // Function to find the missing number // in a range static int missingNum(int[] arr, int n) { // calculating the minimum of the array int minNum = arr.Min(); // calculating the sum of the array int arrSum = arr.Sum(); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 int rangeSum = (minNum + minNum + n) * (n + 1) / 2; // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum; } // Driver Code public static void Main(string[] args) { int[] arr = { 13, 12, 11, 15 }; int n = arr.Length; // function call Console.WriteLine(missingNum(arr, n)); }} // this code is contributed by phasing17",
"e": 8863,
"s": 7989,
"text": null
},
{
"code": "//JS program to find missing// number in a range. // Function to find the missing number// in a rangefunction missingNum(arr, n){ // calculating the minimum of the array var minNum = Math.min(...arr); // calculating the sum of the array var arrSum = arr.reduce((a, b) => a + b, 0); // calculating the sum of the range [min, min + n] // given using the AP series sum formula // (n + 1) * (2 * min + 1) / 2 var rangeSum = Number((minNum + minNum + n) * (n + 1) / 2); // the difference between the sum of range // and the sum of array is the missing element return rangeSum - arrSum;} // Driver codevar arr = [ 13, 12, 11, 15 ];var n = arr.length;// function callconsole.log(missingNum(arr, n)); // this code is contributed by phasing17",
"e": 9638,
"s": 8863,
"text": null
},
{
"code": null,
"e": 9641,
"s": 9638,
"text": "14"
},
{
"code": null,
"e": 9663,
"s": 9641,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 9685,
"s": 9663,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9695,
"s": 9685,
"text": "Sach_Code"
},
{
"code": null,
"e": 9705,
"s": 9695,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9721,
"s": 9705,
"text": "rishavmahato348"
},
{
"code": null,
"e": 9731,
"s": 9721,
"text": "phasing17"
},
{
"code": null,
"e": 9743,
"s": 9731,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 9766,
"s": 9743,
"text": "limited-range-elements"
},
{
"code": null,
"e": 9773,
"s": 9766,
"text": "Arrays"
},
{
"code": null,
"e": 9783,
"s": 9773,
"text": "Searching"
},
{
"code": null,
"e": 9790,
"s": 9783,
"text": "Arrays"
},
{
"code": null,
"e": 9800,
"s": 9790,
"text": "Searching"
}
] |
Python – Convert day number to date in particular year
|
16 Nov, 2020
Given day number, convert to date it refers to.
Input : day_num = “339”, year = “2020” Output : 12-04-2020 Explanation : 339th Day of 2020 is 4th December.
Input : day_num = “4”, year = “2020” Output : 01-04-2020 Explanation : 4th Day of 2020 is 4th January.
Method #1 : Using datetime.strptime()
In this, we get the year string and day number string, and pass to strptime(), converts to the corresponding required date.
Python3
# Python3 code to demonstrate working of# Convert day number to date in particular year# Using datetime.strptime()from datetime import datetime # initializing day numberday_num = "339" # print day numberprint("The day number : " + str(day_num)) # adjusting day numday_num.rjust(3 + len(day_num), '0') # Initialize yearyear = "2020" # converting to dateres = datetime.strptime(year + "-" + day_num, "%Y-%j").strftime("%m-%d-%Y") # printing resultprint("Resolved date : " + str(res))
The day number : 339
Resolved date : 12-04-2020
Method #2 : Using timedelta()
In this, we initialize the date by 1st of January and then add number of days using timedelta(), resultant gives the date required.
Python3
# Python3 code to demonstrate working of# Convert day number to date in particular year# Using datetime.strptime()from datetime import datetime, date, timedelta # initializing day numberday_num = "339" # print day numberprint("The day number : " + str(day_num)) # adjusting day numday_num.rjust(3 + len(day_num), '0') # Initialize yearyear = "2020" # Initializing start datestrt_date = date(int(year), 1, 1) # converting to dateres_date = strt_date + timedelta(days=int(day_num) - 1)res = res_date.strftime("%m-%d-%Y") # printing resultprint("Resolved date : " + str(res))
The day number : 339
Resolved date : 12-04-2020
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2020"
},
{
"code": null,
"e": 76,
"s": 28,
"text": "Given day number, convert to date it refers to."
},
{
"code": null,
"e": 184,
"s": 76,
"text": "Input : day_num = “339”, year = “2020” Output : 12-04-2020 Explanation : 339th Day of 2020 is 4th December."
},
{
"code": null,
"e": 288,
"s": 184,
"text": "Input : day_num = “4”, year = “2020” Output : 01-04-2020 Explanation : 4th Day of 2020 is 4th January. "
},
{
"code": null,
"e": 326,
"s": 288,
"text": "Method #1 : Using datetime.strptime()"
},
{
"code": null,
"e": 450,
"s": 326,
"text": "In this, we get the year string and day number string, and pass to strptime(), converts to the corresponding required date."
},
{
"code": null,
"e": 458,
"s": 450,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert day number to date in particular year# Using datetime.strptime()from datetime import datetime # initializing day numberday_num = \"339\" # print day numberprint(\"The day number : \" + str(day_num)) # adjusting day numday_num.rjust(3 + len(day_num), '0') # Initialize yearyear = \"2020\" # converting to dateres = datetime.strptime(year + \"-\" + day_num, \"%Y-%j\").strftime(\"%m-%d-%Y\") # printing resultprint(\"Resolved date : \" + str(res))",
"e": 946,
"s": 458,
"text": null
},
{
"code": null,
"e": 995,
"s": 946,
"text": "The day number : 339\nResolved date : 12-04-2020\n"
},
{
"code": null,
"e": 1025,
"s": 995,
"text": "Method #2 : Using timedelta()"
},
{
"code": null,
"e": 1157,
"s": 1025,
"text": "In this, we initialize the date by 1st of January and then add number of days using timedelta(), resultant gives the date required."
},
{
"code": null,
"e": 1165,
"s": 1157,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert day number to date in particular year# Using datetime.strptime()from datetime import datetime, date, timedelta # initializing day numberday_num = \"339\" # print day numberprint(\"The day number : \" + str(day_num)) # adjusting day numday_num.rjust(3 + len(day_num), '0') # Initialize yearyear = \"2020\" # Initializing start datestrt_date = date(int(year), 1, 1) # converting to dateres_date = strt_date + timedelta(days=int(day_num) - 1)res = res_date.strftime(\"%m-%d-%Y\") # printing resultprint(\"Resolved date : \" + str(res))",
"e": 1745,
"s": 1165,
"text": null
},
{
"code": null,
"e": 1794,
"s": 1745,
"text": "The day number : 339\nResolved date : 12-04-2020\n"
},
{
"code": null,
"e": 1818,
"s": 1794,
"text": "Python datetime-program"
},
{
"code": null,
"e": 1825,
"s": 1818,
"text": "Python"
},
{
"code": null,
"e": 1841,
"s": 1825,
"text": "Python Programs"
}
] |
Python | Ways to Copy Dictionary
|
22 Jan, 2019
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. When we simply assign dict1 = dict2 it refers to the same dictionary. Let’s discuss a few ways to copy the dictionary from another dictionary.Method#1: Using copy()copy() method returns a shallow copy of the dictionary.It doesn’t take any parameter and return a new dictionary which is not referring to the initial dictionary.
# Python3 code to demonstrate# how to copy dictionary# using copy() function # initialising dictionarytest1 = {"name" : "akshat", "name1" : "manjeet", "name2" : "vashu"} # method to copy dictionary using copy() functiontest2 = test1.copy() # updating test2test2["name1"] ="nikhil" # print initial dictionaryprint("initial dictionary = ", test1) # printing updated dictionaryprint("updated dictionary = ", test2)
Output
initial dictionary = {'name1': 'manjeet', 'name2': 'vashu', 'name': 'akshat'}
updated dictionary = {'name1': 'nikhil', 'name': 'akshat', 'name2': 'vashu'}
Method #2: Using dict()The dict() is a constructor which creates dictionary in Python.
# Python3 code to demonstrate# how to copy dictionary# using dict() # initialising dictionarytest1 = {"name" : "akshat", "name1" : "manjeet", "name2" : "vashu"} # method to copy dictionary using dicttest2 = dict(test1) # updating test2test2["name1"] ="nikhil" # print initial dictionaryprint("initial dictionary = ", test1) # printing updated dictionaryprint("updated dictionary = ", test2)
Output
initial dictionary = {'name2': 'vashu', 'name': 'akshat', 'name1': 'manjeet'}
updated dictionary = {'name2': 'vashu', 'name': 'akshat', 'name1': 'nikhil'}
Method#3 : Using Dictionary comprehension
# Python3 code to demonstrate# how to copy dictionary# using dictionary comprehension # initialising dictionarytest1 = {"name" : "akshat", "name1" : "manjeet", "name2" : "vashu"} # method to copy dictionary using dictionary comprehensiontest2 = {k:v for k, v in test1.items()} # updating test2test2["name1"] ="ayush" # print initial dictionaryprint("initial dictionary = ", test1) # printing updated dictionaryprint("updated dictionary = ", test2)
Output
initial dictionary = {'name': 'akshat', 'name2': 'vashu', 'name1': 'manjeet'}
updated dictionary = {'name': 'akshat', 'name2': 'vashu', 'name1': 'ayush'}
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jan, 2019"
},
{
"code": null,
"e": 598,
"s": 28,
"text": "Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. When we simply assign dict1 = dict2 it refers to the same dictionary. Let’s discuss a few ways to copy the dictionary from another dictionary.Method#1: Using copy()copy() method returns a shallow copy of the dictionary.It doesn’t take any parameter and return a new dictionary which is not referring to the initial dictionary."
},
{
"code": "# Python3 code to demonstrate# how to copy dictionary# using copy() function # initialising dictionarytest1 = {\"name\" : \"akshat\", \"name1\" : \"manjeet\", \"name2\" : \"vashu\"} # method to copy dictionary using copy() functiontest2 = test1.copy() # updating test2test2[\"name1\"] =\"nikhil\" # print initial dictionaryprint(\"initial dictionary = \", test1) # printing updated dictionaryprint(\"updated dictionary = \", test2)",
"e": 1021,
"s": 598,
"text": null
},
{
"code": null,
"e": 1028,
"s": 1021,
"text": "Output"
},
{
"code": null,
"e": 1186,
"s": 1028,
"text": "initial dictionary = {'name1': 'manjeet', 'name2': 'vashu', 'name': 'akshat'}\nupdated dictionary = {'name1': 'nikhil', 'name': 'akshat', 'name2': 'vashu'}\n"
},
{
"code": null,
"e": 1273,
"s": 1186,
"text": "Method #2: Using dict()The dict() is a constructor which creates dictionary in Python."
},
{
"code": "# Python3 code to demonstrate# how to copy dictionary# using dict() # initialising dictionarytest1 = {\"name\" : \"akshat\", \"name1\" : \"manjeet\", \"name2\" : \"vashu\"} # method to copy dictionary using dicttest2 = dict(test1) # updating test2test2[\"name1\"] =\"nikhil\" # print initial dictionaryprint(\"initial dictionary = \", test1) # printing updated dictionaryprint(\"updated dictionary = \", test2)",
"e": 1675,
"s": 1273,
"text": null
},
{
"code": null,
"e": 1682,
"s": 1675,
"text": "Output"
},
{
"code": null,
"e": 1840,
"s": 1682,
"text": "initial dictionary = {'name2': 'vashu', 'name': 'akshat', 'name1': 'manjeet'}\nupdated dictionary = {'name2': 'vashu', 'name': 'akshat', 'name1': 'nikhil'}\n"
},
{
"code": null,
"e": 1882,
"s": 1840,
"text": "Method#3 : Using Dictionary comprehension"
},
{
"code": "# Python3 code to demonstrate# how to copy dictionary# using dictionary comprehension # initialising dictionarytest1 = {\"name\" : \"akshat\", \"name1\" : \"manjeet\", \"name2\" : \"vashu\"} # method to copy dictionary using dictionary comprehensiontest2 = {k:v for k, v in test1.items()} # updating test2test2[\"name1\"] =\"ayush\" # print initial dictionaryprint(\"initial dictionary = \", test1) # printing updated dictionaryprint(\"updated dictionary = \", test2)",
"e": 2341,
"s": 1882,
"text": null
},
{
"code": null,
"e": 2348,
"s": 2341,
"text": "Output"
},
{
"code": null,
"e": 2505,
"s": 2348,
"text": "initial dictionary = {'name': 'akshat', 'name2': 'vashu', 'name1': 'manjeet'}\nupdated dictionary = {'name': 'akshat', 'name2': 'vashu', 'name1': 'ayush'}\n"
},
{
"code": null,
"e": 2517,
"s": 2505,
"text": "python-dict"
},
{
"code": null,
"e": 2524,
"s": 2517,
"text": "Python"
},
{
"code": null,
"e": 2536,
"s": 2524,
"text": "python-dict"
}
] |
Java Swing | Simple User Registration Form
|
20 Aug, 2021
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, list, color chooser, etc.
In this article, we’ll see how to make a Registration form which includes all the buttons and field in one Form.
Steps:
1. Create a Java file that contains the main class – Registration. This class will only contain the main method to invoke the required methods.
class Registration {
public static void main(String[] args)
throws Exception
{
MyFrame f = new MyFrame();
}
}
2. Create another class MyFrame, which will contain the form.
3. In this MyFrame Class, the methods to be made are:
Components like JLabel, JTextField, JRadioButton, ButtonGroup, JComboBox, and JTextArea. These components will collectively form the Registration form.
A constructor, to initialize the components with default values.
A method actionPerformed() to get the action performed by the user and act accordingly.
4. Copy the code of MyFrame class from below.
5. Save the file as Registration.java
6. Compile the file by using javac command.
javac Registration.java
7. Run the program by calling the main class
java Registration
Below is the code to implement the Simple Registration Form using Java Swing:
Java
// Java program to implement// a Simple Registration Form// using Java Swing import javax.swing.*;import java.awt.*;import java.awt.event.*; class MyFrame extends JFrame implements ActionListener { // Components of the Form private Container c; private JLabel title; private JLabel name; private JTextField tname; private JLabel mno; private JTextField tmno; private JLabel gender; private JRadioButton male; private JRadioButton female; private ButtonGroup gengp; private JLabel dob; private JComboBox date; private JComboBox month; private JComboBox year; private JLabel add; private JTextArea tadd; private JCheckBox term; private JButton sub; private JButton reset; private JTextArea tout; private JLabel res; private JTextArea resadd; private String dates[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }; private String months[] = { "Jan", "feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sup", "Oct", "Nov", "Dec" }; private String years[] = { "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019" }; // constructor, to initialize the components // with default values. public MyFrame() { setTitle("Registration Form"); setBounds(300, 90, 900, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); c = getContentPane(); c.setLayout(null); title = new JLabel("Registration Form"); title.setFont(new Font("Arial", Font.PLAIN, 30)); title.setSize(300, 30); title.setLocation(300, 30); c.add(title); name = new JLabel("Name"); name.setFont(new Font("Arial", Font.PLAIN, 20)); name.setSize(100, 20); name.setLocation(100, 100); c.add(name); tname = new JTextField(); tname.setFont(new Font("Arial", Font.PLAIN, 15)); tname.setSize(190, 20); tname.setLocation(200, 100); c.add(tname); mno = new JLabel("Mobile"); mno.setFont(new Font("Arial", Font.PLAIN, 20)); mno.setSize(100, 20); mno.setLocation(100, 150); c.add(mno); tmno = new JTextField(); tmno.setFont(new Font("Arial", Font.PLAIN, 15)); tmno.setSize(150, 20); tmno.setLocation(200, 150); c.add(tmno); gender = new JLabel("Gender"); gender.setFont(new Font("Arial", Font.PLAIN, 20)); gender.setSize(100, 20); gender.setLocation(100, 200); c.add(gender); male = new JRadioButton("Male"); male.setFont(new Font("Arial", Font.PLAIN, 15)); male.setSelected(true); male.setSize(75, 20); male.setLocation(200, 200); c.add(male); female = new JRadioButton("Female"); female.setFont(new Font("Arial", Font.PLAIN, 15)); female.setSelected(false); female.setSize(80, 20); female.setLocation(275, 200); c.add(female); gengp = new ButtonGroup(); gengp.add(male); gengp.add(female); dob = new JLabel("DOB"); dob.setFont(new Font("Arial", Font.PLAIN, 20)); dob.setSize(100, 20); dob.setLocation(100, 250); c.add(dob); date = new JComboBox(dates); date.setFont(new Font("Arial", Font.PLAIN, 15)); date.setSize(50, 20); date.setLocation(200, 250); c.add(date); month = new JComboBox(months); month.setFont(new Font("Arial", Font.PLAIN, 15)); month.setSize(60, 20); month.setLocation(250, 250); c.add(month); year = new JComboBox(years); year.setFont(new Font("Arial", Font.PLAIN, 15)); year.setSize(60, 20); year.setLocation(320, 250); c.add(year); add = new JLabel("Address"); add.setFont(new Font("Arial", Font.PLAIN, 20)); add.setSize(100, 20); add.setLocation(100, 300); c.add(add); tadd = new JTextArea(); tadd.setFont(new Font("Arial", Font.PLAIN, 15)); tadd.setSize(200, 75); tadd.setLocation(200, 300); tadd.setLineWrap(true); c.add(tadd); term = new JCheckBox("Accept Terms And Conditions."); term.setFont(new Font("Arial", Font.PLAIN, 15)); term.setSize(250, 20); term.setLocation(150, 400); c.add(term); sub = new JButton("Submit"); sub.setFont(new Font("Arial", Font.PLAIN, 15)); sub.setSize(100, 20); sub.setLocation(150, 450); sub.addActionListener(this); c.add(sub); reset = new JButton("Reset"); reset.setFont(new Font("Arial", Font.PLAIN, 15)); reset.setSize(100, 20); reset.setLocation(270, 450); reset.addActionListener(this); c.add(reset); tout = new JTextArea(); tout.setFont(new Font("Arial", Font.PLAIN, 15)); tout.setSize(300, 400); tout.setLocation(500, 100); tout.setLineWrap(true); tout.setEditable(false); c.add(tout); res = new JLabel(""); res.setFont(new Font("Arial", Font.PLAIN, 20)); res.setSize(500, 25); res.setLocation(100, 500); c.add(res); resadd = new JTextArea(); resadd.setFont(new Font("Arial", Font.PLAIN, 15)); resadd.setSize(200, 75); resadd.setLocation(580, 175); resadd.setLineWrap(true); c.add(resadd); setVisible(true); } // method actionPerformed() // to get the action performed // by the user and act accordingly public void actionPerformed(ActionEvent e) { if (e.getSource() == sub) { if (term.isSelected()) { String data1; String data = "Name : " + tname.getText() + "\n" + "Mobile : " + tmno.getText() + "\n"; if (male.isSelected()) data1 = "Gender : Male" + "\n"; else data1 = "Gender : Female" + "\n"; String data2 = "DOB : " + (String)date.getSelectedItem() + "/" + (String)month.getSelectedItem() + "/" + (String)year.getSelectedItem() + "\n"; String data3 = "Address : " + tadd.getText(); tout.setText(data + data1 + data2 + data3); tout.setEditable(false); res.setText("Registration Successfully.."); } else { tout.setText(""); resadd.setText(""); res.setText("Please accept the" + " terms & conditions.."); } } else if (e.getSource() == reset) { String def = ""; tname.setText(def); tadd.setText(def); tmno.setText(def); res.setText(def); tout.setText(def); term.setSelected(false); date.setSelectedIndex(0); month.setSelectedIndex(0); year.setSelectedIndex(0); resadd.setText(def); } }} // Driver Codeclass Registration { public static void main(String[] args) throws Exception { MyFrame f = new MyFrame(); }}
1. Compile:
2. Registration Form unfilled:
3. Registration Form filled:
kalrap615
clintra
java-swing
Java Programs
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
Java program to count the occurrence of each character in a string using Hashmap
How to Iterate HashMap in Java?
SDE SHEET - A Complete Guide for SDE Preparation
Implementing Web Scraping in Python with BeautifulSoup
Working with zip files in Python
XML parsing in Python
Python | Simple GUI calculator using Tkinter
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 506,
"s": 54,
"text": "Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, list, color chooser, etc."
},
{
"code": null,
"e": 619,
"s": 506,
"text": "In this article, we’ll see how to make a Registration form which includes all the buttons and field in one Form."
},
{
"code": null,
"e": 627,
"s": 619,
"text": "Steps: "
},
{
"code": null,
"e": 771,
"s": 627,
"text": "1. Create a Java file that contains the main class – Registration. This class will only contain the main method to invoke the required methods."
},
{
"code": null,
"e": 928,
"s": 771,
"text": "class Registration {\n\n public static void main(String[] args)\n throws Exception\n {\n MyFrame f = new MyFrame();\n }\n}"
},
{
"code": null,
"e": 990,
"s": 928,
"text": "2. Create another class MyFrame, which will contain the form."
},
{
"code": null,
"e": 1044,
"s": 990,
"text": "3. In this MyFrame Class, the methods to be made are:"
},
{
"code": null,
"e": 1196,
"s": 1044,
"text": "Components like JLabel, JTextField, JRadioButton, ButtonGroup, JComboBox, and JTextArea. These components will collectively form the Registration form."
},
{
"code": null,
"e": 1261,
"s": 1196,
"text": "A constructor, to initialize the components with default values."
},
{
"code": null,
"e": 1349,
"s": 1261,
"text": "A method actionPerformed() to get the action performed by the user and act accordingly."
},
{
"code": null,
"e": 1395,
"s": 1349,
"text": "4. Copy the code of MyFrame class from below."
},
{
"code": null,
"e": 1433,
"s": 1395,
"text": "5. Save the file as Registration.java"
},
{
"code": null,
"e": 1477,
"s": 1433,
"text": "6. Compile the file by using javac command."
},
{
"code": null,
"e": 1501,
"s": 1477,
"text": "javac Registration.java"
},
{
"code": null,
"e": 1547,
"s": 1501,
"text": "7. Run the program by calling the main class "
},
{
"code": null,
"e": 1565,
"s": 1547,
"text": "java Registration"
},
{
"code": null,
"e": 1644,
"s": 1565,
"text": "Below is the code to implement the Simple Registration Form using Java Swing: "
},
{
"code": null,
"e": 1649,
"s": 1644,
"text": "Java"
},
{
"code": "// Java program to implement// a Simple Registration Form// using Java Swing import javax.swing.*;import java.awt.*;import java.awt.event.*; class MyFrame extends JFrame implements ActionListener { // Components of the Form private Container c; private JLabel title; private JLabel name; private JTextField tname; private JLabel mno; private JTextField tmno; private JLabel gender; private JRadioButton male; private JRadioButton female; private ButtonGroup gengp; private JLabel dob; private JComboBox date; private JComboBox month; private JComboBox year; private JLabel add; private JTextArea tadd; private JCheckBox term; private JButton sub; private JButton reset; private JTextArea tout; private JLabel res; private JTextArea resadd; private String dates[] = { \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\", \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"30\", \"31\" }; private String months[] = { \"Jan\", \"feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"July\", \"Aug\", \"Sup\", \"Oct\", \"Nov\", \"Dec\" }; private String years[] = { \"1995\", \"1996\", \"1997\", \"1998\", \"1999\", \"2000\", \"2001\", \"2002\", \"2003\", \"2004\", \"2005\", \"2006\", \"2007\", \"2008\", \"2009\", \"2010\", \"2011\", \"2012\", \"2013\", \"2014\", \"2015\", \"2016\", \"2017\", \"2018\", \"2019\" }; // constructor, to initialize the components // with default values. public MyFrame() { setTitle(\"Registration Form\"); setBounds(300, 90, 900, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); c = getContentPane(); c.setLayout(null); title = new JLabel(\"Registration Form\"); title.setFont(new Font(\"Arial\", Font.PLAIN, 30)); title.setSize(300, 30); title.setLocation(300, 30); c.add(title); name = new JLabel(\"Name\"); name.setFont(new Font(\"Arial\", Font.PLAIN, 20)); name.setSize(100, 20); name.setLocation(100, 100); c.add(name); tname = new JTextField(); tname.setFont(new Font(\"Arial\", Font.PLAIN, 15)); tname.setSize(190, 20); tname.setLocation(200, 100); c.add(tname); mno = new JLabel(\"Mobile\"); mno.setFont(new Font(\"Arial\", Font.PLAIN, 20)); mno.setSize(100, 20); mno.setLocation(100, 150); c.add(mno); tmno = new JTextField(); tmno.setFont(new Font(\"Arial\", Font.PLAIN, 15)); tmno.setSize(150, 20); tmno.setLocation(200, 150); c.add(tmno); gender = new JLabel(\"Gender\"); gender.setFont(new Font(\"Arial\", Font.PLAIN, 20)); gender.setSize(100, 20); gender.setLocation(100, 200); c.add(gender); male = new JRadioButton(\"Male\"); male.setFont(new Font(\"Arial\", Font.PLAIN, 15)); male.setSelected(true); male.setSize(75, 20); male.setLocation(200, 200); c.add(male); female = new JRadioButton(\"Female\"); female.setFont(new Font(\"Arial\", Font.PLAIN, 15)); female.setSelected(false); female.setSize(80, 20); female.setLocation(275, 200); c.add(female); gengp = new ButtonGroup(); gengp.add(male); gengp.add(female); dob = new JLabel(\"DOB\"); dob.setFont(new Font(\"Arial\", Font.PLAIN, 20)); dob.setSize(100, 20); dob.setLocation(100, 250); c.add(dob); date = new JComboBox(dates); date.setFont(new Font(\"Arial\", Font.PLAIN, 15)); date.setSize(50, 20); date.setLocation(200, 250); c.add(date); month = new JComboBox(months); month.setFont(new Font(\"Arial\", Font.PLAIN, 15)); month.setSize(60, 20); month.setLocation(250, 250); c.add(month); year = new JComboBox(years); year.setFont(new Font(\"Arial\", Font.PLAIN, 15)); year.setSize(60, 20); year.setLocation(320, 250); c.add(year); add = new JLabel(\"Address\"); add.setFont(new Font(\"Arial\", Font.PLAIN, 20)); add.setSize(100, 20); add.setLocation(100, 300); c.add(add); tadd = new JTextArea(); tadd.setFont(new Font(\"Arial\", Font.PLAIN, 15)); tadd.setSize(200, 75); tadd.setLocation(200, 300); tadd.setLineWrap(true); c.add(tadd); term = new JCheckBox(\"Accept Terms And Conditions.\"); term.setFont(new Font(\"Arial\", Font.PLAIN, 15)); term.setSize(250, 20); term.setLocation(150, 400); c.add(term); sub = new JButton(\"Submit\"); sub.setFont(new Font(\"Arial\", Font.PLAIN, 15)); sub.setSize(100, 20); sub.setLocation(150, 450); sub.addActionListener(this); c.add(sub); reset = new JButton(\"Reset\"); reset.setFont(new Font(\"Arial\", Font.PLAIN, 15)); reset.setSize(100, 20); reset.setLocation(270, 450); reset.addActionListener(this); c.add(reset); tout = new JTextArea(); tout.setFont(new Font(\"Arial\", Font.PLAIN, 15)); tout.setSize(300, 400); tout.setLocation(500, 100); tout.setLineWrap(true); tout.setEditable(false); c.add(tout); res = new JLabel(\"\"); res.setFont(new Font(\"Arial\", Font.PLAIN, 20)); res.setSize(500, 25); res.setLocation(100, 500); c.add(res); resadd = new JTextArea(); resadd.setFont(new Font(\"Arial\", Font.PLAIN, 15)); resadd.setSize(200, 75); resadd.setLocation(580, 175); resadd.setLineWrap(true); c.add(resadd); setVisible(true); } // method actionPerformed() // to get the action performed // by the user and act accordingly public void actionPerformed(ActionEvent e) { if (e.getSource() == sub) { if (term.isSelected()) { String data1; String data = \"Name : \" + tname.getText() + \"\\n\" + \"Mobile : \" + tmno.getText() + \"\\n\"; if (male.isSelected()) data1 = \"Gender : Male\" + \"\\n\"; else data1 = \"Gender : Female\" + \"\\n\"; String data2 = \"DOB : \" + (String)date.getSelectedItem() + \"/\" + (String)month.getSelectedItem() + \"/\" + (String)year.getSelectedItem() + \"\\n\"; String data3 = \"Address : \" + tadd.getText(); tout.setText(data + data1 + data2 + data3); tout.setEditable(false); res.setText(\"Registration Successfully..\"); } else { tout.setText(\"\"); resadd.setText(\"\"); res.setText(\"Please accept the\" + \" terms & conditions..\"); } } else if (e.getSource() == reset) { String def = \"\"; tname.setText(def); tadd.setText(def); tmno.setText(def); res.setText(def); tout.setText(def); term.setSelected(false); date.setSelectedIndex(0); month.setSelectedIndex(0); year.setSelectedIndex(0); resadd.setText(def); } }} // Driver Codeclass Registration { public static void main(String[] args) throws Exception { MyFrame f = new MyFrame(); }}",
"e": 9402,
"s": 1649,
"text": null
},
{
"code": null,
"e": 9415,
"s": 9402,
"text": "1. Compile: "
},
{
"code": null,
"e": 9446,
"s": 9415,
"text": "2. Registration Form unfilled:"
},
{
"code": null,
"e": 9475,
"s": 9446,
"text": "3. Registration Form filled:"
},
{
"code": null,
"e": 9487,
"s": 9477,
"text": "kalrap615"
},
{
"code": null,
"e": 9495,
"s": 9487,
"text": "clintra"
},
{
"code": null,
"e": 9506,
"s": 9495,
"text": "java-swing"
},
{
"code": null,
"e": 9520,
"s": 9506,
"text": "Java Programs"
},
{
"code": null,
"e": 9528,
"s": 9520,
"text": "Project"
},
{
"code": null,
"e": 9626,
"s": 9528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9664,
"s": 9626,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 9721,
"s": 9664,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 9750,
"s": 9721,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 9831,
"s": 9750,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 9863,
"s": 9831,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 9912,
"s": 9863,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 9967,
"s": 9912,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 10000,
"s": 9967,
"text": "Working with zip files in Python"
},
{
"code": null,
"e": 10022,
"s": 10000,
"text": "XML parsing in Python"
}
] |
Using await async in Dart
|
14 Aug, 2020
The async and await approaches in Dart are very similar to other languages, which makes it a comfortable topic to grasp for those who have used this pattern before. However, even if you don’t have experience with asynchronous programming using async/await, you should find it easy to follow along here.
Functions form the base of asynchronous programming. These async functions have async modifiers in their body. Here is an example of a general async function below:
When an async function is called, a Future is immediately returned and the body of the function is executed later. As the body of the async function is executed, the Future returned by the function call will be completed along with its result. In the above example, calling demo() results in the Future.
Any functions you want to run asynchronously need to have the async modifier added to it. This modifier comes right after the function signature, like this:
Dart
void hello() async { print('something exciting is going to happen here...');}
Typically, the function you want to run asynchronously would have some expensive operation in it like file I/O (an API call to a RESTful service).
Await expressions makes you write the asynchronous code almost as if it were synchronous. In general, an await expression has the form as given below:
Dart
void main() async { await hello(); print('all done');}
Typically, it is an asynchronous computation and is expected to evaluate to a Future. The await expressions evaluate the main function, and then suspends the currently running function until the result is ready–that is, until the Future has completed. The result of the await expression is the completion of the Future.
There are two important things to grasp concerning the block of code above. First off, we use the async modifier on the main method because we are going to run the hello() function asynchronously.
Secondly, we place the await modifier directly in front of our asynchronous function. Hence, this is frequently referred to as the async/await pattern.
Just remember, if you are going to use await, make sure that both the caller function and any functions you call within that function all use the async modifier.
Dart is a single-threaded programming language. Future<T> object represents the result of an asynchronous operation which produces a result of type T. If the result is not usable value, then the future’s type is Future<void>. A Future represents a single value either a data or an error asynchronously
There are 2 ways to handle Futures:
Using the Future API
Using the async and await operation.
Now, Let’s write a program and see the output.
Example:
Dart
Future delayedPrint(int seconds, String msg) { final duration = Duration(seconds: seconds); return Future.delayed(duration).then((value) => msg);}main() async { print('Life'); await delayedPrint(2, "Is").then((status){ print(status); }); print('Good');}
Life
Is
Good
In this case, we used async and await keywords. Await basically holds the control flow, until the operation completes. To use await within a function, we have to mark the function by async keyword. Which means, this function is an asynchronous function.
Combined with the Futures class, the async / await pattern in Dart is a powerful and expressive way of doing asynchronous programming.
Dart-Exception-Handling
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ListView Class in Flutter
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Flutter - Pop Up Menu
Android Studio Setup for Flutter Development
What is widgets in Flutter?
Flutter - CircleAvatar Widget
Flutter - RichText Widget
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Aug, 2020"
},
{
"code": null,
"e": 358,
"s": 54,
"text": "The async and await approaches in Dart are very similar to other languages, which makes it a comfortable topic to grasp for those who have used this pattern before. However, even if you don’t have experience with asynchronous programming using async/await, you should find it easy to follow along here. "
},
{
"code": null,
"e": 523,
"s": 358,
"text": "Functions form the base of asynchronous programming. These async functions have async modifiers in their body. Here is an example of a general async function below:"
},
{
"code": null,
"e": 828,
"s": 523,
"text": "When an async function is called, a Future is immediately returned and the body of the function is executed later. As the body of the async function is executed, the Future returned by the function call will be completed along with its result. In the above example, calling demo() results in the Future. "
},
{
"code": null,
"e": 985,
"s": 828,
"text": "Any functions you want to run asynchronously need to have the async modifier added to it. This modifier comes right after the function signature, like this:"
},
{
"code": null,
"e": 990,
"s": 985,
"text": "Dart"
},
{
"code": "void hello() async { print('something exciting is going to happen here...');}",
"e": 1069,
"s": 990,
"text": null
},
{
"code": null,
"e": 1216,
"s": 1069,
"text": "Typically, the function you want to run asynchronously would have some expensive operation in it like file I/O (an API call to a RESTful service)."
},
{
"code": null,
"e": 1367,
"s": 1216,
"text": "Await expressions makes you write the asynchronous code almost as if it were synchronous. In general, an await expression has the form as given below:"
},
{
"code": null,
"e": 1372,
"s": 1367,
"text": "Dart"
},
{
"code": "void main() async { await hello(); print('all done');}",
"e": 1429,
"s": 1372,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1429,
"text": "Typically, it is an asynchronous computation and is expected to evaluate to a Future. The await expressions evaluate the main function, and then suspends the currently running function until the result is ready–that is, until the Future has completed. The result of the await expression is the completion of the Future."
},
{
"code": null,
"e": 1946,
"s": 1749,
"text": "There are two important things to grasp concerning the block of code above. First off, we use the async modifier on the main method because we are going to run the hello() function asynchronously."
},
{
"code": null,
"e": 2098,
"s": 1946,
"text": "Secondly, we place the await modifier directly in front of our asynchronous function. Hence, this is frequently referred to as the async/await pattern."
},
{
"code": null,
"e": 2260,
"s": 2098,
"text": "Just remember, if you are going to use await, make sure that both the caller function and any functions you call within that function all use the async modifier."
},
{
"code": null,
"e": 2562,
"s": 2260,
"text": "Dart is a single-threaded programming language. Future<T> object represents the result of an asynchronous operation which produces a result of type T. If the result is not usable value, then the future’s type is Future<void>. A Future represents a single value either a data or an error asynchronously"
},
{
"code": null,
"e": 2598,
"s": 2562,
"text": "There are 2 ways to handle Futures:"
},
{
"code": null,
"e": 2619,
"s": 2598,
"text": "Using the Future API"
},
{
"code": null,
"e": 2656,
"s": 2619,
"text": "Using the async and await operation."
},
{
"code": null,
"e": 2703,
"s": 2656,
"text": "Now, Let’s write a program and see the output."
},
{
"code": null,
"e": 2712,
"s": 2703,
"text": "Example:"
},
{
"code": null,
"e": 2717,
"s": 2712,
"text": "Dart"
},
{
"code": "Future delayedPrint(int seconds, String msg) { final duration = Duration(seconds: seconds); return Future.delayed(duration).then((value) => msg);}main() async { print('Life'); await delayedPrint(2, \"Is\").then((status){ print(status); }); print('Good');}",
"e": 2980,
"s": 2717,
"text": null
},
{
"code": null,
"e": 2994,
"s": 2980,
"text": "Life\nIs\nGood\n"
},
{
"code": null,
"e": 3248,
"s": 2994,
"text": "In this case, we used async and await keywords. Await basically holds the control flow, until the operation completes. To use await within a function, we have to mark the function by async keyword. Which means, this function is an asynchronous function."
},
{
"code": null,
"e": 3383,
"s": 3248,
"text": "Combined with the Futures class, the async / await pattern in Dart is a powerful and expressive way of doing asynchronous programming."
},
{
"code": null,
"e": 3407,
"s": 3383,
"text": "Dart-Exception-Handling"
},
{
"code": null,
"e": 3412,
"s": 3407,
"text": "Dart"
},
{
"code": null,
"e": 3510,
"s": 3412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3536,
"s": 3510,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 3557,
"s": 3536,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 3575,
"s": 3557,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 3606,
"s": 3575,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 3632,
"s": 3606,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 3654,
"s": 3632,
"text": "Flutter - Pop Up Menu"
},
{
"code": null,
"e": 3699,
"s": 3654,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 3727,
"s": 3699,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 3757,
"s": 3727,
"text": "Flutter - CircleAvatar Widget"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.